Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resizing an image in asp.net without losing the image quality

I am developing an ASP.NET 3.5 web application in which I am allowing my users to upload either jpeg,gif,bmp or png images. If the uploaded image dimensions are greater then 103 x 32 the I want to resize the uploaded image to 103 x 32. I have read some blog posts and articles, and have also tried some of the code samples but nothing seems to work right. Has anyone succeed in doing this?

like image 298
Kumar Avatar asked Feb 23 '10 16:02

Kumar


People also ask

Can you resize an image without losing quality?

If you want to resize an image without losing quality, you need to make sure that the "Resample" checkbox is unchecked. This checkbox tells Paint to change the number of pixels in the image. When you uncheck this box, Paint will not change the number of pixels, and the quality of the image will not be reduced.

How do I resize an image to maintain quality?

Go to Image, then Scale, where you can input your desired dimensions. Finally, under the Quality, choose Sinc as Interpolation and then click Scale. There you have it, an image resize with sustained quality.

Can raster images be resized without losing quality?

For example, if we scale a raster image to enlarge it, without changing resolution, it will lose quality and look blurry or pixilated. This is because we are stretching the pixels over a larger area, thus making them look less sharp.


2 Answers

I had the same problem a while back and dealt with it this way:

private Image RezizeImage(Image img, int maxWidth, int maxHeight) {     if(img.Height < maxHeight && img.Width < maxWidth) return img;     using (img)     {         Double xRatio = (double)img.Width / maxWidth;         Double yRatio = (double)img.Height / maxHeight;         Double ratio = Math.Max(xRatio, yRatio);         int nnx = (int)Math.Floor(img.Width / ratio);         int nny = (int)Math.Floor(img.Height / ratio);         Bitmap cpy = new Bitmap(nnx, nny, PixelFormat.Format32bppArgb);         using (Graphics gr = Graphics.FromImage(cpy))         {             gr.Clear(Color.Transparent);              // This is said to give best quality when resizing images             gr.InterpolationMode = InterpolationMode.HighQualityBicubic;              gr.DrawImage(img,                 new Rectangle(0, 0, nnx, nny),                 new Rectangle(0, 0, img.Width, img.Height),                 GraphicsUnit.Pixel);         }         return cpy;     }  }  private MemoryStream BytearrayToStream(byte[] arr) {     return new MemoryStream(arr, 0, arr.Length); }  private void HandleImageUpload(byte[] binaryImage) {     Image img = RezizeImage(Image.FromStream(BytearrayToStream(binaryImage)), 103, 32);     img.Save("IMAGELOCATION.png", System.Drawing.Imaging.ImageFormat.Gif); } 

I just read that this was the the way to get highest quality.

like image 33
Alxandr Avatar answered Sep 24 '22 07:09

Alxandr


This is the code I use. It supports rotation, and also sets the image resolution to the JPEG standards of 72dpi@24-bit color (by default GDI+ saves images at 96dpi@32-bit color). It also fixes the black/gray border problem that some people experience when resizing images.

/// <summary> /// Resizes and rotates an image, keeping the original aspect ratio. Does not dispose the original /// Image instance. /// </summary> /// <param name="image">Image instance</param> /// <param name="width">desired width</param> /// <param name="height">desired height</param> /// <param name="rotateFlipType">desired RotateFlipType</param> /// <returns>new resized/rotated Image instance</returns> public static Image Resize(Image image, int width, int height, RotateFlipType rotateFlipType) {     // clone the Image instance, since we don't want to resize the original Image instance     var rotatedImage = image.Clone() as Image;     rotatedImage.RotateFlip(rotateFlipType);     var newSize = CalculateResizedDimensions(rotatedImage, width, height);      var resizedImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppArgb);     resizedImage.SetResolution(72, 72);      using (var graphics = Graphics.FromImage(resizedImage))     {         // set parameters to create a high-quality thumbnail         graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;         graphics.SmoothingMode = SmoothingMode.AntiAlias;         graphics.CompositingQuality = CompositingQuality.HighQuality;         graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;          // use an image attribute in order to remove the black/gray border around image after resize         // (most obvious on white images), see this post for more information:         // http://www.codeproject.com/KB/GDI-plus/imgresizoutperfgdiplus.aspx         using (var attribute = new ImageAttributes())         {             attribute.SetWrapMode(WrapMode.TileFlipXY);              // draws the resized image to the bitmap             graphics.DrawImage(rotatedImage, new Rectangle(new Point(0, 0), newSize), 0, 0, rotatedImage.Width, rotatedImage.Height, GraphicsUnit.Pixel, attribute);         }     }      return resizedImage; }  /// <summary> /// Calculates resized dimensions for an image, preserving the aspect ratio. /// </summary> /// <param name="image">Image instance</param> /// <param name="desiredWidth">desired width</param> /// <param name="desiredHeight">desired height</param> /// <returns>Size instance with the resized dimensions</returns> private static Size CalculateResizedDimensions(Image image, int desiredWidth, int desiredHeight) {     var widthScale = (double)desiredWidth / image.Width;     var heightScale = (double)desiredHeight / image.Height;      // scale to whichever ratio is smaller, this works for both scaling up and scaling down     var scale = widthScale < heightScale ? widthScale : heightScale;      return new Size                    {                        Width = (int) (scale * image.Width),                        Height = (int) (scale * image.Height)                    }; } 
like image 142
Daniel T. Avatar answered Sep 22 '22 07:09

Daniel T.