大家在用 .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 PixelFormat[] indexedPixelFormats = { PixelFormat.Undefined, PixelFormat.DontCare,
PixelFormat.Format16bppArgb1555, PixelFormat.Format1bppIndexed, PixelFormat.Format4bppIndexed,
PixelFormat.Format8bppIndexed
    };

/// <summary>/// 判断图片的PixelFormat 是否在 引发异常的 PixelFormat 之中/// </summary>/// <param name="imgPixelFormat">原图片的PixelFormat</param>/// <returns></returns>private static bool IsPixelFormatIndexed(PixelFormat imgPixelFormat)
{
    foreach (PixelFormat pf in indexedPixelFormats)
    {
        if (pf.Equals(imgPixelFormat)) return true;
    }

return false;
}

//.........使用using (Image img = Image.FromFile("原图片路径"))
{
    //如果原图片是索引像素格式之列的,则需要转换
    if (IsPixelFormatIndexed(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 ,另外之前做测试deno已就绪,有问题或者有需要的可以联系邮箱 penglong@tccwpl.com
 

最新文章

  1. Lua-面向对象中类的构造
  2. python走起之第十二话
  3. ProGuard代码混淆技术详解
  4. Entity Framework 教程
  5. c++ static变量
  6. POJ1947 Rebuilding Roads
  7. [ruby on rails] 跟我学之(9)删除数据
  8. D. Green and Black Tea
  9. CoreGraphics之CGContext绘图
  10. spring 配置触发器 (类似于定时任务)
  11. Strategic game(POJ 1463 树形DP)
  12. bitmap资源回收
  13. [学习笔记]15个QA让你快速入门51单片机开发
  14. [Python][小知识][NO.4] wxPython 字体选择对话框(O.O 不知道放到那里就放到这个分类的)
  15. Hdoj 1007 Quoit Design 题解
  16. HTML汇总以及CSS的一些开端
  17. Chrome浏览器相关细节整理
  18. learning ddr input clock frequency change condition
  19. ROS进阶学习笔记(10)- 搭建自己的Turtlebot(5) - Interactive Makers
  20. java 内存, 类加载g

热门文章

  1. 文件服务器HFS
  2. http网站转换成https网站
  3. Syntax error, parameterized types are only available if source level is 1.5 解决方案
  4. python 线程队列、线程池、全局解释器锁GIL
  5. sftpdrive mtputty
  6. USB知识汇总
  7. Python:Day13
  8. 如何在关闭ssh连接的情况下,让进程继续运行?
  9. 05 python 初学(列表)
  10. 转载 mvc:message-converters简单介绍 https://www.cnblogs.com/liaojie970/p/7736098.html