Create thumbnail for an image with the same scale

Hi, after you upload an image to the server you need to scale it or manipulate it according to your business needs. In this post, I’ll show how to create a thumbnail of an image with the same scale as the original image with C#.

//the Path should be of the form “~/Folder/image.gif
//tH and tW are the size of new thumbnail to be generated.
public Image ThumbImage(String Path, int tH,int tW)
{
System.Drawing.Image im=null;
Try
{
im = System.Drawing.Image.FromFile(Server.MapPath(Path));
}
catch (Exception ex) { }
//get the image size
       int h = im.Height;
       int w = im.Width;
       
       //the new thumbnaial dimensions
Double nh = 0;
       Double nw = 0;
//if the original width is greater than the wanted thumbnail width
       if (w > tW)
       {
//then set the new width to the wanted thumbnail width
nw = tW;
             
//and also multiply the original image height with the scale ration
              nh = h * (nw / w);
        }
//Now the same for the Height
//if the original Height is greater than the wanted thumbnail Height
        if (nh > tH)
        {
//then set the new Height to the wanted thumbnail Height
nh = tH;
             
//and also multiply the original image width with the scale ration
nw = w * (nh / h);
        }
        //so if one dimension gets smaller the other will get reduced the same
        Image NewIm = new Image();
        NewIm.Height = Unit.Pixel((int)nh);
        NewIm.Width = Unit.Pixel((int)nw);
        NewIm.ImageUrl = Path;
        return NewIm;
}