无法从带有索引像素格式的图像创建graphics对象

15 篇文章 0 订阅
大家在用 .NET 做图片水印功能的时候, 很可能会遇到 “无法从带有索引像素格式的图像创建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, 我们可以看到如下的提示信息:


通过上面的错误解释,我们可以看到,原因是因为图片是索引像素格式的。为了避免此问题的发生,我们在做水印之前,可以先判断原图片是否是索引像素格式的,如果是,则可以采用将此图片先clone到一张BMP上的方法来解决:

        /// <summary> 带索引的,会产生graphics异常的PixelFormat
        /// </summary>
        private static readonly HashSet<PixelFormat> indexedPixelFormats = new HashSet<PixelFormat>
        {
            PixelFormat.Undefined, PixelFormat.DontCare,
            PixelFormat.Format16bppArgb1555, PixelFormat.Format1bppIndexed, 
            PixelFormat.Format4bppIndexed,PixelFormat.Format8bppIndexed
        };

            //.........使用
            using (Image img = Image.FromFile("原图片路径"))
            {
                //如果原图片是索引像素格式之列的,则需要转换
                if (indexedPixelFormats.Contains(img.PixelFormat))
                {
                    Bitmap bmp = new Bitmap(img.Width, img.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(img, 0, 0);
                    }
                    //下面的水印操作,就直接对 bmp 进行了
                    //......
                }
                else //否则直接操作
                {
                    //直接对img进行水印操作
                }
            }


转自: http://www.cnblogs.com/qixuejia/archive/2010/09/03/1817248.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值