zoukankan      html  css  js  c++  java
  • System.Drawing.Image在Save之后Type变了

        前段时间发现asp.net MVC 3附带了一个相当方便的图片处理类WebImage,常用的图片处理功能全都包括进去了,用起来是相当的爽。

        在项目中刚好有相关的图片处理需求,但由于实际项目是使用asp.net 2.0 webform的,只能把WebImage中图片处理的一部分提取出来。使用了一段时间都比较正常,最近发现在把图片进行“调整大小”、“水印”等处理之后,图片的Type都变成PNG了。

        检查了一下,貌似有点关键代码刚好漏掉了,也不想完全照搬WebImage的处理方式,所以在保存文件的时候重新设置了一下ImageCodecInfo。

            private static ImageCodecInfo GetImageEncoder(string imageType)
            {
                imageType = imageType.ToUpperInvariant();
    
                foreach (ImageCodecInfo info in ImageCodecInfo.GetImageEncoders())
                {
                    if (info.FormatDescription == imageType)
                    {
                        return info;
                    }
                }
    
                return null;
            }

    以上代码用于获取具体图片类型的ImageCodecInfo,如BMP, JPEG, GIF, TIFF, PNG。

    在保存的时候调用如下:

        using (EncoderParameters parms = new EncoderParameters(1))
        {
            parms.Param[0] = new EncoderParameter(Encoder.Compression, 40);
            img.Save(file, GetImageEncoder(“JPEG”), parms);
        }

    以上代码对图片进行压缩,再保存为JPEG编码格式,可以根据实际需要进行调整。

    额,发现WebImage这些工具类虽然很好用,但是也容易使人变懒,不过研究一下它们的实现倒是很好的学习方式。

  • 相关阅读:
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    《EffectiveJava中文第二版》 高清PDF下载
    《MoreEffectiveC++中文版》 pdf 下载
    《啊哈c语言》 高清 PDF 下载
  • 原文地址:https://www.cnblogs.com/lwme/p/1909631.html
Copyright © 2011-2022 走看看