Search code examples
c#asp.netimagehttphandler

How to pass binary image to image handler to display it in DataList?


I have a web page with a method called to display some images in the DataList control

MyImage.cs

class MyImage
{
    string Name { get; set; }
    byte[] Jpeg { get; set; } 
}

MyImages.aspx.cs

public void DisplayMyImages(IEnumerable<MyImage> myImages)
{
    this.myImagesDataList.DataSource = myImages;
    this.myImagesDataList.DataBind();  
}

/// ...

protected void myImagesDataList_ItemDataBound(object sender, DataListItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item ||
        e.Item.ItemType == ListItemType.AlternatingItem)
    {
        MyImage myImage = (MyImage)e.Item.DataItem;
        Image myImageImage = (Image)e.Item.FindControl("myImageImage");

        // How to pass myImage.Jpeg to ImageHandler? form here

        myImageImage.ImageUrl = "~/Handlers/ImageHandler.ashx";
    }
}

But how to pass jpeg image to ImageHandler if it is already extracted from the database and passed to DisplayMyImages() function?

Remarks:

I do not want to save them back to files and pass the paths in a query string to ImageHandler

Having a standard query string approach is not possible as I do not want to violate model view presenter approach


Solution

  • I've just answered your question on CodeProject, but I'll copy the answer here as well.

    Depending on how big your images are, and which browsers you need to support, you might be able to use a data URI.

    myImageImage.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(myImage.Jpeg);
    

    (If you're using IE8, you're limited to 32Kb; earlier versions of IE aren't supported at all.)