图片压缩技术

 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;
        }

posted @ 2016-06-22 14:55  Crazier  阅读(230)  评论(0编辑  收藏  举报