将图像保存到内存流错误

Saving Image into memory stream Error

我正在尝试:

1) 扫描图像并将其插入内存流。

2) 在图片框1中显示。

3) 将picturebox1图片读入memorystream并保存到oledb

这是我的代码:

1st) 通过 WIA Dialog 扫描并将图像插入内存流,然后在 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 的初学者,我可以看出这对我来说很复杂,我们将不胜感激。

根据 Image.FromStream 的文档,流必须在 Image 的生命周期内保持打开状态,但您要在这一行中处理流:

If MStream IsNot Nothing Then MStream.Dispose()

尝试从您的第一个代码块中删除该行。

我想 MemoryStream 应该在某个时候处理掉,但也许 PictureBoxImage 类 会为您处理。否则,您可能必须在关闭表单时添加一个 Dispose 调用。