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


    大家在用 .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("图片路径")  

    为了避免此问题的发生,我们在做水印之前,可以先判断原图片是否是索引像素格式的,如果是,则可以采用将此图片先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进行水印操作
        }
    }
  • 相关阅读:
    WAMP 2.2 配置与IIS共用单IP,多域名多网站配置方法
    [.NET MVC4 入门系列00]目录
    [.NET MVC4 入门系列04]Controller和View间交互原理
    [.NET MVC4 入门系列05]添加自定义查询页Search
    [.NET MVC4 入门系列02]MVC Movie 为项目添加Model
    [.NET MVC4 入门系列07] 在Model模型模块中添加验证
    [.NET MVC4 入门系列03]使用Controller访问Model中数据
    DateTime 类常用技巧
    Access 注意地方
    互联网公司老板的十大谎言,别对号入座
  • 原文地址:https://www.cnblogs.com/tianma3798/p/4520152.html
Copyright © 2020-2023  润新知