C# 向SQL數據庫中存儲圖片的方法

向數據庫中存儲圖片的方法有兩種:

1.將圖片轉換成二進制的形式存儲到數據庫

2.將圖片的路徑存儲到數據庫中,用時通過路徑找到圖片

下面分別介紹這兩種方法

1.將圖片轉換成二進制形式存儲

首先,在sql數據庫中建立一個表,有兩個字段:ID、Image,其中ID爲主鍵,Image的存儲類型爲Image類型。

單擊button1按鈕,實現圖片存儲:

private void button1_Click(object sender, EventArgs e)
        {
            
            openFileDialog1.Filter="*.jpg|*.JPG";//設置彈出對話框選擇圖片
            openFileDialog1.ShowDialog();
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string path = openFileDialog1.FileName;
                using (FileStream filestream = new FileStream(path, FileMode.Open))
                {
                    Byte[] imageByte = new byte[filestream.Length];
                    filestream.Read(imageByte,0,imageByte.Length);//將圖片數據讀入比特數組存儲
                    string connectionstring = "Data Source=(local);Initial Catalog=Test;Integrated Security=SSPI";
                    SqlConnection sqlcon = new SqlConnection(connectionstring);
                    sqlcon.Open();
                    SqlCommand sqlcom = new SqlCommand("insert into Image(ID,Image) values (1,@ImageList)",sqlcon);//此處設置一個佔位符ImageList,含義將在以下定義
                    sqlcom.Parameters.Add("ImageList",SqlDbType.Image);
                    sqlcom.Parameters["ImageList"].Value = imageByte;
                    sqlcom.ExecuteNonQuery();
                    sqlcon.Close();
                }
            }
            
        }

單擊button2按鈕,實現圖片的提取:

private void button2_Click(object sender, EventArgs e)
        {
            string connectionstring = "Data Source=(local);Initial Catalog=Test;Integrated Security=SSPI";
            SqlConnection sqlcon = new SqlConnection(connectionstring);
            sqlcon.Open();
            byte[] imagebytes;
            SqlCommand sqlcom = new SqlCommand("select Image from Image where ID=1",sqlcon);//查詢到要提取的圖片
            SqlDataReader dr = sqlcom.ExecuteReader();
            if (dr.Read())
            {
                imagebytes = (byte[])dr["Image"];
                MemoryStream ms = new MemoryStream(imagebytes);//創建圖片數據流
                Bitmap bmap = new Bitmap(ms);//獲取圖片
                ms.Close();
                pictureBox1.Image = bmap;
            }
        }

2.路徑存取法

這個簡單,只要把圖片的路徑轉換成字符串,存儲到數據庫中,使用時將字符串提取出來,將其賦值給pictureBox的URL或ImageLocation屬性即可。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章