O'Reilly logo

ASP.NET 2.0 Cookbook, 2nd Edition by Geoffrey T. LeBlond, Michael A Kittel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

15.3. Displaying Images Stored in a Database

Problem

Your application stores images in a database that you want to display on a web form.

Solution

Create a web form that reads the image data from the database and streams the image to the Response object.

In the .aspx file, enter an @ Page directive and omit any head or body tags to link the .aspx page to the code-behind class that retrieves and displays the images:

  1. Read the image ID that is generated by the running application—for example, the image ID passed in the URL for accessing the web form.

  2. Open a connection to the database that contains the images.

  3. Build a query string, and read the byte array of the desired image from the database.

  4. Set the content type for the image and write it to the Response object.

Examples 15-10, 15-11 through 15-12 show the .aspx file and VB and C# code-behind files for an application that implements the image-building portion of the solution.

To use this dynamic image generation technique in your application, set the src attribute of the image tags used to display the images to the URL of the ASP.NET page that reads the images from the database, passing the image ID in the URL.

In the .aspx file for the page, add an img tag for displaying the image.

In the code-behind class for the page that uses the image, use the .NET language of your choice to set the src attribute of the image tag to the URL for the web form just described, passing the ID of the image in the URL.

Examples 15-13, 15-14 through 15-15 show the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required