直接上代码
1 public static class ImageCompress 2 { 3 /// <summary> 4 /// 图片压缩 5 </summary> 6 <param name="imagePath">图片文件路径</param> 7 <param name="targetFolder">保存文件夹 8 <param name="quality">压缩质量 9 <param name="fileSuffix">压缩后的文件名后缀(防止直接覆盖原文件)10 void CompressionImage(string imagePath,string targetFolder,1)">long quality = 100,1)">string fileSuffix = "compress") 11 { 12 if (!File.Exists(imagePath)) 13 { 14 throw new FileNotFoundException(); 15 } 16 Directory.Exists(targetFolder)) 17 18 Directory.CreateDirectory(targetFolder); 19 20 var fileInfo = 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 = MemoryStream(imageByte); 26 var image = Image.FromStream(ms); 27 image.Save(fileFullName); 28 ms.Close(); 29 ms.Dispose(); 30 image.Dispose(); 31 } 32 private byte[] CompressionImage(long quality) 33 34 using (var fileStream = FileStream(imagePath,FileMode.Open)) 35 36 var img =Image.FromStream(fileStream)) 37 { 38 var bitmap = Bitmap(img)) 39 { 40 var codecInfo = GetEncoder(img.RawFormat); 41 var myEncoder = Encoder.Quality; 42 var myEncoderParameters = new EncoderParameters(143 var myEncoderParameter = EncoderParameter(myEncoder,1)">44 myEncoderParameters.Param[0] = myEncoderParameter; 45 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 static ImageCodecInfo GetEncoder(ImageFormat format) 58 59 var codecs = ImageCodecInfo.GetImageDecoders(); 60 return codecs.FirstOrDefault(codec => codec.FormatID == format.Guid); 61 62 }
void Button_Click(object sender,RoutedEventArgs e) { var fileDialog = OpenFileDialog(); var fileSelect = ; if (fileDialog.ShowDialog(this)==true) { fileSelect = fileDialog.FileName; } if(string.IsNullOrWhiteSpace(fileSelect)) ; ImageCompress.CompressionImage(fileSelect,@"d:\50); }
原文链接:https://www.cnblogs.com/wdw984/p/13112621.html