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

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

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

每次我收到以下exception:

未处理的exception:System.InvalidOperationException:具有索引像素格式的图像不支持SetPixel。

bmpjpg文件都抛出exception。

尝试以下方法

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

如果你得到“Format8bppIndexed”,那么Bitmap的每个像素的颜色将被一个256色的表中的索引替换。 因此,每个像素仅由一个字节表示。 你可以获得一系列颜色:

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

您必须将图像从索引转换为非索引。 试试这段代码来转换它:

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

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

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