Dynamically Rendering asp:Image from BLOB entry in ASP.NET

Add a ‘Generic Handler’ to your web project, name it something like Image.ashx. Implement it like this:

public class ImageHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        using(Image image = GetImage(context.Request.QueryString["ID"]))
        {    
            context.Response.ContentType = "image/jpeg";
            image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
        }
    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }
}

Now just implement the GetImage method to load the image with the given ID, and you can use

<asp:Image runat="server" ImageUrl="~/Image.ashx?ID=myImageId" /> 

to display it. You might want to think about implementing some form of caching in the handler too. And remember if you want to change the image format to PNG, you need to use an intermediate MemoryStream (because PNGs require a seekable stream to be saved).

Leave a Comment