设置BMP / JPG文件的像素颜色在C# [英] Setting pixel color of BMP/JPG file in C#
问题描述
我试图设置图像的特定像素的颜色。
以下是代码段
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);
}
}
每一次我得到了以下异常:
Every time I get the following exception:
未处理的异常: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,那么位图的每个像素的颜色是由一个索引替代的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;
}
这篇关于设置BMP / JPG文件的像素颜色在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!