索引图像上的图形

Kri*_*ers 25 c# graphics image indexed-image

我收到错误:

"无法从具有索引像素格式的图像创建图形对象."

在功能:

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();
}
Run Code Online (Sandbox Code Playgroud)

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

Mic*_* DN 33

参考这个,它可以通过创建一个具有相同尺寸的空白位图和正确的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;
Run Code Online (Sandbox Code Playgroud)

  • 但它不会写在原始图像上.它将创建一个空白图像,并将在其上写.所以最后数据不会写在原始图像上. (5认同)
  • 这个代码需要跟随更多的代码,在图形对象上绘制原始图像,如"Dim rect As New System.Drawing.Rectangle(0,0,bm.width,bm.height)":g.DrawImage(bm, rect,0,0,bm.width,bm.Height,GraphicsUnit.Pixel)` (4认同)
  • 唯一有效的原因是它使新图像具有高色彩。这实际上不允许您在 8 位图像上绘图... (3认同)
  • 不幸的是,正如所指出的,这不允许在具有原始色彩空间的原始图像上使用图形。因此,如果您有单色 (1bpp) 高分辨率图像(例如 70k x 40k 像素),则内存大小将爆增...... (2认同)

小智 6

最简单的方法是创建一个新图像,如下所示:

Bitmap EditableImg = new Bitmap(IndexedImg);
Run Code Online (Sandbox Code Playgroud)

它会创建一个与原始图像完全相同的新图像。

  • “及其所有内容”......除了原始调色板。这将创建一个 32bppARGB 图像。它实际上不允许编辑 8 位图像。 (3认同)