May 17, 2023

How to stream image from generic handler

This article provides an example of streaming images from a generic handler in .NET.

If you store your images in a database table as byte[] then you can utilize a handler to display them in a data grid.

The process involves sending a request to the handler (.ashx) page, retrieving the image, and then displaying it.

In the given example, we have a grid that stores IDs in one column and displays the corresponding images in another column using an asp:ImageField.

Create a generic handler that streams image. In this example ImageField requests image from getFaceImage.ashx by DataImageUrlField parameter in DataImageUrlFormatString format

public void ProcessRequest(HttpContext context)
{
    int id;

    if (context.Request.QueryString["id"] != null)
    {
        id = Convert.ToInt32(context.Request.QueryString["id"]);

        if (id > 0)
        {
            context.Response.ContentType = "image/jpeg";

            Stream strm = new MemoryStream();
            GetImage(id).Save(strm, ImageFormat.Jpeg);
            strm.Position = 0;

            byte[] buffer = new byte[4096];
            int byteSeq = strm.Read(buffer, 0, 4096);
            while (byteSeq > 0)
            {
                context.Response.OutputStream.Write(buffer, 0, byteSeq);
                byteSeq = strm.Read(buffer, 0, 4096);
            }
        }
    }
    else
        return;
}

public Image GetImage(int id)
{
    //Make appropriate calls for image according to id
    //...

    //return the image
    return new Bitmap("");
}