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();

                }

            }

        }

    }

調用:CompressionImage(stream,0L)//最低質量 1M jpg圖大概能壓成180k左右

 

你可能感兴趣的:(C#)