C#中压缩图片的算法

 

有时,我们在程序中想把比较大的图片压缩为比较小的尺寸。下面的程序就是将图片压缩为较小尺寸的函数。

/// <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左右
—— 完 ——
相关推荐
评论

立 为 非 似

中 谁 昨 此

宵 风 夜 星

。 露 , 辰

文章点击榜

细 无 轻 自

如 边 似 在

愁 丝 梦 飞

。 雨 , 花