ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ResizeAndFit

This method resizes a System.Drawing.Image and tries to fit it in the destination Size. The source image size may be smaller or bigger then the target size. Source and target layout orientation can be different. ResizeAndFit tries to fit it the best it can.

Source

public static Image ResizeAndFit(this Image image, Size newSize)
{
    var sourceIsLandscape = image.Width > image.Height;
    var targetIsLandscape = newSize.Width > newSize.Height;

    var ratioWidth = (double)newSize.Width / (double)image.Width;
    var ratioHeight = (double)newSize.Height / (double)image.Height;

    var ratio = 0.0;

    if (ratioWidth > ratioHeight && sourceIsLandscape==targetIsLandscape)
        ratio = ratioWidth;
    else
        ratio = ratioHeight;

    int targetWidth = (int)(image.Width * ratio);
    int targetHeight = (int)(image.Height * ratio);

    var bitmap = new Bitmap(newSize.Width, newSize.Height);
    var graphics = Graphics.FromImage((Image)bitmap);
    
    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

    var offsetX = ((double)(newSize.Width - targetWidth)) / 2;
    var offsetY = ((double)(newSize.Height - targetHeight)) / 2;

    graphics.DrawImage(image, (int)offsetX, (int)offsetY, targetWidth, targetHeight);
    graphics.Dispose();

    return (Image)bitmap;
}

Example

Image image = Image.FromStream(context.Request.InputStream).ResizeAndFit(new Size( 125, 100));

Author: Loek van den Ouweland

Submitted on: 13 feb. 2009

Language: C#

Type: System.Drawing.Image

Views: 4993