Image resizing and cropping

A couple of methods to demonstrate the resizing and cropping of images.


private static Image ResizeImage(Image imageToResize, Size newSize)
{
    Bitmap b = new Bitmap(newSize.Width, newSize.Height);  //new bitmap
    Graphics g = Graphics.FromImage((Image)b);  //new graphics object 

    g.InterpolationMode = InterpolationMode.HighQualityBicubic;  //change this depending expanding/shrinking etc..
    g.DrawImage(imageToResize, 0, 0, newSize.Width, newSize.Height);  //draw the new image
    g.Dispose();  //done now thanks.

    return (Image)b;
}

You can of course use GetThumbnail in some instances and avoid all of this convolution, however using the interpolation method above will maintain far better image quality.


private static Image CropImage(Image imageToCrop, Rectangle rect)
{
    Bitmap b = new Bitmap(imageToCrop);  //new bmp
    Image croppedImage = b.Clone(rect, b.PixelFormat);  //copy a section of the original

    return croppedImage;
}

Advertisements

2 thoughts on “Image resizing and cropping

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s