高質量圖片壓縮低失真

        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;
        }
相關文章
相關標籤/搜索