Search This Blog

Friday, April 16, 2010

How to display image stored in database in byte format in ASP.NET

It is very common these days to display an image on .aspx page from database. Here is an example of how it is possible.

As the image is in byte format you need to first display it on a separate .aspx page (or .ashx page as in our case) and then give the link of this page as the url for image control.

Right click on your project -> Add new item -> add a Generic handler to your project and name it ImgHandler.ashx.
Now we need to display the image on this page. We will assume that we get the ID from Request.Query String like this :-
string imageid = Context.Request.QueryString["ID"];

Make an SQLConnection and fetch the image and image type based on ID.
Now simply display this image by using BinaryWrite method like this:
byte[] ByteArray = (byte[])reader["Image"];
Context.Response.ContentType = "image/pjpeg"; // for jpeg images
Context.Response.BinaryWrite(ByteArray);

Full code
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
public class ImgHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
SqlConnection con;
con = new SqlConnection(connectionString);
con.Open();
string ImageID = Context.Request.QueryString["ID"];
SqlCommand com = new SqlCommand("Select * from ABC where ID=" + ImageID,con);
SqlReader reader = com.ExecuteReader();
reader.Read();
byte[] ByteArray = (byte[])reader["Image"];
context.Response.ContentType = "image/pjeg";
context.Response.BinaryWrite(ByteArray);
con.Close()
}
}
On the image control (html image control) write
src = ''

No comments:

Post a Comment