设置BMP / JPG文件的像素颜色
问题描述:
我正在尝试设置图像的给定像素的颜色。
以下是代码段
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);
}
}
每次我收到以下异常:
未处理的异常:System.InvalidOperationException:对于具有索引像素格式的图像,SetPixel不支持
。
Unhandled Exception: System.InvalidOperationException: SetPixel is not supported for images with indexed pixel formats.
bmp
和 jpg
文件都抛出异常。
答
尝试以下
Bitmap myBitmap = new Bitmap(@"c:\file.bmp");
MessageBox.Show(myBitmap.PixelFormat.ToString());
如果你得到Format8bppIndexed,那么Bitmap的每个像素的颜色都被一个索引替换成256色的表。
因此每个像素仅由一个字节表示。
你可以获得一系列颜色:
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;
}