Jam*_*mie 9 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);
}
}
Run Code Online (Sandbox Code Playgroud)
每次我收到以下异常:
未处理的异常:System.InvalidOperationException:具有索引像素格式的图像不支持SetPixel.
抛出异常bmp和jpg文件.
Osk*_*lin 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;
}
Run Code Online (Sandbox Code Playgroud)
尝试以下方法
Bitmap myBitmap = new Bitmap(@"c:\file.bmp");
MessageBox.Show(myBitmap.PixelFormat.ToString());
Run Code Online (Sandbox Code Playgroud)
如果你得到"Format8bppIndexed",那么Bitmap的每个像素的颜色将被一个256色的表中的索引替换.因此,每个像素仅由一个字节表示.你可以得到一系列颜色:
if (myBitmap.PixelFormat == PixelFormat.Format8bppIndexed) {
Color[] colorpal = myBitmap.Palette.Entries;
}
Run Code Online (Sandbox Code Playgroud)