我还在学习Emgu CV,我需要从包含PNG32数据的字节数组中加载Image。我正在加载图像如下(这是工作示例):
FileStream fs;
Bitmap bitmap;
Image<Rgba, byte> image;
bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
image = new Image<Rgba, byte>(width, height)
{
Bytes = data // data is my byte array
};
if(File.Exists("1.png"))
File.Delete("1.png");
image.Save("1.png");
fs = new FileStream("1.png", FileMode.Open);
bitmap = (Bitmap)Image.FromStream(fs); // this is image what I need
fs.Close();
File.Delete("1.png");
因为,如果我会使用
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
Image<Rgba, byte> image = new Image<Rgba, byte>(width, height)
{
Bytes = data // data is my byte array
};
bitmap = image.Bitmap; // this is image what I need
我的位图背景将为白色,但我的初始图像具有透明背景。
所以,我认为从二进制数据加载Image的方法比我的第一个例子更好,但我不知道。有人可以帮忙吗?
如果您的字节数组是PNG文件中的所有数据,那么图像尺寸和颜色深度都只是该文件标题数据的一部分,您根本不需要做任何特殊操作。你为什么甚至使用那个Image<Rgba, byte>
?你似乎最终想要它作为Bitmap
...所以只需将它直接加载为Bitmap
:
Bitmap bitmap;
using (MemoryStream ms = new MemoryStream(data))
using (Bitmap tmp = new Bitmap(ms))
bitmap = new Bitmap(tmp);
这应该是您需要的唯一代码。最后的new Bitmap(tmp)
将创建一个新的对象,该对象与tmp
附加的流不相关,使得对象可以在没有the previously mentioned issues concerning disposed streams的情况下使用。此外,当从现有的Bitmap
制作新的Bitmap
时,结果将始终为32bpp ARGB。
如果要保留原始颜色深度,可以用new Bitmap(tmp);
替换the CloneImage function I described here。
如果您的文件包含包含透明度的8位PNG文件,则System.Drawing
类会因某种原因将它们转换为32位ARGB。要解决这个问题,请查看this answer I gave to a question on that subject。