Search code examples
c#bitmapdrawinggrayscaleargumentexception

'System.ArgumentException' when trying to use SetPixel (x, y, Color)


I am trying to create a white picture (greyscale format).

So here is the code I use:

Bitmap bmp = new Bitmap(1, 1,        
System.Drawing.Imaging.PixelFormat.Format16bppGrayScale);
bmp.SetPixel(0, 0, Color.FromArgb(255, 255, 255));
bmp = new Bitmap(bmp, i.Width, i.Height);

"I" is an existing Bitmap image. I am playing with its channels. The principle is to create a 1 pixel image in greyscale, give this pixel the white color and then enlarge it to the good size.

But I have this as a result:

"An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll"

I tried Color.White but it isn't allowed for greyscale or indexed formats.

What are my other options to fix this?


Solution

  • Why not to do it without converting to greyscale?

    Bitmap A = new Bitmap(i.Width, i.Height);
    for (int x = 0; x < i.Width; x++)
        for (int y = 0; y < i.Height; y++)
        {
            Color C = i.GetPixel(x, y);
            Color WD = Color.FromArgb(C.R, 255, C.G, 0);
            A.SetPixel(x, y, WD);
        }
    

    Simply done by placing colour channels in the desired order