Directly upload the code
public static class ImageCompress { /// <summary> /// Picture compression /// </summary> /// <param name="imagePath">Image file path</param> /// <param name="targetFolder">Save folder</param> /// <param name="quality">Compression quality</param> /// <param name="fileSuffix">Compressed file name suffix (prevent direct overwriting of the original file)</param> public static void CompressionImage(string imagePath, string targetFolder, long quality = 100, string fileSuffix = "compress") { if (!(imagePath)) { throw new FileNotFoundException(); } if (!(targetFolder)) { (targetFolder); } var fileInfo = new FileInfo(imagePath); var fileName = (, ""); var fileFullName = ($"{targetFolder}", $"{fileName}_{fileSuffix}{}"); var imageByte = CompressionImage(imagePath, quality); var ms = new MemoryStream(imageByte); var image = (ms); (fileFullName); (); (); (); } private static byte[] CompressionImage(string imagePath, long quality) { using (var fileStream = new FileStream(imagePath, )) { using (var img =(fileStream)) { using (var bitmap = new Bitmap(img)) { var codecInfo = GetEncoder(); var myEncoder = ; var myEncoderParameters = new EncoderParameters(1); var myEncoderParameter = new EncoderParameter(myEncoder, quality); [0] = myEncoderParameter; using (var ms = new MemoryStream()) { (ms, codecInfo, myEncoderParameters); (); (); return (); } } } } } private static ImageCodecInfo GetEncoder(ImageFormat format) { var codecs = (); return (codec => == ); } }
Calling method (WPF as an example)
private void Button_Click(object sender, RoutedEventArgs e) { var fileDialog = new OpenFileDialog(); var fileSelect = ""; if ((this)==true) { fileSelect = ; } if((fileSelect)) return; (fileSelect,@"d:\",50); }
The above is the detailed content of the sample code for C# image compression (the best effect on jpg compression). For more information about C# image compression, please pay attention to my other related articles!