设置BMP/JPG文件的像素颜色

9

我正在尝试设置图像中给定像素的颜色。 以下是代码片段:

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

每次我都会收到以下异常:

未处理的异常: System.InvalidOperationException: 对于索引像素格式的图像不支持 SetPixel。

该异常会同时出现在 bmpjpg 文件中。

3个回答

17

您需要将图像从索引色转换为非索引色。尝试使用以下代码进行转换:

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

当我运行这个方法时,会出现内存不足异常。 - talha06

6
请尝试以下操作。
Bitmap myBitmap = new Bitmap(@"c:\file.bmp");
MessageBox.Show(myBitmap.PixelFormat.ToString());

如果您得到了“Format8bppIndexed”,则位图的每个像素的颜色都将被替换为指向256种颜色表中的一个索引,因此每个像素仅用一个字节表示。您可以获得颜色数组:
if (myBitmap.PixelFormat == PixelFormat.Format8bppIndexed) {
    Color[] colorpal = myBitmap.Palette.Entries;
}

1

使用“clone”方法也可以进行相同的转换。

    Bitmap IndexedImage = new Bitmap(imageFile);

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接