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

大家在用 .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/

转载于:https://www.cnblogs.com/sjcatsoft/archive/2008/12/19/1358630.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值