Resize an Image in C#

In this article, I will tell you how to resize an image to a desired size.

To resize an image in ASP.Net/C#, we will use the following procedure:

1. Get an image that you want to resize: 

// Replace this with the actual path to your image
string path = "~Images"; 
System.Drawing.Image img = System.Drawing.Image.FromFile(string.Concat(path, "\3904.jpeg"));

In the attached sample, I stored the image in the image folder.

2. The Bitmap object is declared to get the image in pixel data.

Bitmap b = new Bitmap(img);

3. To resize the image to the desired format, I used the method given below:

private static System.Drawing.Image ResizeImage(System.Drawing.Image imgToResize, Size size)
{
    // Get the image current width
    int sourceWidth = imgToResize.Width;
    // Get the image current height
    int sourceHeight = imgToResize.Height;
    float nPercent = 0;
    float nPercentW = 0;
    float nPercentH = 0;
    // Calculate width and height with new desired size
    nPercentW = ((float)size.Width / (float)sourceWidth);
    nPercentH = ((float)size.Height / (float)sourceHeight);
    nPercent = Math.Min(nPercentW, nPercentH);
    // New Width and Height
    int destWidth = (int)(sourceWidth * nPercent);
    int destHeight = (int)(sourceHeight * nPercent);
    Bitmap b = new Bitmap(destWidth, destHeight);
    Graphics g = Graphics.FromImage((System.Drawing.Image)b);
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    // Draw image with new width and height
    g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
    g.Dispose();
    return (System.Drawing.Image)b;
}

In the method above we get the bitmap image and draw the new image with new width and height. (The image will be drawn in the specified aspect ratio.)

4. Pass the bitmap image in the method above with the desired width and height:

System.Drawing.Image i = ResizeImage(b, new Size(500, 500));

The method given above will return the image with the new width and height.

Result

Resize-an-Image-in-Csharp.jpg


Similar Articles