2012-02-02 95 views
0

我需要保存一個窗體用戶瀏覽圖像&將其設置爲PictureBox但在另一個按鈕上,我需要將該圖像保存到SQL Server。存儲過程用INSERT命令(image數據類型)從桌面如何在VB.NET(Windows窗體)中將PictureBox圖像保存到SQL

瀏覽圖片,圖片框代碼: -

Public Sub SelectImage() 

     With OpenFileDialog1 
      '.InitialDirectory = "C:\" 
      .Filter = "All Files|*.*|Bitmaps|*.bmp|GIFs|*.gif|JPEGs|*.jpg" 
      .FilterIndex = 4 
     End With 

     If OpenFileDialog1.ShowDialog() = DialogResult.OK Then 
      PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName) 
      PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage 
      PictureBox1.BorderStyle = BorderStyle.Fixed3D 

     End If 
    End Sub 

保存按鈕代碼

Public Sub Insert_Update_Personal() 
     Dim UploadImage As Bitmap = PictureBox1.Image 

     Dim ds As DataSet = New DataSet() 
     Dim cmd As SqlCommand = New SqlCommand("sp_Insert_Update_Personal", con) 
     con.Open() 
     cmd.CommandType = CommandType.StoredProcedure 

     cmd.Parameters.AddWithValue("@childrenage", TextBox10.Text) 
     cmd.Parameters.AddWithValue("@picture", UploadImage) 
     cmd.Parameters.AddWithValue("@hrcomments", TextBox5.Text) 

     cmd.ExecuteNonQuery() 
     con.Close() 
     cmd.Dispose() 
    End Sub 

但是當我運行表單時,它給了我錯誤「沒有映射存在從對象類型System.Drawing.Bitmap到已知的託管提供程序本機類型」。

+0

你需要在將圖像推入數據庫之前將圖像轉換爲字節數組。 – 2012-02-02 14:28:24

+0

此外,從原始圖像,而不是從PictureBox。 – Alexander 2013-07-02 05:54:29

回答

1

試試這個:(變化的MySqlConnection到的SQLConnection因爲我在我的例子使用MySQL)

Public Shared Function ByteToImage(ByVal blob() As Byte) As Bitmap 
     Dim mStream As New MemoryStream 
     Dim pData() As Byte = DirectCast(blob, Byte()) 
     mStream.Write(pData, 0, Convert.ToInt32(pData.Length)) 
     Dim bm As Bitmap = New Bitmap(mStream, False) 
     mStream.Dispose() 
     Return bm 
    End Function 

然後使用它是這樣的:

Private Function InsertImage(ByVal ImagePath As String, ByVal oIDNum As String) As Boolean 
    Dim iPhoto() As Byte = jwImage.FileImageToByte(ImagePath) 
    Dim xBool As Boolean = False 
    Using xConn As New MySqlConnection(ConnectionClass.ConnectionString) 
     Try 
      Dim xComm As New MySqlCommand 
      With xComm 
       .CommandText = "InsertImage" 
       .Connection = xConn 
       .CommandType = CommandType.StoredProcedure 

       .Parameters.AddWithValue("xID", oIDNum) 
       .Parameters.AddWithValue("xImage", iPhoto) 
      End With 

      xConn.Open() 
      xComm.ExecuteNonQuery() 
      xComm.Dispose() 
      xBool = True 
     Catch ex As MySqlException 
      MessageBox.Show(ex.Message, "MySQL Error: " & ex.Number, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) 
      xBool = False 
     End Try 
    End Using 

    Return xBool 
End Function 
+0

嗨,感謝您只是想知道什麼是「jwImage」是一個PictureBox ID? – Pankaj 2012-02-02 21:18:11

+0

你可以請解釋這一行Dim iPhoto()As Byte = jwImage.FileImageToByte(ImagePath) 此外,當我將這個函數稱爲「ByteToImage」 – Pankaj 2012-02-02 21:55:49

+0

@Pankaj jwImage是一個類的名稱。如名稱所示,FileImageToByte將圖像轉換爲字節數組。 – 2012-02-02 23:28:47

相關問題