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#程序設計有所幫助。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM