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

大家在用 .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, 我们可以看到如下的提示信息:

为了避免此问题的发生,可以采用将此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/
posted @ 2008-12-19 18:31  三角猫  阅读(900)  评论(0编辑  收藏  举报