Published on: 06 Aug, 2013

How to Resize Image in ASP.Net C#?

Tumblr Digg Google Plus

This tutorial will show you how you can resize images dynamically in ASP.Net C#.

You will need to import the Drawing namespace to your project or site page.

//required .net objects
using System.Drawing;
using System.Drawing.Imaging;

The following function will resize the image by accepting the dimension of the image you need, followed by the location of where the image located and lastly where you want to save the updated/resized image.

    //function to resize image
    public static void ResizeImage(int size, string filePath, string saveFilePath) {
        //variables for image dimension/scale
        double newHeight = 0;
        double newWidth = 0;
        double scale = 0;
        //create new image object
        Bitmap curImage = new Bitmap(filePath);
        //Determine image scaling
        if (curImage.Height > curImage.Width) {
            scale = Convert.ToSingle(size) / curImage.Height;
        } else {
            scale = Convert.ToSingle(size) / curImage.Width;
        if (scale < 0 || scale > 1) { scale = 1;}

        //New image dimension
        newHeight = Math.Floor(Convert.ToSingle(curImage.Height) * scale);
        newWidth = Math.Floor(Convert.ToSingle(curImage.Width) * scale);

        //Create new object image
        Bitmap newImage = new Bitmap(curImage, Convert.ToInt32(newWidth), Convert.ToInt32(newHeight));
        Graphics imgDest = Graphics.FromImage(newImage);
        imgDest.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        imgDest.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        imgDest.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        imgDest.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
        EncoderParameters param = new EncoderParameters(1);
        param.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);

        //Draw the object image
        imgDest.DrawImage(curImage, 0, 0, newImage.Width, newImage.Height);
        //Save image file
        newImage.Save(saveFilePath, info[1], param);
        //Dispose the image objects

You may interested on our other article about How to crop image in ASP.Net C#


There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.