42

It's embarrassing to ask this question but can't find an answer.

I tried this in vain.

Image resultImage = new Bitmap(image1.Width, image1.Height, PixelFormat.Format24bppRgb);

using (Graphics grp = Graphics.FromImage(resultImage)) 
{
    grp.FillRectangle(
        Brushes.White, 0, 0, image1.Width, image1.Height);
    resultImage = new Bitmap(image1.Width, image1.Height, grp);
}

I basically want to fill a 1024x1024 RGB bitmap image with white in C#. How can I do that?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Tae-Sung Shin
  • 20,215
  • 33
  • 138
  • 240

5 Answers5

46

You almost had it:

private Bitmap DrawFilledRectangle(int x, int y)
{
    Bitmap bmp = new Bitmap(x, y);
    using (Graphics graph = Graphics.FromImage(bmp))
    {
        Rectangle ImageSize = new Rectangle(0,0,x,y);
        graph.FillRectangle(Brushes.White, ImageSize);
    }
    return bmp;
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Lee Harrison
  • 2,306
  • 21
  • 32
35

You are assigning a new image to resultImage, thereby overwriting your previous attempt at creating a white image (which should succeed, by the way).

So just remove the line

resultImage = new Bitmap(image1.Width, image1.Height, grp);
Joey
  • 344,408
  • 85
  • 689
  • 683
23

Another approach,

Create a unit bitmap

var b = new Bitmap(1, 1);
b.SetPixel(0, 0, Color.White);

And scale it

var result = new Bitmap(b, 1024, 1024);
prashanth
  • 2,059
  • 12
  • 13
  • 1
    I like this approach! Thanks! – NoWar Nov 24 '14 at 12:54
  • 4
    Careful! When you use `Color.FromArgb()` you will get a gradient when scaling the bitmap. Better use the [solution](http://stackoverflow.com/a/12502497/489772) from @LeeHarrison. – Jan Feb 16 '15 at 20:32
5

Graphics.Clear(Color)

Bitmap bmp = new Bitmap(1024, 1024);
using (Graphics g = Graphics.FromImage(bmp)){g.Clear(Color.White);}
Top Systems
  • 951
  • 12
  • 24
1

Depending on your needs, a BitmapSource might suit. You can quickly fill a byte array with the 0xff (i.e. white) using Enumerable.Repeat().

int w = 1024;
int h = 1024;
byte[] pix = Enumerable.Repeat((byte)0xff, w * h * 4).ToArray();
SomeImage.Source = BitmapSource.Create(w, h, 96, 96, PixelFormats.Pbgra32, null, pix, w * 4);
xtempore
  • 5,260
  • 4
  • 36
  • 43