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:

  1. string path = Server.MapPath("~/Images");  
  2. System.Drawing.Image img = System.Drawing.Image.FromFile(string.Concat(path,"/3904.jpg"));  

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.

  1. Bitmap b = new Bitmap(img); 

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

  1. private static System.Drawing.Image resizeImage(System.Drawing.Image imgToResize, Size size)  
  2. {  
  3.     //Get the image current width  
  4.     int sourceWidth = imgToResize.Width;  
  5.     //Get the image current height  
  6.     int sourceHeight = imgToResize.Height;  
  7.     float nPercent = 0;  
  8.     float nPercentW = 0;  
  9.     float nPercentH = 0;  
  10.     //Calulate  width with new desired size  
  11.     nPercentW = ((float)size.Width / (float)sourceWidth);  
  12.     //Calculate height with new desired size  
  13.     nPercentH = ((float)size.Height / (float)sourceHeight);  
  14.     if (nPercentH < nPercentW)  
  15.         nPercent = nPercentH;  
  16.     else  
  17.      nPercent = nPercentW;  
  18.      //New Width  
  19.      int destWidth = (int)(sourceWidth * nPercent);  
  20.      //New Height  
  21.      int destHeight = (int)(sourceHeight * nPercent);  
  22.      Bitmap b = new Bitmap(destWidth, destHeight);  
  23.      Graphics g = Graphics.FromImage((System.Drawing.Image)b);  
  24.      g.InterpolationMode = InterpolationMode.HighQualityBicubic;  
  25.      // Draw image with new width and height  
  26.      g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);  
  27.      g.Dispose();  
  28.      return (System.Drawing.Image)b;  
  29. }
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:

  1. System.Drawing.Image i = resizeImage(b, new Size(100, 100));

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

Result

Resize-an-Image-in-Csharp.jpg