When I am writing a Bitmap to a file and read from the file, I am getting the transparency correctly.
using (Bitmap bmp = new Bitmap(2, 2))
{
Color col = Color.FromArgb(1, 2, 3, 4);
bmp.SetPixel(0, 0, col);
bmp.Save("J.bmp");
}
using (Bitmap bmp = new Bitmap("J.bmp"))
{
Color col = bmp.GetPixel(0, 0);
// Value of col.A = 1. This is right.
}
But if I write the Bitmap to a MemoryStream and read from that MemoryStream, the transparency has been removed. All alpha values become 255.
MemoryStream ms = new MemoryStream();
using (Bitmap bmp = new Bitmap(2, 2))
{
Color col = Color.FromArgb(1, 2, 3, 4);
bmp.SetPixel(0, 0, col);
bmp.Save(ms, ImageFormat.Bmp);
}
using (Bitmap bmp = new Bitmap(ms))
{
Color col = bmp.GetPixel(0, 0);
// Value of col.A = 255. Why? I am expecting 1 here.
}
I wish to save the Bitmap to a MemoryStream and read it back with transparency. How can I resolve this issue?
The problem is this line:
bmp.Save(ms, ImageFormat.Bmp). ImageFormat.Bmp does not support alpha values, you can change it to ImageFormat.Png for the same effect.