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 ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.