使用.Net Framework 4.5压缩图像

时间:2017-04-17 20:36:47

标签: c#

我有下一个代码:

class Program
{
    const string ImagePath = @"C:\mypath\36";
    private const int Quality = 50;

    static void Main()
    {
        Console.WriteLine("Inicio: " + DateTime.Now);    
        var images = Directory.GetFiles(ImagePath);

        foreach (var name in images)
        {
            var bitmap = new Bitmap(name);
            var tname = name.Split('\\')[5].Split('.')[0];
            VariousQuality(bitmap, tname);
        }
        Console.WriteLine("Finalizacion: " + DateTime.Now);
        Console.ReadLine();
    }

    static void VariousQuality(Image original, string name)
    {
        var codecs = ImageCodecInfo.GetImageEncoders();
        var jpgEncoder = codecs.FirstOrDefault(codec => codec.FormatID == ImageFormat.Jpeg.Guid);

        if (jpgEncoder == null) return;

        var encoder = Encoder.Quality;
        var encoderParameters = new EncoderParameters(1);

        var encoderParameter = new EncoderParameter(encoder, Quality);
        encoderParameters.Param[0] = encoderParameter;

        var fileOut = Path.Combine(ImagePath, "__" + name + ".jpg");
        var ms = new FileStream(fileOut, FileMode.Create, FileAccess.Write);
        original.Save(ms, jpgEncoder, encoderParameters);

        ms.Flush();
        ms.Close();

    }

    static void DefaultCompressionPng(Image original)
    {
        var ms = new MemoryStream();
        original.Save(ms, ImageFormat.Png);
        var compressed = new Bitmap(ms);
        ms.Close();

        var fileOutPng = Path.Combine(ImagePath, "default.png");
        compressed.Save(fileOutPng, ImageFormat.Png);
    }

    static void DefaultCompressionJpeg(Image original)
    {
        var ms = new MemoryStream();
        original.Save(ms, ImageFormat.Jpeg);
        var compressed = new Bitmap(ms);
        ms.Close();

        var fileOutPng = Path.Combine(ImagePath, "default.jpg");
        compressed.Save(fileOutPng, ImageFormat.Jpeg);
    }

}

代码正在使用.Net version 4.0,但现在我将代码更新为版本4.5,我收到了下一个错误:

original.Save(ms, jpgEncoder, encoderParameters);
  

未处理的类型' System.ArgumentException'发生在   System.Drawing.dll程序   {System.Collections.ListDictionaryInternal}该参数无效。   System.Drawing.Image.Save(Stream stream,ImageCodecInfo encoder,   EncoderParameters encoderParams)
  ImageCompression.Program.VariousQuality(图像原始,字符串名称   2012 \ Projects \ ImageCompression \ ImageCompression \ Program.cs:第44行

有关如何解决此错误的一些想法?

1 个答案:

答案 0 :(得分:0)

Quality类型更改为long

private const long Quality = 50;

PS

MSDN Encoder.Quality示例:

 myEncoderParameter = new EncoderParameter(myEncoder, 50L);