有时,我们在程序中想把比较大的图片压缩为比较小的尺寸。下面的程序就是将图片压缩为较小尺寸的函数。
/// <summary>
/// 压缩图片的算法
/// </summary>
/// <param name="fileStream">图片流</param>
/// <param name="quality">压缩质量,取值在0-100之间,数值越大质量越高</param>
/// <returns></returns>
private byte[] CompressionImage(Stream fileStream, long quality)
{
using (System.Drawing.Image img = System.Drawing.Image.FromStream(fileStream))
{
using (Bitmap bitmap = new Bitmap(img)) {
ImageCodecInfo CodecInfo = GetEncoder(img.RawFormat);
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, quality);
myEncoderParameters.Param[0] = myEncoderParameter;
using (MemoryStream ms = new MemoryStream()) {
bitmap.Save(ms, CodecInfo, myEncoderParameters);
myEncoderParameters.Dispose();
myEncoderParameter.Dispose();
return ms.ToArray();
}
}
}
}0L); //最低质量 1M 大小的jpg图片可以压缩到180k左右
在程序中的调用方法:CompressionImage(stream,
新闻热点
疑难解答