Thursday, November 6, 2008

Resize image

private System.Drawing.Image ResizeToMaxSize(System.Drawing.Image image, int maxWidth, int maxHeight, float xDpi, float yDpi)
{

if (image == null)
{
return image;
}
int width = image.Width;
int height = image.Height;

double widthFactor = (Convert.ToDouble(width) / Convert.ToDouble(maxWidth));
double heightFactor = (Convert.ToDouble(height) / Convert.ToDouble(maxHeight));

if (widthFactor < 1 && heightFactor < 1)
{
// Skip resize
return image;
}
else
{
int newWidth;
int newHeight;
if (widthFactor > heightFactor)
{
newWidth = Convert.ToInt32(Convert.ToDouble(width) / widthFactor);
newHeight = Convert.ToInt32(Convert.ToDouble(height) / widthFactor);
}
else
{
newWidth = Convert.ToInt32(Convert.ToDouble(width) / heightFactor);
newHeight = Convert.ToInt32(Convert.ToDouble(height) / heightFactor);
}

Bitmap bitmap = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb);
bitmap.SetResolution(xDpi, yDpi);

Graphics graphics = Graphics.FromImage(bitmap);
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
image.Dispose();
return bitmap;
}
}