Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
531 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...