Monday, December 22, 2008

Displaying Images from Database into an ASP:IMAGE control

Just recently, while working on a project, I stumbled upon a need to fetch images from the SQL Database and display them in the image control on the page.

I did a bit of research and landed upon a concept of using GENERIC HANDLERS for that purpose.

I found that really useful as compared to any other approach of saving the files to disk and setting the URLs etc.

Here is what can be done:

1. Add a new GENERIC HANDLER (ImageDisplay.ashx) to the project.
2. Set the ImageControl's ImageUrl to this ashx page..
imgDisplay.ImageUrl = "ImageDisplay.ashx?imageId=1";
where imageId is the Database ID of the image that needs to be fetched.
3. Now write code to fetch data from Database for that imageId in the ProcessRequest event of the ashx page.

public void ProcessRequest(HttpContext context)
{
Int32 imageId = Convert.ToInt32(context.Request.QueryString["imageId"]);

// This is the function that returns the Byte Array from the Database
Byte[] pict = GetImageById(imageId);
context.Response.ContentType = "image/bmp";
context.Response.OutputStream.Write(pict, 0, pict.Length);
}

4. The method GetImageById would depend upon the Database and data-type that you have for the column for image. Since I had a MySQL database with BLOB column, which can hold a Byte[], the method was quite simple for me and I just had to pull it out from Database and insert it into a Byte[] object.

-- Ashutosh

5 comments:

  1. Anonymous17:58

    hi,
    what code u had written in the GetImageById () method??

    As i'm using this code so pleezz help me for the same..
    thanks in adv

    ReplyDelete
  2. hi ashutosh,
    ur this blog of displaying images help me alot bt i just wanted to knw what actual code u hd written in the GetImageById() method??
    Plz Help me,i'm in need of that....

    thanks in adv....

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. GetImageById() does a simpke select query on DB to fetch the byte[] from DB for the given ImageId.


    Thanks
    Ashutosh

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete