索引图像上的图形

问题描述 投票:25回答:3

我收到错误:

“无法从具有索引像素格式的图像创建图形对象。”

在功能:

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();
}

我想问你,我该如何解决?

c# image graphics indexed-image
3个回答
31
投票

参考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;

4
投票

最简单的方法是创建一个这样的新图像:

Bitmap EditableImg = new Bitmap(IndexedImg);

它创建一个与原始内容完全相同的新图像及其所有内容。


1
投票

总的来说,如果你想使用索引图像并实际保留它们的颜色深度和调色板,这将始终意味着为它们编写显式检查和特殊代码。 Graphics根本无法使用它们,因为它操纵颜色,索引图像的实际像素不包含颜色,只包含索引。

对于那些年后仍然看到这一点的人来说......将图像绘制到现有(8位)索引图像上的有效方法是:

  • 遍历要粘贴的图像的所有像素,并为每种颜色find the closest match on the target image's colour palette,并将其索引保存为字节数组。
  • 使用LockBits打开索引图像的后备字节数组,并通过使用高度和图像步幅循环相关索引,将匹配的字节粘贴到所需位置。

这不是一件容易的事,但它肯定是可能的。如果粘贴的图像也被索引,并且包含超过256个像素,则可以通过在调色板上而不是在实际图像数据上进行颜色匹配来加速处理,然后从其他索引图像获取后备字节,并重新映射他们使用创建的映射。

请注意,所有这些仅适用于8位。如果您的图像是四位或一位,最简单的处理方法是首先将其转换为8位,这样您就可以将其作为每像素一个字节处理,然后将其转换回来。

有关更多信息,请参阅How can I work with 1-bit and 4-bit images?

© www.soinside.com 2019 - 2024. All rights reserved.