Thursday, 6 March 2014

Creating Thumbnail Image by keeping Aspect Ratio using C#

I am using a large picture (High Resolution) and then I will create its thumbnail.

Suppose that I need a thumbnail whose width should be maximum 200px. Now, while creating a thumbnail of a large image we also need to provide its height. So, how do we get to know about its height by keeping its aspect ratio also. Well, it can be achieved using very simple mathematical equation.

Lets do all this by writing code. I am doing this on a click of a button.

protected void Button1_Click(object sender, EventArgs e)
    //----------        Getting the Image File
    System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath("~/profile/Avatar.jpg"));
    //----------        Getting Size of Original Image
    double imgHeight = img.Size.Height;
    double imgWidth = img.Size.Width;

    //----------        Getting Decreased Size
    double x = imgWidth / 200;
    int newWidth = Convert.ToInt32(imgWidth / x);
    int newHeight = Convert.ToInt32(imgHeight / x);

    //----------        Creating Small Image
    System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
    System.Drawing.Image myThumbnail = img.GetThumbnailImage(newWidth, newHeight, myCallback, IntPtr.Zero);

    //----------        Saving Image
public bool ThumbnailCallback()
    return false;
Original Image

Thumbnail Image

1 comment: