简体   繁体   中英

Emgu CV make transparent background

I'm still learning Emgu CV and I need to load Image from byte array which contains a PNG32 data. I'm loading image as follows (this is working example):

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");

because, if I will use just

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

the background of my bitmap will be white, however my initial image has a transparent background.

So, I think that there is more optimal way to load Image from binary data than in my first example, but I don't know it. Can anyone help?

If your byte array is all the data from the PNG file, then the image dimensions and colour depth are all simply part of that file's header data, and you don't need to do anything special at all. Why are you even using that Image<Rgba, byte> ? You seem to want it as Bitmap in the end... so just load it as Bitmap directly:

Bitmap bitmap;
using (MemoryStream ms = new MemoryStream(data))
using (Bitmap tmp = new Bitmap(ms))
    bitmap = new Bitmap(tmp);

That should be the only code you need. The new Bitmap(tmp) at the end will make a new object that is not tied to the stream that the tmp one is attached to, making the object usable without the previously mentioned issues concerning disposed streams . Additionally, when making a new Bitmap from an existing Bitmap , the result will always be 32bpp ARGB.

If you want to preserve the original colour depth, you can replace the new Bitmap(tmp); by the CloneImage function I described here .

If your files include 8-bit PNG files that contain transparency, the System.Drawing classes will convert them to 32 bit ARGB for some reason. To get around that, look at this answer I gave to a question on that subject .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM