0
我在窗體中有一個按鈕和一個datagridview。我需要從數據庫獲取圖像並在datagrid中顯示其值,然後獲取數據網格中圖像的值以將其複製到另一個數據庫。在將圖像從數據庫轉換爲字節並返回到圖像時出現問題
具體來說,我正在將database1的table1中的圖像(blob)複製到database2的表1中。
的button1_Click:
Dim img As Image
Dim bArr As Byte()
Try
Dim Sql = "Select ID, IMG from sample"
connectionOnline()
Dim cmd = New MySqlCommand(Sql, ConOnline)
Dim dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
DataGridView1.Rows.Clear()
While dr.Read = True
img = dr(1)
bArr = imgToByteArray(img)
DataGridView1.Rows.Add(dr(0), bArr)
End While
ConOnline.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Try
connectionSync()
Dim a, b As String
Dim Sql = "INSERT INTO SAMPLE (ID, IMG)values(@a,@b)"
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
a = Me.DataGridView1.Rows(i).Cells(0).Value.ToString()
Dim img1 As Image = byteArrayToImage(bArr)
Dim cmd As New MySqlCommand(Sql, ConSync)
cmd.Parameters.AddWithValue("@a", a)
cmd.Parameters.AddWithValue("@b", img1)
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
Next
ConSync.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Try
connectionSync()
Dim Sql = "INSERT INTO B.SAMPLE(ID, IMG) SELECT ID, IMG FROM C.SAMPLE WHERE not exists (SELECT 1 from B.SAMPLE WHERE B.SAMPLE.ID=C.SAMPLE.ID)"
Dim cmd = New MySqlCommand(Sql, ConSync)
With cmd
.ExecuteNonQuery()
End With
MsgBox("Success", vbInformation, "Save")
ConSync.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Try
connectionOffline()
Dim Sql = "UPDATE SAMPLE SET IMG=(SELECT C.SAMPLE.NAME FROM C.SAMPLE WHERE C.SAMPLE.ID=B.SAMPLE.ID) WHERE B.SAMPLE.ID=(SELECT C.SAMPLE.ID FROM C.SAMPLE WHERE C.SAMPLE.ID=B.SAMPLE.ID)"
Dim cmd = New MySqlCommand(Sql, ConOffline)
With cmd
.ExecuteNonQuery()
End With
MsgBox("Success")
ConOffline.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
下面B和C是數據庫
雖然樣品是表
爲i用於將圖像轉換功能
Public Function imgToByteArray(ByVal img As Image) As Byte()
Using mStream As New MemoryStream()
img.Save(mStream, img.RawFormat)
Return mStream.ToArray()
End Using
End Function
Public Function byteArrayToImage(ByVal byteArrayIn As Byte()) As Image
Using mStream As New MemoryStream(byteArrayIn)
Return Image.FromStream(mStream)
End Using
End Function
結果(在數據庫中; IMG)只顯示:「System.Drawing.Bitmap」而不是實際圖像
可我知道什麼是your.value =巴爾?另外,我得到一個「無法投射'System.Byte []'類型的對象來輸入'Sytem.Drawing.Image'。」錯誤:( –
無論如何,我刪除'b = Me.DataGridView1.Rows(i).Cells(1).Value.ToString()'在我的代碼,因爲我在'cmd.Parameters.AddWithValue(「 @b「,img1)'不是b –
@MiharuChan更多的信息在回答 – Caveman