我正在努力:
1)扫描图像并将其插入内存流。
2)在picturebox1中显示。
3)将picturebox1图像读入内存流并将其保存到oledb。
这是我的代码:
1st)通过WIA Dialog扫描并将图像插入memorystream,然后在picturebox1中显示:
Try
Dim CD As New WIA.CommonDialog
Dim F As WIA.ImageFile = CD.ShowAcquireImage(WIA.WiaDeviceType.ScannerDeviceType)
If F IsNot Nothing Then
Dim MStream As IO.MemoryStream = Nothing
Try
'Convert the raw scanner output into a byte array
Dim ImageBytes() As Byte = DirectCast(F.FileData.BinaryData, Byte())
'Read the image data bytes into a MemoryStream
MStream = New IO.MemoryStream(ImageBytes)
PictureBox1.Image = System.Drawing.Image.FromStream(MStream)
Catch ex As Exception
MsgBox("An error occurred: " & ex.Message, MsgBoxStyle.Critical)
End Try
If MStream IsNot Nothing Then MStream.Dispose()
End If
Catch ex As Exception
MsgBox(ex.message, MsgBoxStyle.Critical)
End Try
这很完美。
问题即将来临,
2nd)将picturebox1中的图像读入新的内存流,然后将其保存到oledb:
If conn.State = ConnectionState.Closed Then
conn.ConnectionString = connstring
conn.Open()
'Reading image from picturebox1 and then insert it to a new memorystream.
Dim arrImage() As Byte
Dim myMs As New IO.MemoryStream
PictureBox1.Image.Save(myMs, System.Drawing.Imaging.ImageFormat.Jpeg)
arrImage = myMs.GetBuffer
'Now save image to oledb from the memorystream.
Dim query As String = "INSERT INTO Guestinfo ([IDImage]) VALUES (@IDImage)"
Dim command As New OleDbCommand
With command
.CommandText = query
.Parameters.Add("@IDImage", OleDb.OleDbType.Binary).Value = arrImage
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("Saved Successfully!", MsgBoxStyle.Information)
conn.Close()
ListView1.Items.Clear()
loadlistview()
Me.Close()
End If
错误在这一行:
PictureBox1.Image.Save(myMs, System.Drawing.Imaging.ImageFormat.Jpeg)
我可能会看到这个错误,因为在扫描过程中我们将图像转换为字节数组以将其放入内存流中,但在阅读过程中,我们试图将图片框图像作为Jpeg读入内存流。
我可以看到,作为Visualbasic的初学者,我的任何帮助都会受到赞赏。
答案 0 :(得分:2)
根据Image.FromStream
的文档,流必须在Image
的生命周期内保持打开状态,但您要在此行中处理流:
If MStream IsNot Nothing Then MStream.Dispose()
尝试从第一个代码块中删除该行。
我认为MemoryStream
应该在某个时候被处理掉,但是PictureBox
和Image
类可能会为你处理。{1}}和Dispose
类。否则,您可能必须在表单关闭时添加{{1}}调用。