Display binary stream received from database as "image" inside html as <img> tag
I am trying to display an image that is being retrieved from a database as a binary stream in a web form. Can you shed some light on this!
I am working on a project in which users have profiles, and each user has their own profile picture displayed on the main page. This image comes from a database.
here is the code i used to get the stream!
TestDBDataContext context1 = new TestDBDataContext(); var r = (from a in context1.ImageTables where a.Id == 8 select a).First(); MemoryStream stream = new MemoryStream(r.FileImage.ToArray()); thanks
What I have done in the past sets the URL of the image on the aspx page, for example:
<img src="getLogo.aspx" alt="Logo" /> Then, in the code for getLogo.aspx, I did the following:
Response.BinaryWrite( imageData ); Response.ContentType = "image/gif"; Where imageData is your image as an array of bytes
Base64 encodes your binary and inserts it into the image tag as follows (change the mimetype type):
<img src="data:image/gif;base64,BASE64 ENCODED BINARY HERE"> Here is how you do it, but I wouldnโt do it, as some browsers cannot handle it (IE6). You better save the file first, and do it the usual way.
First you have a separate .aspx file for the image (in fact, I would prefer an IHttpHandler overload for this, but the principle is the same, and let it introduce only one new concept at a time).
The .aspx file is simply inherited from the code and has no content. That way, he would have a directive <%@ Page %> and nothing more.
At the end of the code, in the page load event handler, get the image and set the type of the response content to the appropriate value (or, if, for example, all the images are image / png, you can just hard code that). Then write the image to the output.
TestDBDataContext context1 = new TestDBDataContext(); int id; if(int.TryParse(Request.QueryString["id"], out id)) { var r = (from a in context1.ImageTables where a.Id == 8 select a).FirstOrDefault(); if(r != null) { Response.ContentType = r.ContentType; Response.BinaryWrite(r.FileImage.ToArray()); return; } } //code to handle 404 not found for no such image here (send error message or Server.Transfer to error page, etc. Then you can use this with <img src="profileImg.aspx?id=8" alt="" /> etc.
Performance improvement is getting 4,000 bytes at a time from the database and writing them to Response.OutputStream , and not just one massive array in memory. For small files, the difference is not significant, but for very large files it can be significant (as in โcheers, now my web server no longer crashes anymore!โ).