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 HighQualityB
icubic 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 left 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 right image has the better contrast.
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);
You can read more on different interpolation mode here.
You can also download the project files here, they include uploading and high quality resizing.