如何编写将 System.Drawing.Bitmap 转换为字节数组的扩展方法?
如何编写将 System.Drawing.Bitmap 转换为字节数组的扩展方法?为什么不呢:
<Extension()> _
Public Function ToByteArray(ByVal image As System.Drawing.Bitmap) As Byte()
Using ms = New MemoryStream()
image.Save(ms, image.RawFormat)
Return ms.ToArray()
End Using
End Function
然而,当我使用它时,我会从 Save() 操作中抛出“System.Runtime.InteropServices.ExternalException:GDI+ 中发生一般错误”。我做错了什么?
How can I write an extension method that converts a System.Drawing.Bitmap to a byte array? Why not:
<Extension()> _
Public Function ToByteArray(ByVal image As System.Drawing.Bitmap) As Byte()
Using ms = New MemoryStream()
image.Save(ms, image.RawFormat)
Return ms.ToArray()
End Using
End Function
Yet when I use that, I get "System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+" thrown from the Save() operation. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如其他人所说,这是一个已知的 GDI+ 错误。
但是,当您在完全读取图像之前关闭图像的源流时,它通常会出现。仅加载新的 Image 对象只会加载元数据,如宽度、高度、颜色深度等,而不是实际的像素。它们将在稍后延迟加载。
可以通过将图像(在加载期间)复制到内存中创建的新图像中来避免这种情况。我认为输入流当时仍然可用。一旦有了新的基于内存的 Image 类,您就可以自由地处理源流。 (另一种解决方案是不关闭/处置源流)。
编辑:
KB814675 位图和图像构造函数依赖项中描述的问题以及解决方法。
As someone else state, this is a known GDI+ bug.
However, it usually appear when you've closed the source stream of the image before reading it completely. Just loading a new Image object will only load metadata, like width, height, color depth, etc, not the actual pixels. They will be lazily loaded at a later time.
This can be avoided by copying your image (during loading) into a new Image created in memory. I presume that the input stream is still available at that time. Once you have the new memory-based Image class you can dispose of the source stream freely. (Another solution would be not to close/dispose the source stream).
Edit:
Problem described in KB814675 Bitmap and Image constructor dependencies together with a workaround.
已知的 GDI+ 错误。
您无法立即关闭
MemoryStream
。将输出数组复制到另一个字节数组,然后关闭流。
Known GDI+ bug.
You can't close the
MemoryStream
straight away.Copy the output array to another byte array, then close the stream.
尝试将
image.RawFormat
更改为 JPEG 或 PNG 等格式。某些图像可能可以通过位图打开但不可保存(至少以原始格式)。Try changing
image.RawFormat
to something like JPEG or PNG. It's possible for some images to be openable by a Bitmap but not saveable (at least in the original format).根据这个线程,我使用以下代码并且它可以正常工作:
According to this thread, I using following code and it work correctly: