Asp.Net C# 图片缩放 等比例放大缩小透明背景

        public byte[] ZoomPicture(Image SourceImage, int TargetWidth, int TargetHeight)
        {
            int IntWidth; //新的图片宽
            int IntHeight; //新的图片高
            try
            {
                //System.Drawing.Imaging.ImageFormat format = SourceImage.RawFormat;    //图片格式
                System.Drawing.Bitmap SaveImage = new System.Drawing.Bitmap(TargetWidth, TargetHeight, PixelFormat.Format32bppArgb);
                Graphics g = Graphics.FromImage(SaveImage);
                // g.Clear(Color.Transparent);
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; //图片质量

                //计算缩放图片的大小 
                if (SourceImage.Width > TargetWidth && SourceImage.Height <= TargetHeight)//宽度比目的图片宽度大,长度比目的图片长度小
                {
                    IntWidth = TargetWidth;
                    IntHeight = (IntWidth * SourceImage.Height) / SourceImage.Width;
                }
                else if (SourceImage.Width <= TargetWidth && SourceImage.Height > TargetHeight)//宽度比目的图片宽度小,长度比目的图片长度大
                {
                    IntHeight = TargetHeight;
                    IntWidth = (IntHeight * SourceImage.Width) / SourceImage.Height;
                }
                else if (SourceImage.Width <= TargetWidth && SourceImage.Height <= TargetHeight) //长宽比目的图片长宽都小
                {
                    IntHeight = SourceImage.Width;
                    IntWidth = SourceImage.Height;
                }
                else//长宽比目的图片的长宽都大
                {
                    IntWidth = TargetWidth;
                    IntHeight = (IntWidth * SourceImage.Height) / SourceImage.Width;
                    if (IntHeight > TargetHeight)//重新计算
                    {
                        IntHeight = TargetHeight;
                        IntWidth = (IntHeight * SourceImage.Width) / SourceImage.Height;
                    }
                }
                //绘制图片
                g.DrawImage(SourceImage, (TargetWidth - IntWidth) / 2, (TargetHeight - IntHeight) / 2, IntWidth, IntHeight);

                using(MemoryStream stream = new MemoryStream())
                {
                    SaveImage.Save(stream, ImageFormat.Png);
                    //销毁对象
                    SaveImage.Dispose();
                    SourceImage.Dispose();
                    g.Dispose();
                    return stream.ToArray();
                }
            }
            catch (Exception ex)
            {
                HxSoft.Common.Config.Err(ex);
            }
            return null;
        }

因为我这里需要缓存图片,所有使用了 byte[]作为返回值,如果是存储图片之类的可以直接返回Image类型(fun里面的SaveImage对象)

我这里使用了质量高的效果,如果使用场景都是很小的图片,可以将图片质量降低以换取更高的性能

猜你喜欢

转载自jingjie520.iteye.com/blog/2267240