使用c#调整图片质量

时间:2022-02-19 17:06:34
//参数: 原始图片,保存路径,压缩比
private void CompressImage(MagickNet.Image img,string toPath, long ratio)
{
using (Bitmap thumbImage = new Bitmap(MagickNet.Image.ToBitmap(img)))
{
ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
EncoderParameters myEncoderParameters = new EncoderParameters();
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, ratio);
myEncoderParameters.Param[] = myEncoderParameter;
thumbImage.Save(toPath, jgpEncoder, myEncoderParameters);
}
} private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}

调用

CompressImage(img, toPath, 90L);