1

I have images stored in my database table and looking to read from the database and output these images in my asp.net page. Does anyone have any suggestions or tips for doing this?

Thanks

Funky
  • 12,890
  • 35
  • 106
  • 161
  • 1
    What have you tried so far? You could use a separate HttpHandler to serve up the images, or you could just save the images to the webroot and serve them up as static files. – rsbarro Mar 28 '11 at 15:01
  • 1
    On a side note. You may wish to reconsider storing your images in the database. There is another SOF QandA about it http://stackoverflow.com/questions/561447/store-pictures-as-files-or-in-the-database-for-a-web-app – Tim B James Mar 28 '11 at 16:09
  • Don't worry, I know better to not store images in a database! Unfortunately this is a requirement from my boss – Funky Mar 29 '11 at 08:55

2 Answers2

2

You should create an ashx handler. Then in your page output insert some tag <img src="yourhandler.ashx?id=yourid" ..> In the handler class you read the image from the DB and stream down to the client with Response.Write. Remember to set the content type properly. Here an example: http://www.developerfusion.com/code/5223/using-ashx-files-to-retrieve-db-images/. As soon you have a first version working, you probably need to improve it by adding some cache handling, but let's start creating the handle :)

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
1

You could do something like this:

Create separate page which will retrieve the image from the Db, and set the image src to the new pages url. Pass a query string with the ID of the photo or some means of you being able to get it from the DB.

On the new page have some code like this:

     if (Request.QueryString["imageId"] != null)
                {
                    int imgId= int.Parse(Request.QueryString["imageId"]);

byte[] photoBytes= //get photo bytes from the DB here...


                    if (photoBytes != null)
                    {
                        if (photoBytes.Length > 0)
                        {
                            byte[] bImage;
                            bImage = photoBytes;

//write the bytes to the response.. the page that has referenced this page as the img src will sow the image  
                            Response.BinaryWrite(bImage);

                        }
                    }
                }
Bex
  • 4,898
  • 11
  • 50
  • 87
  • 1
    I wouldn't use an aspx page for this. It would be more appropriate to use an ashx or just write a new HttpHandler. An ASP.NET page would work, but is too heavy for this operation. You also should set the response type in there somewhere ("image/jpeg", etc). – rsbarro Mar 28 '11 at 15:15
  • I agree there .. using an ashx is better, but this worked for me as a handler wasn't an option at the time! :) – Bex Mar 28 '11 at 15:29