C# 进行图片压缩的示例代码(对jpg压缩效果最好)
直接上代码
publicstaticclassImageCompress { //////图片压缩 /// ///图片文件路径 /// 保存文件夹 /// 压缩质量 /// 压缩后的文件名后缀(防止直接覆盖原文件) publicstaticvoidCompressionImage(stringimagePath,stringtargetFolder,longquality=100,stringfileSuffix="compress") { if(!File.Exists(imagePath)) { thrownewFileNotFoundException(); } if(!Directory.Exists(targetFolder)) { Directory.CreateDirectory(targetFolder); } varfileInfo=newFileInfo(imagePath); varfileName=fileInfo.Name.Replace(fileInfo.Extension,""); varfileFullName=Path.Combine($"{targetFolder}",$"{fileName}_{fileSuffix}{fileInfo.Extension}"); varimageByte=CompressionImage(imagePath,quality); varms=newMemoryStream(imageByte); varimage=Image.FromStream(ms); image.Save(fileFullName); ms.Close(); ms.Dispose(); image.Dispose(); } privatestaticbyte[]CompressionImage(stringimagePath,longquality) { using(varfileStream=newFileStream(imagePath,FileMode.Open)) { using(varimg=Image.FromStream(fileStream)) { using(varbitmap=newBitmap(img)) { varcodecInfo=GetEncoder(img.RawFormat); varmyEncoder=Encoder.Quality; varmyEncoderParameters=newEncoderParameters(1); varmyEncoderParameter=newEncoderParameter(myEncoder,quality); myEncoderParameters.Param[0]=myEncoderParameter; using(varms=newMemoryStream()) { bitmap.Save(ms,codecInfo,myEncoderParameters); myEncoderParameters.Dispose(); myEncoderParameter.Dispose(); returnms.ToArray(); } } } } } privatestaticImageCodecInfoGetEncoder(ImageFormatformat) { varcodecs=ImageCodecInfo.GetImageDecoders(); returncodecs.FirstOrDefault(codec=>codec.FormatID==format.Guid); } }
调用方法(WPF为例)
privatevoidButton_Click(objectsender,RoutedEventArgse) { varfileDialog=newOpenFileDialog(); varfileSelect=""; if(fileDialog.ShowDialog(this)==true) { fileSelect=fileDialog.FileName; } if(string.IsNullOrWhiteSpace(fileSelect))return; ImageCompress.CompressionImage(fileSelect,@"d:\",50); }
以上就是C#进行图片压缩的示例代码(对jpg压缩效果最好)的详细内容,更多关于c#图片压缩的资料请关注毛票票其它相关文章!