1. 程式人生 > >【轉載】C#將圖片以二進制流的方式存入數據庫

【轉載】C#將圖片以二進制流的方式存入數據庫

nbsp pan his HERE acc ddb 獲取 特殊 圖像

在C#開發應用程序的過程中,圖片一般會存放在文件系統中,當然圖片也可以二進制的方式存放到數據庫中,不過一般不建議存放在數據庫中,因為圖片占用的空間還是挺大的,特殊情況下可以考慮將圖片存在數據。此文將介紹如何將圖片存放在Sqlserver數據庫中,並從數據庫中讀取出圖片信息。

在將圖片存儲到數據庫之前,需要先設計數據庫表,建議使用sqlserver的數據類型Image類型存儲數據,當然也有人使用二進制binary類型存儲。

一、將圖片寫入數據庫中的方法

在此方法中使用到FileStream類,該類在此的作用是將圖片讀取到文件流中。具體實現方法如下:

 public void WriteImgToDb()
{
  SqlConnection conn
=new SqlConnection("server=.;database=pubs;trusted_connection=Yes"); conn.Open(); SqlCommand scmd = null; string Path = Application.StartupPath + "//Imgren"; //為獲取文件的根目錄 int j = 0; FileStream fs=null; for (int i = 1; i <= 13; i++) //利用循環添加一次添加圖片 { string sql = "insert into tb_Image values(@a,@b)
"; //利用參數實現圖片添加 scmd = new SqlCommand(sql, scon); scmd.Parameters.Add("@a", SqlDbType.Int); scmd.Parameters["@a"].Value = i; //記住該方法,將值存入參數內 byte[] bt = new byte[10240]; //初始化圖片大小 //創建圖片寫入流 fs = new FileStream(Path + "//" + i + ".bmp", FileMode.OpenOrCreate, FileAccess.Read); fs.Read(bt,
0, bt.Length); //讀取圖片的字節數 scmd.Parameters.Add("@b", SqlDbType.Image, (int)fs.Length); scmd.Parameters["@b"].Value = bt; //將圖片的字節數存入參數內 j = scmd.ExecuteNonQuery(); } if (j > 0) MessageBox.Show("將圖片寫入數據庫成功!!!", "友好提示"); else MessageBox.Show("將圖片寫入數據庫失敗!!!", "友好提示"); fs.Close(); //關閉釋放流資源 }

二、將從數據庫中讀取圖片到picturebox控件中(WinForm窗體控件)。

此方法使用了MemoryStream類即內存流對象,同時使用了Image類,Image類是.NET Framework內部提供的圖片相關類。從Sqlserver數據庫中讀取圖片數據具體實現方法如下:

public void ReadDbImage()
{
  SqlConnection conn=new SqlConnection("server=.;database=pubs;trusted_connection=Yes"); 
     conn.Open(); 
     SqlCommand scmd = null; 
     string sql = "select I_image from tb_image where I_id=" +int.Parse(textBox1.Text.Trim()) + ""; 
     scmd = new SqlCommand(sql, scon); 
     SqlDataReader red = scmd.ExecuteReader(); 
     if (red.Read()) 
     { 
       //創建支持存儲區的內存流 
        MemoryStream ms = new MemoryStream((byte[])red[0]); 
        Image img = Image.FromStream(ms, true); //該方法: FromStream()為驗證圖像的流 
        this.pictureBox1.Image = img; 
     } 
     red.Close(); //關閉資源 
}

擴展閱讀:C#工具類:使用SharpZipLib進行壓縮、解壓文件、微軟官方提供的Sqlserver數據庫操作幫助類SQLHelper類。

備註:原文轉載自C#將圖片以二進制流的方式存入數據庫_IT技術小趣屋。

【轉載】C#將圖片以二進制流的方式存入數據庫