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

C#將圖片存放到SQL SERVER資料庫中的方法

本文例項講述了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#程式設計有所幫助。