直接上代码:
/// <summary>
/// 根据指定压缩比率压缩图片
/// </summary>
/// <param name="original"></param>
/// <param name="imagePath"></param>
/// <param name="quality"></param>
public static void CompressToQuality(Image original, String imagePath, int quality)
{
ImageCodecInfo jpgEncoder = null;
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == ImageFormat.Jpeg.Guid)
{
jpgEncoder = codec;
break;
}
}
if (jpgEncoder != null)
{
System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;
EncoderParameters encoderParameters = new EncoderParameters(1);
EncoderParameter encoderParameter = new EncoderParameter(encoder, quality);
encoderParameters.Param[0] = encoderParameter;
FileStream ms = new FileStream(imagePath, FileMode.Create, FileAccess.Write);
original.Save(ms, jpgEncoder, encoderParameters);
ms.Flush();
ms.Close();
}
}
|
请发表评论