开发者

Setting pixel color of BMP/JPG file

开发者 https://www.devze.com 2022-12-30 22:56 出处:网络
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\");

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开发者_StackOverflow社区 exception is thrown both for bmp and jpg files.


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


try the following

Bitmap myBitmap = new Bitmap(@"c:\file.bmp");
MessageBox.Show(myBitmap.PixelFormat.ToString());

If you get "Format8bppIndexed" then the color of each pixel of the Bitmap is replaced by an index into a table of 256 Colors. and therefor each pixel is represented by only one byte. you can get an array of colors:

if (myBitmap.PixelFormat == PixelFormat.Format8bppIndexed) {
    Color[] colorpal = myBitmap.Palette.Entries;
}


The same conversion can be done using "clone" method.

    Bitmap IndexedImage = new Bitmap(imageFile);

    Bitmap bitmap = IndexedImage.Clone(new Rectangle(0, 0, IndexedImage.Width, IndexedImage.Height), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
0

精彩评论

暂无评论...
验证码 换一张
取 消