C#中的PNG图像问题

时间:2009-10-26 14:33:27

标签: c# image graphics png

在Visual Studio 2008中工作。我正在尝试绘制PNG图像并再次保存该图像。

我执行以下操作:

private Image img = Image.FromFile("file.png");
private Graphics newGraphics;

在构造函数中:

newGraphics = Graphics.FromImage(img);

构建解决方案不会出错。当我尝试运行它时,我明白了:

  

无法创建Graphics对象   来自具有索引的图像   像素格式。

我在C#中使用图像的经验不多。这意味着什么,我该如何解决这个问题?

编辑:通过调试,Visual Studio告诉我该图片具有 format8bppindexed 像素格式。

因此,如果我不能使用Graphics类,我该使用什么?

EDIT2:在阅读this之后,我认为可以安全地假设我在使用GDI +时更好地坚持使用JPG文件,不是吗?

EDIT3:我的使用陈述:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

2 个答案:

答案 0 :(得分:12)

您无法使用索引图像格式(PNG,GIF,...)创建图形。 您应该使用位图(文件或将图像转换为位图)。

Image img = Image.FromFile("file.png");
img = new Bitmap(img);
newGraphics = Graphics.FromImage(img);

答案 1 :(得分:9)

如果没有更好的支持索引PNG的PNG库,那么你很难尝试绘制到该图像,因为显然GDI +图形对象不支持索引图像。

如果您不需要使用索引PNG,则可以捕获该错误并使用第三方实用程序将输入转换为常规RGB PNG。

编辑:

我确实找到了这个链接http://fci-h.blogspot.com/2008/02/c-indexed-pixel-problem.html,它提供了一种在图像上绘制的方法,但它不会影响原始图像,只需要一个可以保存()的副本(如果需要)。

如果链接出现故障:

Bitmap bm = (Bitmap) System.Drawing.Image.FromFile("Fci-h.jpg",true);
Bitmap tmp=new Bitmap (bm.Width ,bm.Height );
Graphics grPhoto = Graphics.FromImage(tmp);
grPhoto.DrawImage(bm, new Rectangle(0, 0, tmp.Width , tmp.Height ), 0, 0, tmp.Width , tmp.Height , GraphicsUnit.Pixel);