将位图转换为二进制数组性能
我确实有一个包含超过 500 个位图对象的位图数组。我需要将数组中的每个位图对象转换为二进制数组。我正在使用 MemoryStream 类来实现此目的:
using (MemoryStream ms = new MemoryStream())
{
images[0].Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
byte[] byteData = ms.ToArray();
}
我想知道是否还有其他方法可以实现此目的。我不确定这个过程有多昂贵。
谢谢
I do have a Bitmap Array that contains more than 500 Bitmaps object. I need to convert each single Bitmap object within the Array into a binary Array. I'm using the MemoryStream class to achieve this:
using (MemoryStream ms = new MemoryStream())
{
images[0].Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
byte[] byteData = ms.ToArray();
}
I would like to know if there is other way to achieve this. I'm not sure how expensive is this process.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我做了一些速度测试,转换为 ImageFormat.Bmp 是最快的。它不需要进行任何压缩。不过,最佳格式还取决于您之后打算如何处理数据。
还值得考虑的是位图最初是从哪里来的。如果您从文件中加载它们,则可能值得进行切换并首先读取文件数据,然后从中创建位图对象。
I've done some speed tests and converting to ImageFormat.Bmp is the fastest. It doesn't need to do any compression. Though the best format will also depend on what you plan to do with the data after that.
It's also worth considering where the Bitmaps came from in the first place. If you're loading them in from a file it may be worth it to switch things around and read the file data in first, then create your Bitmap objects from it after that.
通过选择 Gif,您正在进行 CPU/内存权衡,而您很可能不希望这样做。具体来说,相对于使用 BMP,Gif 会更小,但需要一些时间来压缩(除非图像已经采用该格式)。
如果您复制这些内容足够多,以至于出现内存带宽问题(并且无法解决该问题),那么这是一个好主意,但否则您应该坚持使用 BMP。但实际上,对于 500 张图像,我预计最多需要 1-2 秒,因此您可能不需要担心这种微观优化。如果花费很长时间,您可以转向非托管代码,这可能会表现得更好,因为您可以更好地控制内存分配和副本。
By choosing Gif you are making a CPU/memory trade off which you most likely don't want. Specifically the Gif is going to be smaller but is going to take some time to compress (unless the images are already in the format) relative to using a BMP.
If you are copying these around enough that you have memory bandwidth issues (and can't fix that) this is a good idea, but otherwise you should stick with BMP. Really though, for 500 images I would expect this to take 1-2 seconds at the most so you probably don't need to worry about this sort of micro optimization. If its taking to long you can move to unmanaged code which will likely perform better because you will have finer control over memory allocations and copies.