问题
In this code I'm creating Transparent bitmap but coloring the pixels in the List testpoints in yellow. How can I keep make it Transparent but the pixels to be coloring or keep with the original colors of them instead yellow ?
private void button2_Click(object sender, EventArgs e)
{
Graphics g;
g = Graphics.FromImage(bmpBackClouds);
g.Clear(Color.Transparent);
g.Dispose();
BitmapData b1 = bmpBackClouds.LockBits(new System.Drawing.Rectangle(0, 0,
bmpBackClouds.Width, bmpBackClouds.Height),
System.Drawing.Imaging.ImageLockMode.ReadWrite,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
int stride = b1.Stride;
int i;
System.IntPtr Scan0 = b1.Scan0;
unsafe
{
byte* p;
for (i = 0; i < testpoints.Count; i++)
{
p = (byte*)(void*)Scan0;
p += (int)testpoints[i].Y * stride + (int)testpoints[i].X * 4;
p[1] = p[2] = (byte)255;
p[0] = (byte)0;
p[3] = (byte)255;
}
}
bmpBackClouds.UnlockBits(b1);
bmpBackClouds.Save(@"c:\temp\yellowbmpcolor.png", ImageFormat.Png);
}
回答1:
You code will work fine with a tiny correction:
Delete the part where you delete the image:
Graphics g;
g = Graphics.FromImage(bmpBackClouds);
g.Clear(Color.Transparent);
g.Dispose();
This will wipe out the image and you'll end up with nothing in it.
Then after changing this
p[1] = p[2] = (byte)255;
p[0] = (byte)0;
p[3] = (byte)255;
to that:
p[3] = 0;
the portions in your testpoints list will be transparent, with their color channels intact.
Which is somewhat hard to see ;-)
The best test is to read it back and to restore the alpha channel and voila, the original image is back!
Note In case you wanted to make the whole Bitmap
transparent by those first lines - This doesn't work. There is a bug in GDI
's treatment of transparency; presumably to save time it doesn't preserve the original colors when you try to use it to make part of an image or all of it transparent. This it true both for Graphics.Clear
and for the other Graphics
methods like Graphics.FillRectangle
etc..
..so if you want to clear an image's alpha channel completely, use code like the above to do so, obviously without the list and with loops over all pixels..
来源:https://stackoverflow.com/questions/26082681/write-transparency-to-bitmap-using-unsafe-with-the-original-colors-preserved