I need a code that will allow me to resize images, but with the following functionality:
1) resize image upon upload
2) Resize image proportionally by specifying
Taken from this Stackoverflow answer, I come up with:
public static Image Resize(this Image image, int maxWidth = 0, int maxHeight = 0)
{
if (maxWidth == 0)
maxWidth = image.Width;
if (maxHeight == 0)
maxHeight = image.Height;
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
To resize Image specifying its maxWidth:
var _image = Image.FromStream(Source);
var _thumbImage = _image.Resize(100);
To resize Image specifying its maxHeight:
var _image = Image.FromStream(Source);
var _thumbImage = _image.Resize(maxHeight: 100);