Image Resize using C#.

Use the following method to resize an image.

public Image ResizeImage(Image image, int maxWidth, int maxHeight)
{
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 <>
{
// 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);
}
if (newHeight == 0)
{
newHeight = 1;
}
if (newWidth == 0)
{
newWidth = 1;
}
Bitmap bitmap = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
bitmap.SetResolution(96, 96);

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;
}
}


...S.VinothkumaR.

No comments: