I want to proceed with telling how to deal with uploaded images with ASP.NET. I have already showed how to resize images. However, that resizing method isn't perfect. It doesn't produce images of high quality. Even though it just shrinks images, the quality of resized images don't match the quality of original images, the produced quality usually appears to be worse. Sure, there is a neat solution. We just need to use the HighQualityBicubic Interpolation mode. Sounds difficult? In fact, it's not difficult to implement, just need to add a few lines of code, but the result is great.
Here are two images, the first is made with a simply resizing method, while the right one is made with a resizing method. Note, that it doesn't have noise on the buildings and the next image has the better contrast.
low quality
high quality
The code is:
private Bitmap ResizeImage(Stream streamImage, int maxWidth, int maxHeight)
{
Bitmap originalImage = new Bitmap(streamImage);
int newWidth = originalImage.Width;
int newHeight = originalImage.Height;
double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;
if (aspectRatio <= 1 && originalImage.Width > maxWidth)
{
newWidth = maxWidth;
newHeight = (int)Math.Round(newWidth / aspectRatio);
}
else if (aspectRatio > 1 && originalImage.Height > maxHeight)
{
newHeight = maxHeight;
newWidth = (int)Math.Round(newHeight * aspectRatio);
}
Bitmap newImage = new Bitmap(originalImage, newWidth, newHeight);
Graphics g = Graphics.FromImage(newImage);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);
originalImage.Dispose();
return newImage;
}
You can read more on different interpolation mode here.
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way. My personal thoughts tend to change, hence the articles in this blog might not provide an accurate reflection of my present standpoint.
© Mike Borozdin