Tuesday, July 28, 2009 10:13 AM
Here is a very simple way to resize an image using a bitmap as a canvas and the graphics object as a the resizing tool. Don’t forget to reference System.Drawing.
/// <summary>
/// Resizes an image from a source file to a destination file
/// the destination file will contain the exact image at the size specified
/// </summary>
/// <param name="sourceImagePath">the source image file that needs to be resized</param>
/// <param name="destinationImagePath">the destination path that the source
/// image file needs to be resized to</param>
/// <param name="width">the new width</param>
/// <param name="height">the new height</param>
static void ResizeImage(string sourceImagePath,
string destinationImagePath, int width, int height)
{
// Create an image object of the original image
System.Drawing.Image
originalImage = System.Drawing.Image.FromFile(sourceImagePath, true);
// Create a new bitmap that we will use as a canvas to drawn on the new resized imaged
Bitmap newBitmap = new Bitmap(originalImage, new System.Drawing.Size(width, height));
// Using the graphics object draw the orginal image on the canvas that was created above
using (Graphics g = Graphics.FromImage(newBitmap))
{
g.InterpolationMode =
System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(originalImage, 0, 0, width, height);
}
// Save the new resize image to a new path
((Image)newBitmap).Save(destinationImagePath);
}