2015-11-06 109 views
-1

我嘗試從c#app保存圖像時遇到以下錯誤消息。到SQL Server 2008數據庫。將圖像保存到sql server 2008數據庫問題?

請注意,加載工作正常,問題在於保存。

請幫忙??

無法參數值從PictureBox的轉換爲字節[]

代碼保存圖像

private void saveLogo() 
      { 

     SqlConnection conn = new SqlConnection(dbcon.ReturnConnection()); 

      try 
      { 
     SqlCommand sqlCommand1 = conn.CreateCommand(); 
       sqlCommand1.CommandText = "INSERT INTO OrgLogo(ID,LogoName,Picture) values(@ID,@Name,@Picture)"; 

       conn.Open(); 
       if (sqlCommand1.Parameters.Count == 0) 
       {     
        sqlCommand1.Parameters.Add("@ID", System.Data.SqlDbType.Int, 4); 
        sqlCommand1.Parameters.Add("@Name", System.Data.SqlDbType.VarChar, 50); 
        sqlCommand1.Parameters.Add("@Picture", System.Data.SqlDbType.Image); 
       } 
      sqlCommand1.Parameters["@ID"].Value =Convert.ToInt32(editID.Text); 
      sqlCommand1.Parameters["@Name"].Value = editName.Text; 
      sqlCommand1.Parameters["@Picture"].Value = pictureBox1; 

      sqlCommand1.ExecuteNonQuery();    

      } 

      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 

      } 
      finally 
      { 
       conn.Close(); 

      } 
     } 

的代碼來打開圖像文件

protected void LoadLogoPic() 
     { 

      this.openFileDialog2.ShowDialog(); 

      string strFn = this.openFileDialog2.FileName; 
       this.pictureBox1.Image = Image.FromFile(strFn); 
       this.openFileDialog2.Filter = "All Files|*.*|BMP Files|*.bmp|JPG Files|*.jpg"; 
       FileInfo fiImage = new FileInfo(strFn); 
       m_lImageFileLength = fiImage.Length; 
       FileStream fs = new FileStream(strFn, FileMode.Open, FileAccess.Read, FileShare.Read); 
       m_barrImg = new byte[Convert.ToInt32(this.m_lImageFileLength)]; 
       int iBytesRead = fs.Read(m_barrImg, 0, Convert.ToInt32(this.m_lImageFileLength)); 
       fs.Close(); 



     } 
+0

您正試圖存儲* PictureBox控件*而不是圖像的數據。如果將圖像的字節(即'm_barrImg')作爲參數值傳遞,則該語句至少適用於小圖片。對於較大的那個,您必須使用 –

回答

0

試試這個方法;

Image img = picturebox1.Image(); 
byte[] arr; 
ImageConverter converter = new ImageConverter(); 
arr=(byte[])converter.ConvertTo(img, typeof(byte[])); 

command.CommandText = "INSERT INTO ImagesTable (Image) VALUES('" + arr + "')"; 
command.CommandType = CommandType.Text; 
command.ExecuteNonQuery(); 
+1

該語句最終將以'INSERT INTO ImagesTable(Image)VALUES('System.Byte []')'結尾。使用字符串連接*永遠不會解決SQL問題,它只是添加新的,就像在這種情況下一樣。事實上,如果傳遞的是實際的字節數組而不是控制權,則OP的代碼將起作用 –

相關問題