直接上代碼 1 public static class ImageCompress 2 { 3 /// <summary> 4 /// 圖片壓縮 5 /// </summary> 6 /// <param name="imagePath">圖片文件路徑</param> 7 /// <param na ...
直接上代碼
1 public static class ImageCompress 2 { 3 /// <summary> 4 /// 圖片壓縮 5 /// </summary> 6 /// <param name="imagePath">圖片文件路徑</param> 7 /// <param name="targetFolder">保存文件夾</param> 8 /// <param name="quality">壓縮質量</param> 9 /// <param name="fileSuffix">壓縮後的文件名尾碼(防止直接覆蓋原文件)</param> 10 public static void CompressionImage(string imagePath, string targetFolder, long quality = 100, string fileSuffix = "compress") 11 { 12 if (!File.Exists(imagePath)) 13 { 14 throw new FileNotFoundException(); 15 } 16 if (!Directory.Exists(targetFolder)) 17 { 18 Directory.CreateDirectory(targetFolder); 19 } 20 var fileInfo = new FileInfo(imagePath); 21 var fileName = fileInfo.Name.Replace(fileInfo.Extension, ""); 22 var fileFullName = Path.Combine($"{targetFolder}", $"{fileName}_{fileSuffix}{fileInfo.Extension}"); 23 24 var imageByte = CompressionImage(imagePath, quality); 25 var ms = new MemoryStream(imageByte); 26 var image = Image.FromStream(ms); 27 image.Save(fileFullName); 28 ms.Close(); 29 ms.Dispose(); 30 image.Dispose(); 31 } 32 private static byte[] CompressionImage(string imagePath, long quality) 33 { 34 using (var fileStream = new FileStream(imagePath, FileMode.Open)) 35 { 36 using (var img =Image.FromStream(fileStream)) 37 { 38 using (var bitmap = new Bitmap(img)) 39 { 40 var codecInfo = GetEncoder(img.RawFormat); 41 var myEncoder = Encoder.Quality; 42 var myEncoderParameters = new EncoderParameters(1); 43 var myEncoderParameter = new EncoderParameter(myEncoder, quality); 44 myEncoderParameters.Param[0] = myEncoderParameter; 45 using (var ms = new MemoryStream()) 46 { 47 bitmap.Save(ms, codecInfo, myEncoderParameters); 48 myEncoderParameters.Dispose(); 49 myEncoderParameter.Dispose(); 50 return ms.ToArray(); 51 } 52 } 53 } 54 } 55 } 56 57 private static ImageCodecInfo GetEncoder(ImageFormat format) 58 { 59 var codecs = ImageCodecInfo.GetImageDecoders(); 60 return codecs.FirstOrDefault(codec => codec.FormatID == format.Guid); 61 } 62 }
調用方法(WPF為例)
private void Button_Click(object sender, RoutedEventArgs e) { var fileDialog = new OpenFileDialog(); var fileSelect = ""; if (fileDialog.ShowDialog(this)==true) { fileSelect = fileDialog.FileName; } if(string.IsNullOrWhiteSpace(fileSelect)) return; ImageCompress.CompressionImage(fileSelect,@"d:\",50); }