Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting pixel color of BMP/JPG file

I'm trying to set a color of given pixel of the image. Here is the code snippet

        Bitmap myBitmap = new Bitmap(@"c:\file.bmp");

        for (int Xcount = 0; Xcount < myBitmap.Width; Xcount++)
        {
            for (int Ycount = 0; Ycount < myBitmap.Height; Ycount++)
            {
                myBitmap.SetPixel(Xcount, Ycount, Color.Black);
            }
        }

Every time I get the following exception:

Unhandled Exception: System.InvalidOperationException: SetPixel is not supported for images with indexed pixel formats.

The exception is thrown both for bmp and jpg files.

like image 648
Jamie Avatar asked May 15 '10 12:05

Jamie


People also ask

How many bits per pixel per color do a BMP bitmap image uses which matches the resolution of most monitors?

BMP files with 24 bits per pixel are common.

How many colors are in a bitmap image?

Each byte is an index into a table of up to 256 colors. The 16-bit per pixel (16bpp) format supports 65536 distinct colors and stores 1 pixel per 2-byte WORD.


1 Answers

You have to convert the image from indexed to non indexed. Try this code to convert it:

    public Bitmap CreateNonIndexedImage(Image src)
    {
        Bitmap newBmp = new Bitmap(src.Width, src.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        using (Graphics gfx = Graphics.FromImage(newBmp)) {
            gfx.DrawImage(src, 0, 0);
        }

        return newBmp;
    }
like image 149
Oskar Kjellin Avatar answered Oct 10 '22 07:10

Oskar Kjellin