将位图转换为字节数组
使用 C#,是否有比保存到临时文件并使用 FileStream
读取结果更好的方法将 Windows Bitmap
转换为 byte[]
代码>?
Using C#, is there a better way to convert a Windows Bitmap
to a byte[]
than saving to a temporary file and reading the result using a FileStream
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
有几种方法。
ImageConverter
这个很方便,因为它不需要大量代码。
内存流
这与您正在做的事情等效,只不过文件保存到内存而不是磁盘。尽管您可以选择 ImageFormat 更多代码,并且可以在保存到内存或磁盘之间轻松修改它。
来源:http://www.vcskicks.com/image-to-byte.php
There are a couple ways.
ImageConverter
This one is convenient because it doesn't require a lot of code.
Memory Stream
This one is equivalent to what you are doing, except the file is saved to memory instead of to disk. Although more code you have the option of ImageFormat and it can be easily modified between saving to memory or disk.
Source: http://www.vcskicks.com/image-to-byte.php
MemoryStream 对此很有帮助。您可以将其放入扩展方法中:
您可以像这样使用它:
我部分不同意 prestomanifto 关于 ImageConverter 的回答。 不要使用 ImageConverter。它在技术上没有任何问题,但它使用对象装箱/拆箱这一事实告诉我,它的代码来自 .NET 框架的旧黑暗地方,并且它并不理想与图像处理一起使用(至少转换为 byte[] 是多余的),特别是当您考虑以下情况时。
我查看了 .Net 框架使用的 ImageConverter 代码,它内部使用的代码与我上面提供的代码几乎相同。它创建一个新的
MemoryStream
,以您提供时的任何格式保存Bitmap
,并返回数组。使用MemoryStream
跳过创建ImageConverter
类的额外开销A MemoryStream can be helpful for this. You could put it in an extension method:
You could just use it like:
I partially disagree with prestomanifto's answer in regards to the ImageConverter. Do not use ImageConverter. There's nothing technically wrong with it, but simply the fact that it uses boxing/unboxing from object tells me it's code from the old dark places of the .NET framework and its not ideal to use with image processing (it's overkill for converting to a byte[] at least), especially when you consider the following.
I took a look at the
ImageConverter
code used by the .Net framework, and internally it uses code almost identical to the one I provided above. It creates a newMemoryStream
, saves theBitmap
in whatever format it was in when you provided it, and returns the array. Skip the extra overhead of creating anImageConverter
class by usingMemoryStream
您也可以只 Marshal.Copy 位图数据。没有中间内存流等以及快速内存复制。这应该适用于 24 位和 32 位位图。
。
You can also just Marshal.Copy the bitmap data. No intermediary memorystream etc. and a fast memory copy. This should work on both 24-bit and 32-bit bitmaps.
.
将图像保存到 MemoryStream,然后获取字节数组。
http://msdn.microsoft.com/en-us/library/ms142148.aspx
Save the Image to a MemoryStream and then grab the byte array.
http://msdn.microsoft.com/en-us/library/ms142148.aspx
使用
MemoryStream
而不是FileStream
,如下所示:Use a
MemoryStream
instead of aFileStream
, like this:更简单:
More simple:
请尝试以下操作:
确保您正在使用:
Try the following:
Make sure you are using:
我相信你可能会简单地这样做:
I believe you may simply do:
非常简单,只需在一行中使用它:
Very simple use this just in one line: