C# 进行图片压缩的示例代码(对jpg压缩效果最好)

这篇文章主要介绍了C# 进行图片压缩的示例代码,帮助大家更好的利用c# 处理图片,提高办公效率,感兴趣的朋友可以了解下

 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为例)

 1 private void Button_Click(object sender, RoutedEventArgs e)
 2     {
 3       var fileDialog = new OpenFileDialog();
 4       var fileSelect = "";
 5       if (fileDialog.ShowDialog(this)==true)
 6       {
 7         fileSelect = fileDialog.FileName;
 8       }
 9       if(string.IsNullOrWhiteSpace(fileSelect)) return;
10       
11       ImageCompress.CompressionImage(fileSelect,@"d:\",50);
12 
13     }

 

C# 进行图片压缩的示例代码(对jpg压缩效果最好)

上一篇:Windows 10操作系统配置JDK 1.15的环境变量


下一篇:Node.js实践一:node.js安装及环境配置之Windows篇