Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

HTTP-handler for image

3.67/5 (2 votes)
14 Apr 2013CPOL 25.8K   644  
Create any size image at runtime.

Introduction

In a few of my previous projects, there was a requirement to show a list of images on different parts of pages on a website. Like everybody else we created a thumbnail for our master image in a different size. Not only that there was other mobile device applications ex., Android, ioS, Nokia which needed images according to there screen width and height, so again we kept a number of images according to other device requirements. Well this consumed heavy disk space on the hosting server, extra work for developers and designers, but thanks to VS handler our problem was resolved. Well we can't implement this trick in our previous projects but in new projects, we can. 

Background

So friends it is a very normal trick, following are the requirements to implement this trick:

C#
using System.IO;
using System.Drawing;

Using the code 

Below is a sample of handler code for the ProcessRequest method:

C#
public void ProcessRequest (HttpContext context) {
        
    int W = Int32.Parse(context.Request.QueryString["w"]);
    int H = Int32.Parse(context.Request.QueryString["h"]);
    Image img = Image.FromFile(context.Server.MapPath("~/prk/1.jpg"));
    Image _img = new Bitmap(W, H);
    Graphics g = Graphics.FromImage(_img);
    g.DrawImage(img, 0, 0, W, H);
    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
    g.Dispose();
    img.Dispose();
    MemoryStream str = new MemoryStream();
    _img = _img.GetThumbnailImage(W, H, null, IntPtr.Zero);
    _img.Save(str, System.Drawing.Imaging.ImageFormat.Png);
    _img.Dispose();
    str.WriteTo(context.Response.OutputStream);
    str.Dispose();
    str.Close();
    context.Response.ContentType = ".png";
    context.Response.End();
}

Now like the same as how we put reference for other images we will do here also, giving our handler URL as source to image.

XML
<img alt="master" src="masterImage.ashx?w=150&amp;h=120" />

Points of Interest

Flexibility to resize image at runtime, flexibility to use on multiple device applications. Helps application performance.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)