2011-08-12 148 views
2

我有一個圖片框。圖片框中的圖像是靜態的。我正在從資源文件夾加載圖像。我無法從圖片框中讀取靜態圖像並將其存儲在數據庫中。這是我的代碼。將picturebox圖像存儲到數據庫

private void btnOk_Click(object sender, EventArgs e) 
    { 
     Image votingBackgroundImage = pictureBox5.Image; 
     Bitmap votingBackgroundBitmap = new Bitmap(votingBackgroundImage); 
     Image votingImage = (Image)votingBackgroundBitmap; 
      var maxheight = (votingImage.Height * 3) + 2; 
      var maxwidth = votingImage.Width * 2; 
      if (maxheight == 227 && maxwidth == 720) 
      { 

       System.IO.MemoryStream defaultImageStream = new System.IO.MemoryStream(); 
       Bitmap NewImage =new Bitmap(votingImage,new Size(720,227)); 
       Image b = (Image)NewImage; 
        b.Save(defaultImageStream, System.Drawing.Imaging.ImageFormat.Bmp); 
       defaultImageData = new byte[defaultImageStream.Length]; 
       } 
    } 

查詢我用來增加圖像中的數據庫:

  String MyString1=string.format("insert into question_table(background_image) Values(@background_image)"); 
      com = new SqlCommand(MyString1, myConnection); 
       com.Parameters.Add("@background_image", SqlDbType.Image).Value = defaultImageData; 
       com.ExecuteNonQuery(); 

當我在database.It存儲值0 x000000的sql查詢此...

回答

1

你只是創建byte[]但你從來沒有真正複製的內容

嘗試

System.IO.MemoryStream defaultImageStream = new System.IO.MemoryStream(); 
Bitmap NewImage =new Bitmap(votingImage,new Size(720,227)); 
Image b = (Image)NewImage; 
b.Save(defaultImageStream, System.Drawing.Imaging.ImageFormat.Bmp); 
defaultImageData = new byte[defaultImageStream.Length]; 
//assign byte array the content of image 
defaultImageData = defaultImageStream .ToArray(); 
0

它看起來像是在分配一個字節數組來存儲你的流的內容,但是你不會複製這些內容本身。可能你不需要中間數組。嘗試使用的MemoryStreamToArray()方法:

b.Save(defaultImageStream, System.Drawing.Imaging.ImageFormat.Bmp); 
// ... 
com.Parameters.Add("@background_image", SqlDbType.Image).Value 
    = defaultImageStream.ToArray(); 
0

你必須把它保存爲一個斑點即字節陣列。