图片压缩技术

Posted 学习永無止境

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图片压缩技术相关的知识,希望对你有一定的参考价值。

 private string ImgComPress(string fromBase64)
        {
            Bitmap bitMap = new Bitmap(new MemoryStream(Convert.FromBase64String(fromBase64)));
            //Bitmap bitMap = new Bitmap(Server.MapPath("./1.jpg"));
            ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters myEncoderParameters = new EncoderParameters(1);
            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 80L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            Bitmap newbitMap = null;
            if (bitMap.Height > 1080)
            {
                float newWidth = ((float)bitMap.Width / bitMap.Height) * 1080;
                newbitMap = new Bitmap(bitMap, (int)newWidth, 1080);//从指定的现有图像并使用指定的大小初始化 Bitmap 类的新实例。
            }
            using (MemoryStream ms = new MemoryStream())
            {
                if (newbitMap != null)
                {
                    newbitMap.Save(ms, jgpEncoder, myEncoderParameters);
                }
                else
                {
                    bitMap.Save(ms, jgpEncoder, myEncoderParameters);
                    bitMap.Save(Server.MapPath("./2.jpg"));
                    bitMap.Save(Server.MapPath("./2_1.jpg"), jgpEncoder, myEncoderParameters);
                }
                if (ms.Length >= 1)
                {
                    return Convert.ToBase64String(ms.GetBuffer());
                }
            }
            return fromBase64;
        }

        private ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }

以上是关于图片压缩技术的主要内容,如果未能解决你的问题,请参考以下文章

Bitmap图片压缩

用 javax.imageio 实现图片压缩原理是啥?

IOS图片压缩(PNG压缩 JPEG压缩 非UIImageJPEGRepresentation)

深度学习之图片压缩算法

android图片压缩避免OOM

微信小程序图片压缩