Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fill a bitmap with a solid color?

Tags:

c#

image

bitmap

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.

like image 904
Salvador Avatar asked Nov 12 '09 05:11

Salvador


3 Answers

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);
}
like image 189
Jeromy Irvine Avatar answered Oct 20 '22 08:10

Jeromy Irvine


Bitmap bmp = new Bitmap(width, height);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.Green);
like image 43
Sam Saarian Avatar answered Oct 20 '22 08:10

Sam Saarian


It depends on what you are trying to accomplish, but usually you would use GDI+ by getting a graphics object and then drawing to it:

Graphics g = Graphics.FromImage(bitmap); 

Its actually a big subject, here are some beginner tutorials: GDI+ Tutorials

Here is a snippet from the tutorial on drawing a rectangle with a gradient fill.

Rectangle rect = new Rectangle(50, 30, 100, 100); 
LinearGradientBrush lBrush = new LinearGradientBrush(rect, Color.Red, Color.Yellow, LinearGradientMode.BackwardDiagonal); 
g.FillRectangle(lBrush, rect); 
like image 6
Ryan Cook Avatar answered Oct 20 '22 08:10

Ryan Cook