2010-05-15 55 views
8

我试图设置图像给定像素的颜色。 这里是代码片段设置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); 
      } 
     } 

每次我得到以下异常:

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

的例外是bmpjpg文件抛出两者。

回答

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

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

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

运行此方法时出现“内存不足”异常 – talha06 2016-07-12 11:13:31

1

相同的转换是可以做到用“克隆”的方法。

Bitmap IndexedImage = new Bitmap(imageFile); 

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

无法降低颜色格式(从32到8bpp) – Pedro77 2012-04-25 16:21:08