public static Bitmap Get(Image image, int maxWidth, int maxHeight)
{
if (image.Width < maxWidth && image.Height < maxHeight)
{
maxWidth = image.Width;
maxHeight = image.Height;
}
var widthScaleFactor = (float)maxWidth / image.Width;
var heightScaleFactor = (float)maxHeight / image.Height;
var scaleFactor = widthScaleFactor > heightScaleFactor ? heightScaleFactor : widthScaleFactor;
var width = Convert.ToInt32(scaleFactor * image.Width);
var height = Convert.ToInt32(scaleFactor * image.Height);
var bitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb);
bitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(bitmap))
{
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.CompositingMode = CompositingMode.SourceCopy;
var imageAttributes = new ImageAttributes();
imageAttributes.SetWrapMode(WrapMode.TileFlipXY);
var destRectangle = new Rectangle(0, 0, width, height);
graphics.DrawImage(image, destRectangle, 0, 0, width, height, GraphicsUnit.Pixel, imageAttributes);
}
return bitmap;
}