2012-07-14 73 views
1

我有1個圖片框,1個文本框和3個按鈕的Windows窗體:LoadFromFile,SaveToDB和LoadFromDB。圖片框從文件到BLOB到SQL Server數據庫,然後從數據庫到圖片框

使用LINQ to SQL中的App.config連接,下面的代碼形式:

private void btnLoadFromFile_Click(object sender, EventArgs e) 
{ 
// open file dialog 
OpenFileDialog open = new OpenFileDialog(); 
// image filters 
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp; *.png)|*.jpg; *.jpeg; *.gif; *.bmp; *.png"; 
if (open.ShowDialog() == DialogResult.OK) 
{ 
// display image in picture box 
picBox.Image = new Bitmap(open.FileName); 
// image file path 
textBox1.Text = open.FileName; 
} 
} 

我可以加載圖像和它的路徑形成。

現在我需要將圖片保存到我的表中名爲[BLOBData]的圖像類型字段:tblBLOB (BLOBID, BLOBData)。那麼,將圖片轉換爲圖片類型的代碼是什麼,然後將圖片類型轉換爲圖片並將其顯示在PictureBox控件中的代碼是什麼?

回答

2

Byte Array作爲Blob存儲在DataBase中。一些有用的轉換方法:

public static byte[] ImageToByteArray(Image imageIn) 
{ 
    var ms = new MemoryStream(); 
    imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); 
    return ms.ToArray(); 
} 

public static Image ByteArrayToImage(byte[] byteArrayIn) 
{ 
    var ms = new MemoryStream(byteArrayIn); 
    Image returnImage = Image.FromStream(ms); 
    return returnImage; 
} 

店DB:

OpenFileDialog open = new OpenFileDialog(); 
if (open.ShowDialog() == DialogResult.OK) 
{ 
    // display image in picture box 
    Image img = new Bitmap(open.FileName); 
    picBox.Image = img; 
    // Byte Array that can store as BLOB in DB 
    byte[] blobData = ImageToByteArray(img); 
} 

和負載從DB:

picBox.Image = ByteArrayToImage(/* Byte Array of image from BLOB cell in DB */); 
+0

請我需要在choosen圖像名稱,以取代imageIn OpenFileDialog()和byteArrayIn由表字段內容組成? – 2012-07-14 23:44:08

+0

非常感謝Ria,你的回答非常有幫助。 – 2012-07-15 00:08:35

+0

var qry =(從dc.tblBLOBs中的p選擇p.BLOBData).FirstOrDefault(); picBox.Image = ByteArrayToImage(qry);錯誤:參數1:無法從'System.Data.Linq.Binary'轉換爲'byte []'錯誤:'MyNamespace.FrmPictureBox.ByteArrayToImage(byte [])'的最佳重載方法匹配有一些無效參數 – 2012-07-15 00:30:53