Why does System.Drawing.Graphics blank the RGB channels when Alpha==0?

烂漫一生 提交于 2019-12-21 19:46:51

问题


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.



来源:https://stackoverflow.com/questions/25236422/why-does-system-drawing-graphics-blank-the-rgb-channels-when-alpha-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!