高质量图片压缩低失真

Posted on 2017-04-18 21:01  hwisecn  阅读(459)  评论(0编辑  收藏  举报
        private byte[] ZipImageSize(byte[] bytes, int width, int height, string formattype)
        {
            Stream bs = new MemoryStream(bytes);
            //从文件取得图片对象
            System.Drawing.Image myImage = System.Drawing.Image.FromStream(bs, true);
            int ow = myImage.Width;
            int oh = myImage.Height;
            //缩略图宽、高 
            double newWidth = myImage.Width, newHeight = myImage.Height;
            //宽大于模版的横图 
            if (myImage.Width > myImage.Height || myImage.Width == myImage.Height)
            {
                if (myImage.Width > width)
                {
                    //宽按模版,高按比例缩放 
                    newWidth = width;
                    newHeight = myImage.Height * (newWidth / myImage.Width);
                }
            }
            //高大于模版的竖图 
            else
            {
                if (myImage.Height > height)
                {
                    //高按模版,宽按比例缩放 
                    newHeight = height;
                    newWidth = myImage.Width * (newHeight / myImage.Height);
                }
            }

            //图片压缩
            Image imgThumb = new Bitmap((int)newWidth, (int)newHeight);
            Graphics g = Graphics.FromImage(imgThumb);
            var destRect = new Rectangle(0, 0, (int) newWidth, (int) newHeight);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.DrawImage(myImage, destRect, 0, 0, ow, oh, GraphicsUnit.Pixel);
            myImage.Dispose();


            Stream ms = new MemoryStream();
            if (formattype == "JPEG")
            {
                imgThumb.Save(ms, ImageFormat.Jpeg);
            }
            else if (formattype == "PNG")
            {
                imgThumb.Save(ms, ImageFormat.Png);
            }
            else if (formattype == "BMP")
            {
                imgThumb.Save(ms, ImageFormat.Bmp);
            }
            else if (formattype == "GIF")
            {
                imgThumb.Save(ms, ImageFormat.Gif);
            }
            else if (formattype == "ICON")
            {
                imgThumb.Save(ms, ImageFormat.Icon);
            }

            else if (formattype == "JPG")
            {
                imgThumb.Save(ms, ImageFormat.Jpeg);
            }

            byte[] buffer = new byte[ms.Length];
            ms.Seek(0, SeekOrigin.Begin);
            ms.Read(buffer, 0, buffer.Length);
            return buffer;
        }

 

Copyright © 2024 hwisecn
Powered by .NET 9.0 on Kubernetes