大家在用 .NET 做图片水印功能的时候, 如果原图片是GIF格式, 很可能会遇到 “无法从带有索引像素格式的图像创建graphics对象”这个错误,对应的英文错误提示是“A Graphics object cannot be created from an image that has an indexed pixel format"

这个exception是出现在 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage("图片路径")  

这个调用的语句上,通过查询 MSDN, 我们可以看到如下的提示信息:

(转载)无法从带有索引像素格式的图像创建graphics对象|A Graphics object cannot be created from an image that has an indexed pixel format

为了避免此问题的发生,可以采用将此GIF图片先clone到一张BMP上的方法来解决:

using (Image sourceImage = Image.FromFile("原图片路径"))
{
////判断原图片是否是GIF图片
if (sourceImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif))
{
Bitmap bmp = new Bitmap(sourceImage.Width, sourceImage.Height, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(bmp))
{
////提高图片质量
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(sourceImage, 0, 0);
}

////现在的 bmp就代替了原来的gif图片,下面的操做,就全部针对这个 bmp 进行就是了
}
}

经过上面的转换, 就可以避免因图片的索引信息而引发异常了。

原文:http://www.zu14.cn/2008/12/19/net_gif_index_error/

相关文章:

  • 2021-12-18
  • 2021-12-04
  • 2022-12-23
  • 2021-09-21
  • 2022-02-13
  • 2022-12-23
  • 2022-01-12
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-06-22
  • 2021-07-14
  • 2021-08-23
  • 2022-02-04
  • 2021-09-28
相关资源
相似解决方案