Search code examples
c#asp.netthumbnailsimage-resizinggeneric-handler

How can I generate a thumbnail from an image in server folder?


I've been trying to figure this out but I'm not getting anywhere. What I'm trying to do is this: I have a aspx page where you can upload images (they are stored in a folder on the server), on one page you can see all the uploaded images and it generates links (a tags) with a reference to these images, but until now it loaded the full images as a "thumbnail" and they are far too large in size (1920x1200px), So I replaced the image src with a generic handler, which should get the image from the folder and then return it, resized to say like 209x133px.

But I have no idea where to start and I would appreciate any held, maybe someone out there once did somethin similar.

Anyway, thanks in advance

This is how I ceate the links and images with a repeater:

protected void repImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.AlternatingItem ||
        e.Item.ItemType == ListItemType.Item)
    {
        string sFile = e.Item.DataItem as string;

        //Create the thumblink
        HyperLink hlWhat = e.Item.FindControl("hlWhat") as HyperLink;
        hlWhat.NavigateUrl = ResolveUrl("~/_img/_upload/" + sFile);
        hlWhat.ToolTip = System.IO.Path.GetFileNameWithoutExtension(sFile);
        hlWhat.Attributes["rel"] = "imagebox-bw";
        hlWhat.Attributes["target"] = "_blank";

        Image oImg = e.Item.FindControl("imgTheImage") as Image;
        oImg.ImageUrl = ResolveUrl("Thumbnail.ashx?img=" + sFile);
        oImg.Width = 203;
        oImg.CssClass = "galleryImgs";

    }

}

and for now, my handler look like this:

<%@ WebHandler Language="C#" Class="Thumbnail" %>

using System;
using System.Web;

public class Thumbnail : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        if (!string.IsNullOrEmpty(context.Request.QueryString["img"]))
        {
            string fileName = context.Request.QueryString["img"];

        }

        else
        {

        }

    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

Solution

  • Adding System.Drawing and System.Drawing.Drawing2D namespaces you Can resize your image CodeBehind:

    public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight)
      {
          var ratio = (double)maxHeight / image.Height;
          var newWidth = (int)(image.Width * ratio);
          var newHeight = (int)(image.Height * ratio);
          var newImage = new Bitmap(newWidth, newHeight);
          using (var g = Graphics.FromImage(newImage))
          {
              g.DrawImage(image, 0, 0, newWidth, newHeight);
          }
          return newImage;
      }