1. 程式人生 > >C#將圖片存放到SQL SERVER數據庫中的方法

C#將圖片存放到SQL SERVER數據庫中的方法

獲取 rom binary 圖片 ctu ces 參考 lena span

本文實例講述了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);

希望本文所述對大家的C#程序設計有所幫助。

C#將圖片存放到SQL SERVER數據庫中的方法