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

时间:2010-05-15 12:45:30

标签: c# image-processing

我正在尝试设置图像的给定像素的颜色。 这是代码段

        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 个答案:

答案 0 :(得分: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;
    }

答案 1 :(得分: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;
}

答案 2 :(得分:1)

使用“克隆”方法可以完成相同的转换。

    Bitmap IndexedImage = new Bitmap(imageFile);

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