How can I change the background color of an image using GDI+?

20,966

Solution 1

Just use the Graphics object .Clear() method, passing the color you wish to use for the background.

For example:

g.Clear(Color.Blue);

Solution 2

It's simple:

Graphics graph = Graphics.FromImage(bitmap);
graph.Clear(Color.Yellow); // set color for background

Solution 3

If you're talking about a specific file format's "background color" field, I'm not sure if GDI+ supports that, but usually to set the background color of an image you'd fill a rectangle the size of the image with one color.

Example, assuming g is your Graphics object, image is your Image object, and color is your Color object:

g.FillRectangle(new SolidBrush(color), new Rectangle(Point.Empty, image.Size));

Also, as FlipScript suggested, you can use the Clear method. (I had no idea it existed!)

g.Clear(color);
Share:
20,966
user496949
Author by

user496949

Updated on April 07, 2020

Comments

  • user496949
    user496949 about 4 years

    I want to know how to change the background color when I generate the image dynamically.