[英]How to save PictureBox Image to SQL in VB.NET ( Windows Form )
我需要在其中保存一個表單,用戶瀏覽圖像並將其設置為PictureBox,但是在另一個按鈕上,我需要將該圖像保存到SQL Server。我有一個帶有Insert Command(帶有Image數據類型)的存儲過程。
來自桌面的瀏覽器圖像,PictureBox代碼 :-
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到已知的托管提供程序本機類型不存在映射”。
試試這個:(將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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.