在asp.net中调整图像大小而不丢失图像质量

我正在开发一个ASP.NET 3.5 Web应用程序,该应用程序允许我的用户上传jpeg,gif,bmp或png图像。如果上载的图像尺寸大于103 x 32,则我希望将上载的图像尺寸调整为103 x32。我已经阅读了一些博客文章和文章,还尝试了一些代码示例,但似乎没有任何用处。有没有人成功做到这一点?



弑天下
浏览 660回答 3
3回答

泛舟湖上清波郎朗

不久前,我遇到了同样的问题,并以这种方式处理:private Image RezizeImage(Image img, int maxWidth, int maxHeight){&nbsp; &nbsp; if(img.Height < maxHeight && img.Width < maxWidth) return img;&nbsp; &nbsp; using (img)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Double xRatio = (double)img.Width / maxWidth;&nbsp; &nbsp; &nbsp; &nbsp; Double yRatio = (double)img.Height / maxHeight;&nbsp; &nbsp; &nbsp; &nbsp; Double ratio = Math.Max(xRatio, yRatio);&nbsp; &nbsp; &nbsp; &nbsp; int nnx = (int)Math.Floor(img.Width / ratio);&nbsp; &nbsp; &nbsp; &nbsp; int nny = (int)Math.Floor(img.Height / ratio);&nbsp; &nbsp; &nbsp; &nbsp; Bitmap cpy = new Bitmap(nnx, nny, PixelFormat.Format32bppArgb);&nbsp; &nbsp; &nbsp; &nbsp; using (Graphics gr = Graphics.FromImage(cpy))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; gr.Clear(Color.Transparent);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // This is said to give best quality when resizing images&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; gr.InterpolationMode = InterpolationMode.HighQualityBicubic;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; gr.DrawImage(img,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new Rectangle(0, 0, nnx, nny),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new Rectangle(0, 0, img.Width, img.Height),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; GraphicsUnit.Pixel);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return cpy;&nbsp; &nbsp; }}private MemoryStream BytearrayToStream(byte[] arr){&nbsp; &nbsp; return new MemoryStream(arr, 0, arr.Length);}private void HandleImageUpload(byte[] binaryImage){&nbsp; &nbsp; Image img = RezizeImage(Image.FromStream(BytearrayToStream(binaryImage)), 103, 32);&nbsp; &nbsp; img.Save("IMAGELOCATION.png", System.Drawing.Imaging.ImageFormat.Gif);}我刚刚读到,这是获得最高质量的方法。
打开App,查看更多内容
随时随地看视频慕课网APP