12.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—omitting any head or body tags to link
the .aspx page to the code-behind class that
retrieves and displays the images.
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.
Open a connection to the database that contains the images.
Build a query string, and read the byte array of the desired image from the database.
Set the content type for the image and write it to the
Responseobject.
Example 12-10 through Example 12-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.
Example 12-13 through Example 12-15 show ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access