bytearray to image asp.net
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?
Another thing you can do which is quicker would be to not use the asp.net Image control and use the basic img element in html. So within your asp.net page, create a img element with an id of img and runat set to server.
Then you could do something like this:
<img id="img" runat="server" alt=""/>
public DataRow ClaimPhotoRow { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
img.Src = "data:image/jpg;base64," + Convert.ToBase64String((byte[])ClaimPhotoRow[0]);
}
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 -->
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" />