Search code examples
c#pngsystem.drawingsystem.drawing.imaging

Programmatically replace transparent regions in an image with white fill?


I've got a PNG image that I'm operating on via the System.Drawing API in .NET. It has large transparent regions, and I would like to replace the transparent regions with white fill--so that there are no transparent regions in the image. Easy enough in an image editing program... but so far I've had no success doing this in C#.

Can someone give me some pointers?


Solution

  • I'm not sure how to detect transparent pixel. I know if the Alpha is 0 it's completly transparent and if it's 255 it's opaque. I'm not sure if you should check for Alpha == 0 or Alpha != 255 ; if you can try it and give me a feedback that would be helpful.

    From MSDN

    The alpha component specifies the transparency of the color: 0 is fully transparent, and 255 is fully opaque. Likewise, an A value of 255 represents an opaque color. An A value from 1 through 254 represents a semitransparent color. The color becomes more opaque as A approaches 255.

        void  Foo(Bitmap image)
        {
            for (int y = 0; y < image.Height; ++y)
            {
                for (int x = 0; x < image.Width; ++x)
                {
                    // not very sure about the condition.                   
                    if (image.GetPixel(x, y).A != 255)
                    {
                        image.SetPixel(x,y,Color.White);
                    }
                }
            }
    
        }