C#進行圖片壓縮
阿新 • • 發佈:2020-06-18
https://www.cnblogs.com/wdw984/p/13112621.html感謝老哥 我是程式碼搬運工
直接上程式碼
public static class ImageCompress { /// <summary> /// 圖片壓縮 /// </summary> /// <param name="imagePath">圖片檔案路徑</param> /// <param name="targetFolder">儲存資料夾</param> /// <param name="quality">壓縮質量</param> /// <param name="fileSuffix">壓縮後的檔名字尾(防止直接覆蓋原檔案)</param> public static void CompressionImage(string imagePath,string targetFolder,long quality = 100,string fileSuffix = "compress") { if (!File.Exists(imagePath)) {throw new FileNotFoundException(); } if (!Directory.Exists(targetFolder)) { Directory.CreateDirectory(targetFolder); } var fileInfo = new FileInfo(imagePath); var fileName = fileInfo.Name.Replace(fileInfo.Extension,""); var fileFullName = Path.Combine($"{targetFolder}",$"{fileName}_{fileSuffix}{fileInfo.Extension}"); var imageByte = CompressionImage(imagePath,quality); var ms = new MemoryStream(imageByte); var image = Image.FromStream(ms); image.Save(fileFullName); ms.Close(); ms.Dispose(); image.Dispose(); } private static byte[] CompressionImage(string imagePath,long quality) { using (var fileStream = new FileStream(imagePath,FileMode.Open)) { using (var img =Image.FromStream(fileStream)) { using (var bitmap = new Bitmap(img)) { var codecInfo = GetEncoder(img.RawFormat); var myEncoder = Encoder.Quality; var myEncoderParameters = new EncoderParameters(1); var myEncoderParameter = new EncoderParameter(myEncoder,quality); myEncoderParameters.Param[0] = myEncoderParameter; using (var ms = new MemoryStream()) { bitmap.Save(ms,codecInfo,myEncoderParameters); myEncoderParameters.Dispose(); myEncoderParameter.Dispose(); return ms.ToArray(); } } } } } private static ImageCodecInfo GetEncoder(ImageFormat format) { var codecs = ImageCodecInfo.GetImageDecoders(); return codecs.FirstOrDefault(codec => codec.FormatID == format.Guid); } }
呼叫方法(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); }