PM's Blog

Pramod Mohanan's notes about ASP.NET, MVC, C#, SQL, jQuery, Bootstrap

Dynamic resizing of Images

Front end users are free to upload images of any size, However for uniformity its often necessary to resize these images to a standard width and height but still maintaining the aspect ratio.

The following function is what I use to to resize an image dynamically. The file thus returned can then be renamed and can be saved with change of extension, for example a .png can be saved as .tif and it works perfectly fine.

do remember to add the following using statements

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

and here is the function

 public static Bitmap resizeImage(string file, int height, int width)
 {
    Image imgToResize = Image.FromFile(file);
    int sourceWidth = imgToResize.Width;
    int sourceHeight = imgToResize.Height;

    float nPercent = 0;
    float nPercentW = 0;
    float nPercentH = 0;

    nPercentW = ((float)width/ (float)sourceWidth);
    nPercentH = ((float)height / (float)sourceHeight);

    if (nPercentH < nPercentW)
       nPercent = nPercentH;
    else
       nPercent = nPercentW;

    int destWidth = (int)(sourceWidth * nPercent);
    int destHeight = (int)(sourceHeight * nPercent);

    Bitmap b = new Bitmap(destWidth, destHeight);
    Graphics g = Graphics.FromImage((Image)b);
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;

    g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
    g.Dispose();
    return b;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

PM's Blog © 2015