I want to resize an image with good quality, and the most important thing is having less weight for an image so that webpages will load it faster.
I am using the below method for this. Please check it out, if it is proper or let me know if it needs any modifications. If there is a better method than this, then also please tell me.
public static void ResizeImage(int newWidth, int newHeight, Stream sourcePath, string targetPath)
{
using (var image = System.Drawing.Image.FromStream(sourcePath))
{
Image imgPhoto = Image.FromStream(sourcePath);
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
if (sourceWidth > newWidth || sourceHeight > newHeight)
{
//Consider vertical pics
if (sourceWidth < sourceHeight)
{
int buff = newWidth;
newWidth = newHeight;
newHeight = buff;
}
int destX = 0, destY = 0;
float nPercent = 0, nPercentW = 0, nPercentH = 0;
nPercentW = ((float)newWidth / (float)sourceWidth);
nPercentH = ((float)newHeight / (float)sourceHeight);
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = System.Convert.ToInt16((newWidth -
(sourceWidth * nPercent)) / 2);
}
else
{
nPercent = nPercentW;
destY = System.Convert.ToInt16((newHeight -
(sourceHeight * nPercent)) / 2);
}
}
var thumbnailImg = new Bitmap(newWidth, newHeight);
var thumbGraph = Graphics.FromImage(thumbnailImg);
thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
thumbGraph.DrawImage(image, imageRectangle);
thumbnailImg.Save(targetPath, image.RawFormat);
}
}