Why does System.Drawing.Graphics blank the RGB cha

2019-04-11 22:22发布

问题:

This has become a serious blocker for a program I'm working on to manipulate images that have Alpha channels. Many of the images I have contain color information where an Alpha channel is completely transparent, and yet as soon as I try to load them into System.Drawing.Graphics, it changes anything with of Alpha of 0, into Black with an Alpha of 0.

Here is a basic sample of the issue. I have looked around trying to find a reason, answer, or workaround, but I haven't found anything that even alludes to this issue. Any help would be appreciated at this point.

var myTestTransparentColor = Color.FromArgb(0, 255, 128, 64);
var image = new Bitmap(135, 135, PixelFormat.Format32bppArgb);

using (var g = Graphics.FromImage(image))
{
    g.Clear(myTestTransparentColor);
}

var color = image.GetPixel(0, 0);

Debug.Assert(color == myTestTransparentColor, "channels must match original");

EDIT:

After further testing I don't really see a way ahead by using System.Drawing.Graphics, so my only solution which is not really an answer, is to avoid System.Drawing.Graphics entirely. Looking through my code, it looks like I can avoid it. Its just after years of using System.Drawing.Graphics for drawing shapes, planting text over images, I find it irritating for System.Drawing.Graphics to have a significant drawback like this.

I still would like to know if I can use System.Drawing.Graphics and keep my ARGB intact, but I guess I can live without it for now.

回答1:

I think Vincent Povirk has answered my question appropriately here: Drawing PixelFormat32bppPARGB images with GDI+ uses conventional formula instead of premultiplied one

"The format of your foreground image doesn't matter (given that it has alpha) because you're setting it to a Gdiplus::Color. Color values are defined as non-premultiplied, so gdiplus multiplies the components by the alpha value when it clears the foreground image. The alternative would be for Color values to have different meaning depending on the format of the render target, and that way lies madness."

"If you really want this level of control over the rendering, you'll have to lock the bitmap bits and do it yourself."

So, I am doing it myself.