Quality issue when resizing image?

I use this code to resize an image. But the result is not in order, I want better quality. I know its poor quality, because I also resize the image with Photoshop, and the result is different the better. How to fix it?

private static Image resizeImage(Image imgToResize, Size size) { int sourceWidth = imgToResize.Width; int sourceHeight = imgToResize.Height; float nPercent = 0; float nPercentW = 0; float nPercentH = 0; nPercentW = ((float)size.Width / (float)sourceWidth); nPercentH = ((float)size.Height / (float)sourceHeight); if (nPercentH < nPercentW) nPercent = nPercentH; else nPercent = nPercentW; int destWidth = (int)(sourceWidth * nPercent); int destHeight = (int)(sourceHeight * nPercent); Bitmap b = new Bitmap(destWidth, destHeight); Graphics g = Graphics.FromImage((Image)b); g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(imgToResize, 0, 0, destWidth, destHeight); g.Dispose(); return (Image)b; } 
+4
source share
1 answer

This is a regular program that I use. You may find this helpful. This is an extension method to download. The only difference is that I omit the code to maintain an aspect ratio that you could easily hook up.

 public static Image GetImageHiQualityResized(this Image image, int width, int height) { var thumb = new Bitmap(width, height); using (var g = Graphics.FromImage(thumb)) { g.SmoothingMode = SmoothingMode.HighQuality; g.CompositingQuality = CompositingQuality.HighQuality; g.InterpolationMode = InterpolationMode.High; g.DrawImage(image, new Rectangle(0, 0, thumb.Width, thumb.Height)); return thumb; } } 

An example of using this extension method may include:

 // Load the original image using(var original = Image.FromFile(@"C:\myimage.jpg")) using(var thumb = image.GetImageHiQualityResized(120, 80)) { thumb.Save(@"C:\mythumb.png", ImageFormat.Png); } 

Notes

The difference between the default JPG encoding and the default PNG encoding is really different. Below are two thumbs using your example, one of which is saved using ImageFormat.Png and one with ImageFormat.Jpeg .

PNG image

PNG Image

JPEG image

JPEG Image

You may find that the work done by the original poster in this matter will be useful if you decide that you absolutely must use JPEG. This includes adjusting the image codec and encoding parameters to high-quality settings. .NET Saving jpeg with the same quality as when loading

If it were me, I would immediately use the PNG format, since it is lossless.

+3
source

All Articles