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

Heidi ·
更新时间:2024-11-13
· 887 次阅读

直接上代码

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

以上就是C# 进行图片压缩的示例代码(对jpg压缩效果最好)的详细内容,更多关于c# 图片压缩的资料请关注软件开发网其它相关文章!

您可能感兴趣的文章:c# 如何实现图片压缩C#使用GZipStream实现文件的压缩与解压C# 使用SharpZipLib生成压缩包的实例代码c# 文件压缩zip或将zip文件解压的方法详解C#压缩、解压文件夹/文件(带密码)C#使用ICSharpCode.SharpZipLib.dll进行文件的压缩与解压功能C#实现文件压缩与解压的方法示例【ZIP格式】C#调用7z实现文件的压缩与解压



C# 示例 压缩 图片 jpg 图片压缩

需要 登录 后方可回复, 如果你还没有账号请 注册新账号