views:

866

answers:

2

I have a byte array representing a picture. I want to present the picture stored in that byte array in an aspx page. Can I do it using an image or imagemap control? If so - how? If not - what's the solution?

+4  A: 

Think about how normal images are served in a web page - the filename is referenced in markup, and the browser sends a separate request to the server for that file.

The same principle applies here, except instead of referencing a static image file, you would want to reference an ASP.NET handler that serves the bytes of the image:

<img src="/imagehandler.ashx" />

The short of the handler would look something like this:

public class ImageHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.OutputStream.Write(imageData, 0, imageData.Length);
        context.Response.ContentType = "image/JPEG";
    }
}

Here's a (long) resource that covers the concepts of creating an HttpHander in ASP.NET.

Also, as Joel points out, think about where the byte array is coming from, since the HttpHandler is served in a totally different request than the page. At the most basic level, the two requests are not aware of each other or share any data.

A common solution to this problem is to put the image data in cache:

Guid id = Guid.NewGuid();
HttpRuntime.Cache.Add(id.ToString(), imageData);

And pass the key to the HttpHandler in the querystring, so it can fetch it from cache:

<img src="/imagehandler.ashx?img=<%=id%>" />
<!-- will print ...ashx?img=42a96c06-c5dd-488c-906f-cf20663d0a43 -->
Rex M
+1 - also note this means that you will likely need to re-think how your current page works, since you likely obtained the byte array in the course of processing a request for a different resource.
Joel Coehoorn
Good point Joel.
Rex M
+2  A: 

You could write a generic handler which will serve the picture:

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

public class Picture : System.Web.IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        byte[] buffer = GetPictureFromSomewhere();
        context.Response.ContentType = "image/jpeg";
        context.Response.OutputStream.Write(buffer, 0, buffer.Length);
    }

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

And then call it in an aspx page:

<asp:Image ID="pic" runat="server" ImageUrl="~/Picture.ashx" />
Darin Dimitrov