Home > Programming > Add background color to PNG files in C#.

Add background color to PNG files in C#.

January 15th, 2010 Jimmy Leave a comment Go to comments

This code snippet will let you force a background color into a PNG file with C#. When working with PNG files in Visual Studio sometimes you’ll run into situations where the background of a PNG shows up as grey or even blue. This is because of the PNG files transparency and Windows can sometimes get confused as what to do for background color, especially when pasting a PNG file into a Wordpad document.

To use the code all you have to do is pass an Image object that you have created either from a file or a pictureBox control. Pass the height, width and the Color you want for the background color and the function will fill on the fly. This function has no return type because it’s modifying the image with the Graphics class which modify’s the image in memory as is. If you pass the Image from a pictureBox control you won’t have to pass the Image object back to the pictureBox control to have it update, it will be updated using the referenced Image object.

    private void addBgToPng(Image img,int xWidth, int xHeight,Color color)
        {
            Image imgOrig = (Image)img.Clone();
            Graphics g = Graphics.FromImage(img);
            Rectangle bgImg = new Rectangle(0, 0, xWidth, xHeight);
            SolidBrush bgBrush = new SolidBrush(color);
            g.FillRectangle(bgBrush, bgImg);
            g.DrawImage(imgOrig, new Point(0, 0));
            bgBrush.Dispose();
         }
Digg: DIGG ME
  1. No comments yet.
  1. No trackbacks yet.