本文實例講述了C#將圖片存放到SQL SERVER數據庫中的方法。分享給大家供大家參考。具體如下:
第一步:
//獲取當前選擇的圖片this.pictureBox1.Image = Image.FromStream(this.openFileDialog1.OpenFile());//獲取當前圖片的路徑string path = openFileDialog1.FileName.ToString();//將制定路徑的圖片添加到FileStream類中 FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);//通過FileStream對象實例化BinaryReader對象BinaryReader br = new BinaryReader(fs);//通過BinaryReader類對象的ReadBytes()方法將FileStream類對象轉化為二進制數組byte[] imgBytesIn = br.ReadBytes(Convert.ToInt32(fs.Length));
第二步:
//將圖片添加到數據庫中string sql="insert into pic values(@pic)";
SqlParameter[] param = new SqlParameter[] { new SqlParameter("@pic", imgBytesIn) };DBHelper.GetExecuteQuery(sql, param);
第三步:
//將圖片從數據庫中取出string sql="select * from pic where id=0";SqlDataReader reader = DBHelper.GetExecuteReader(sql, null);MemoryStream mss = null;if (reader.Read()){
byte[] bytes = (byte[])reader["pic"];
mss = new MemoryStream(bytes);}this.pictureBox2.Image = Image.FromStream(mss);