Server side thumbnail generation

Below is the code for ImageThumbnail.aspx.cs, which does 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 Saturday, March 15, 2008 by | Comments (1) | Add Comment

Comments

Gravatar

Re:Server side thumbnail generation

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!

Posted on 12/17/2009 1:24:33 PM by Greg B #
Gravatar

Hey Greg! You are absolutely right. I wrote this post before Legacy, back then I didn't care about performance :-).

New Comment

Your Name:
Email (for internal use only):
Comment:
 
Code above:

Categories

Recent Tweets

  • Simon Ince's Blog: Hierarchies with HierarchyID in SQL 2008 http://t.co/xSDwiF6rRS.
  • Visual Studio 2010 WAS painfully slow - CodeProject http://t.co/Usba1x6CZy

Valid HTML5