我收到错误:
“无法从具有索引像素格式的图像创建图形对象。”
在功能:
public static void AdjustImage(ImageAttributes imageAttributes, Image image)
{
Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
Graphics g = Graphics.FromImage(image);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttributes);
g.Dispose();
}
我想问你,我该如何解决?
参考this,它可以通过创建一个具有相同尺寸的空白位图和正确的PixelFormat以及该位图上的绘图来解决。
// The original bitmap with the wrong pixel format.
// You can check the pixel format with originalBmp.PixelFormat
Bitmap originalBmp = new (Bitmap)Image.FromFile("YourFileName.gif");
// Create a blank bitmap with the same dimensions
Bitmap tempBitmap = new Bitmap(originalBmp.Width, originalBmp.Height);
// From this bitmap, the graphics can be obtained, because it has the right PixelFormat
using(Graphics g = Graphics.FromImage(tempBitmap))
{
// Draw the original bitmap onto the graphics of the new bitmap
g.DrawImage(originalBmp, 0, 0);
// Use g to do whatever you like
g.DrawLine(...);
}
// Use tempBitmap as you would have used originalBmp
return tempBitmap;
最简单的方法是创建一个这样的新图像:
Bitmap EditableImg = new Bitmap(IndexedImg);
它创建一个与原始内容完全相同的新图像及其所有内容。
总的来说,如果你想使用索引图像并实际保留它们的颜色深度和调色板,这将始终意味着为它们编写显式检查和特殊代码。 Graphics
根本无法使用它们,因为它操纵颜色,索引图像的实际像素不包含颜色,只包含索引。
对于那些年后仍然看到这一点的人来说......将图像绘制到现有(8位)索引图像上的有效方法是:
这不是一件容易的事,但它肯定是可能的。如果粘贴的图像也被索引,并且包含超过256个像素,则可以通过在调色板上而不是在实际图像数据上进行颜色匹配来加速处理,然后从其他索引图像获取后备字节,并重新映射他们使用创建的映射。
请注意,所有这些仅适用于8位。如果您的图像是四位或一位,最简单的处理方法是首先将其转换为8位,这样您就可以将其作为每像素一个字节处理,然后将其转换回来。