我有一个TcpListener
,它得到了无穷无尽的byte array
。由此,我将byte((转换为MemoryStream,并输入一个PictureBox来显示图像。这工作正常。 如果我将 PictureBox 上的锚点设置为top/right/bottom/left
这意味着图像将在表单展开时展开,然后我实际展开表单,则会出现以下错误:
An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll
Additional information: Parameter is not valid.
也
The application is in break mode
法典
' Enter the listening loop.
While True
Dim client As TcpClient = Await server.AcceptTcpClientAsync()
Dim stream As NetworkStream = client.GetStream
Dim MS As New MemoryStream
Await stream.CopyToAsync(MS)
Await ViewImage(MS)
client.Close()
End While
查看图像功能:
Public Async Function ViewImage(ms As MemoryStream) As Task
Try
Dim myimage As Bitmap
myimage = New Bitmap(ms)
PictureBox1.Image = myimage
PictureBox1.Refresh()
myimage.Dispose()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Function
请注意,我的代码中没有捕获异常。有什么想法吗?
此问题很可能与您在ViewImage()
方法结束时释放myimage
有关。
这:
PictureBox1.Image = myimage
...
myimage.Dispose()
使myimage
和PictureBox1.Image
指向同一个Bitmap
对象。位图是引用类型(类(,这意味着当您将其分配给不同的变量时,您只是传递它们的引用指针。
因此,当您处置myimage
时,您正在处置PictureBox
中显示的相同图像,当GDI+尝试重绘它的拉伸版本时,这可能会导致您的错误(事实上,一旦您处置了原始图像,甚至不应该显示原始图像(。
有关详细信息,请参阅:值类型和引用类型 - Microsoft文档。
引用类型和值类型如何工作的基本示例
参考类型:
Dim A As New Bitmap("image.bmp")
Dim B As Bitmap = A 'Points to A.
PictureBox1.Image = A 'Points to A.
PictureBox2.Image = B 'Still points to A.
'Calling Dispose() on any of the above will result in none of them having an image since you will ultimately dispose bitmap A.
值类型:
Dim A As Integer = 3
Dim B As Integer = A 'Copy of A.
Dim C As Integer = B 'Copy of B.
C = 4 'Results in A = 3, B = 3, C = 4.