2017-04-17 57 views
2

我有下面的代碼:使用.NET Framework進行圖像壓縮4.5

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); 

An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll {System.Collections.ListDictionaryInternal} The parameter is invalid. System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
ImageCompression.Program.VariousQuality(Image original, String name 2012\Projects\ImageCompression\ImageCompression\Program.cs:line 44

關於如何解決此錯誤的想法?

回答

0

更改Quality類型爲long

private const long Quality = 50; 

PS

MSDN Encoder.Quality例如:

myEncoderParameter = new EncoderParameter(myEncoder, 50L);