【问题标题】:Problem with PNG images in C#C#中PNG图像的问题
【发布时间】:2010-12-10 03:46:15
【问题描述】:

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

我执行以下操作:

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

在构造函数中:

newGraphics = Graphics.FromImage(img);

构建解决方案不会出错。当我尝试运行它时,我得到了这个:

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

我没有太多在 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;

【问题讨论】:

  • 这个方法好运吗? c-sharpcorner.com/UploadFile/rrraman/…
  • 我一直使用带有 Graphics 对象的 PNG 文件。发布您正在使用的 PNG 文件的链接,我们会看看它有什么问题。
  • 在内部 GDI 与位图一起使用,JPG 是压缩的,使用压缩图像处理原始数据并不是很好。您的图像是 8bppIndexed,这是一种位图格式,其中颜色存储在调色板中,而不是像素数据。 Graphics 对象不能直接修改像素值,因为这不会改变它。您需要将其转换为 24bppRGB

标签: c# image graphics png


【解决方案1】:

如果没有更好的支持索引 PNG 的 PNG 库,您在尝试绘制该图像时会很不走运,因为显然 GDI+ 图形对象不支持索引图像。

如果您不需要使用索引 PNG,您可以捕获该错误并使用 3rd 方实用程序将您的输入转换为常规 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);

【讨论】:

【解决方案2】:

您不能从索引图像格式(PNG、GIF、...)创建图形。 您应该使用位图(文件或将您的图像转换为位图)。

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

【讨论】:

猜你喜欢
  • 2010-10-17
  • 2019-08-01
  • 1970-01-01
  • 2011-02-05
  • 2015-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多