How do I fill a bitmap with a solid color?

Salvador picture Salvador · Nov 12, 2009 · Viewed 70.8k times · Source

I need to create a 24-bit bitmap (resolution 100x100 pixels) using a unique RGB color and save the generated image to the disk. I currently use the SetPixel function, but it is extremely slow.

Bitmap Bmp = new Bitmap(width, height);
//...
//...
Bmp.SetPixel(x,y,Color.FromARGB(redvalue, greenvalue, bluevalue));

Is there a faster method than SetPixel? Thanks in advance.

Answer

Jeromy Irvine picture Jeromy Irvine · Nov 12, 2009

This should do what you need it to. It will fill the entire bitmap with the specified color.

Bitmap Bmp = new Bitmap(width, height);
using (Graphics gfx = Graphics.FromImage(Bmp))
using (SolidBrush brush = new SolidBrush(Color.FromArgb(redvalue, greenvalue, bluevalue)))
{
    gfx.FillRectangle(brush, 0, 0, width, height);
}