KARPACH

WEB DEVELOPER BLOG

Server side thumbnail generation

Below is the code for ImageThumbnail.aspx.cs, which does a server side resizing:

protected void Page_Load(object sender, EventArgs e)
{
    int imageHeight = 0, imageWidth = 0;
    int.TryParse(Request.QueryString["h"], out imageHeight); //requested Height
    int.TryParse(Request.QueryString["w"], out imageWidth); // requested Width
    string imageUrl = Request.QueryString["img"]; // path to full size image
    System.Drawing.Image fullSizeImage = System.Drawing.Image.FromFile(Server.MapPath(imageUrl));
    Response.ContentType = "image/jpg";
    // Lets check if we need resizing.
    if ((imageWidth < fullSizeImage.Width || imageHeight < fullSizeImage.Height) && (imageHeight != 0 || imageWidth != 0))
    {
        if (imageHeight == 0)
            imageHeight = imageWidth * fullSizeImage.Height / fullSizeImage.Width;
        else
            if (imageWidth == 0)
                imageWidth = imageHeight * fullSizeImage.Height / fullSizeImage.Width;
            else
            {
                if (fullSizeImage.Height > fullSizeImage.Width)
                    imageWidth = imageHeight * fullSizeImage.Height / fullSizeImage.Width;
                else
                    imageHeight = imageWidth * fullSizeImage.Height / fullSizeImage.Width;
            }
        System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(CallBackAbort);
        System.Drawing.Image thumbnail = fullSizeImage.GetThumbnailImage(imageWidth, imageHeight, dummyCallBack, IntPtr.Zero);
        thumbnail.Save(Response.OutputStream, ImageFormat.Jpeg);
    }
    else // return original image
        fullSizeImage.Save(Response.OutputStream, ImageFormat.Jpeg);
    fullSizeImage.Dispose();
}

protected bool CallBackAbort()
{
    return false;
}

Here is how you can use this page:

<img src=‘ImageThumbnail.aspx?w=100&/image/bigimage.jpg’ width="100px" />
Posted on March 15, 2008 by

Comments

Posted on 12/17/2009 01:24:33 PM by Greg B

Viktar buddy how goes it? One thing to point out from your example is this could be implemented using a HttpHandler instead of a page making this much more lightweight and opening up the possibilities of using a custom extension!
Hey Greg! You are absolutely right. I wrote this post before Legacy, back then I didn’t care about performance :-).