Recipe 15.4. 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 applicationfor 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 .aspx file and VB and C# code-behind files for an application that uses the dynamic image generation. Figure 15-3 shows some typical output from the application.

Discussion

If you have images in a database that you want to display on a web form, chances are you've considered using an image tag to display them. Nevertheless, you may be searching for a practical way to set the image tag's src attribute and move the image data to the browser while maintaining the maximum flexibility in selecting the images you need.

The solution we favor involves creating a web form that reads an image from a database and streams it to the Response object. A convenient way to specify the image to read from the database is to include an image ID in the URL used to call the web form that retrieves and returns the image to the browser.

Figure 15-3. Displaying images from a database


Our example that illustrates this solution consists of two web forms. The first web form renders no HTML but instead processes the request for reading an image from the database. The second web form is used to demonstrate displaying an image from the database.

The .aspx file of the first form contains no head or body; it simply contains the @ Page directive to link the page to its code-behind class.

The Page_Load method of the code-behind performs the following four steps to retrieve the requested image from the database and send it to the browser:

  1. Retrieve the ID of the requested image from the URL.

  2. Read the byte array of the image from the database.

  3. Set the ContentType of the type of image stored in the database (GIF in this example).

  4. Write the byte array of the image to the Response object.

To use the ASP.NET page to retrieve images from the database, we need to set the src attribute of an image tag to the name of the page just described, passing the ID of the desired image in the URL. A sample URL is shown here:

 src="/books/1/505/1/html/2/CH15ImageFromDatabaseVB.aspx?ImageID=13"  

In our example, the src attribute of an img tag is set in the view image button click event of the test page code-behind.

The performance of this solution can be significantly improved by caching the images retrieved from the database instead of retrieving them for each request. Refer to Recipe 16.3 for an example of how to cache the results as a function of the data passed in the QueryString.

An HttpHandler can be used to implement the same functionality described in this recipe. Refer to Recipe 20.1 for an example of retrieving images from a database using an HttpHandler.

Images can be stored in a database using the technique described in Recipe 18.4.

See Also

Recipes 16.2, 18.4, and 20.1

Example 15-10. Reading images from a database (.aspx)

 <%@ Page Language="VB" AutoEventWireup="false" CodeFile="CH15ImageFromDatabaseVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH15ImageFromDatabaseVB" %> 

Example 15-11. Reading images from a database code-behind (.vb)

 Option Explicit On Option Strict On Imports System Imports System.Configuration.ConfigurationManager Imports System.Data Imports System.Data.Common Imports System.Data.OleDb Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code-behind for ''' CH15ImageFromDatabaseVB.aspx ''' </summary> Partial Class CH15ImageFromDatabaseVB Inherits System.Web.UI.Page 'constants used to create URLs to this page Public Const PAGE_NAME As String = "CH15ImageFromDatabaseVB.aspx" Public Const QS_IMAGE_ID As String = "ImageID" '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the page load event. It ''' is responsible for initializing the controls on the page. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Private Sub Page_Load(ByVal sender As Object, _   ByVal e As System.EventArgs) Handles Me.Load Dim dbConn As OleDbConnection = Nothing Dim dCmd As OleDbCommand Dim imageData( ) As Byte Dim strConnection As String Dim strSQL As String Dim imageID As String If (Not Page.IsPostBack) Then Try 'get the ID of the image to retrieve from the database imageID = Request.QueryString(QS_IMAGE_ID) 'get the connection string from web.config and open a connection 'to the database strConnection = _ ConnectionStrings("dbConnectionString").ConnectionString dbConn = New OleDb.OleDbConnection(strConnection) dbConn.Open( ) 'build the query string and get the data from the database strSQL = "SELECT ImageData " &_  "FROM BookImage " &_  "WHERE BookImageID=?" dCmd = New OleDbCommand(strSQL, dbConn) dCmd.Parameters.Add(New OleDbParameter("BookImageID", imageID)) imageData = CType(dCmd.ExecuteScalar( ), Byte( )) 'set the content type for the image and write it to the response Response.ContentType = "image/gif" Response.BinaryWrite(imageData) Finally 'clean up If (Not IsNothing(dbConn)) Then dbConn.Close( ) End If End Try End If End Sub 'Page_Load End Class 'CH15ImageFromDatabaseVB End Namespace 

Example 15-12. Reading images from a database code-behind (.cs)

 using System; using System.Configuration; using System.Data; using System.Data.Common; using System.Data.OleDb; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code-behind for /// CH15ImageFromDatabaseCS.aspx /// </summary> public partial class CH15ImageFromDatabaseCS : System.Web.UI.Page { // constants used to create URLs to this page public const String PAGE_NAME = "CH15ImageFromDatabaseCS.aspx"; public const String QS_IMAGE_ID = "ImageID"; ///*********************************************************************** /// <summary> /// This routine provides the event handler for the page load event. /// It is responsible for initializing the controls on the page. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void Page_Load(object sender, EventArgs e) { OleDbConnection dbConn = null; OleDbCommand dCmd = null; byte[] imageData = null; String strConnection = null; String strSQL = null; String imageID = null; if (!Page.IsPostBack) { try { // get the ID of the image to retrieve from the database imageID = Request.QueryString[QS_IMAGE_ID]; // get the connection string from web.config and open a connection // to the database strConnection = ConfigurationManager. ConnectionStrings["dbConnectionString"].ConnectionString; dbConn = new OleDbConnection(strConnection); dbConn.Open( ); // build the query string and get the data from the database strSQL = "SELECT ImageData " +  "FROM BookImage " +  "WHERE BookImageID=?"; dCmd = new OleDbCommand(strSQL, dbConn); dCmd.Parameters.Add(new OleDbParameter("BookImageID", imageID)); imageData = (byte[])(dCmd.ExecuteScalar( )); // set the content type for the image and write it to the response Response.ContentType = "image/gif"; Response.BinaryWrite(imageData); } finally { // clean up if (dbConn != null) { dbConn.Close( ); } } } } // Page_Load } // CH15ImageFromDatabaseCS } 

Example 15-13. Displaying images from a database (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH15TestImageFromDatabaseVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH15TestImageFromDatabaseVB" Title="Test Image From Database" %> <asp:Content  runat="server" ContentPlaceHolder> <div align="center" > Display Image From Database (VB) </div> <table align="center" width="50%" border="0"> <tr> <td> <asp:DropDownList  Runat="server" /> </td> <td> <input  runat="server" type="button" value="View" onserverclick="btnViewImage_ServerClick"/> </td> </tr> <tr> <td  runat="server" colspan="2" align="center" > <br /><br /> Selected Image<br /><br /> <img  runat="server" border="0" src="/books/1/505/1/html/2/" alt="book"/> </td> </tr> </table> </asp:Content> 

Example 15-14. Displaying images from a database code-behind (.vb)

 Option Explicit On Option Strict On Imports System.Configuration Imports System.Data Imports System.Data.Common Imports System.Data.OleDb Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code-behind for ''' CH15TestImageFromDatabaseVB.aspx ''' </summary> Partial Class CH15TestImageFromDatabaseVB Inherits System.Web.UI.Page '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the page load event. It ''' is responsible for initializing the controls on the page. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Private Sub Page_Load(ByVal sender As Object, _   ByVal e As System.EventArgs) Handles Me.Load Dim dbConn As OleDbConnection = Nothing Dim dc As OleDbCommand Dim dr As OleDbDataReader Dim strConnection As String Dim strSQL As String If (Not Page.IsPostBack) Then 'initially hide the selected image since one is not selected tdSelectedImage.Visible = False Try 'get the connection string from web.config and open a connection 'to the database strConnection = ConfigurationManager. _ ConnectionStrings("dbConnectionString").ConnectionString dbConn = New OleDb.OleDbConnection(strConnection) dbConn.Open( ) 'build the query string and get the data from the database strSQL = "SELECT BookImageID, Title " &_  "FROM BookImage" dc = New OleDbCommand(strSQL, dbConn) dr = dc.ExecuteReader( ) 'set the source of the data for the repeater control and bind it ddImages.DataSource = dr ddImages.DataTextField = "Title" ddImages.DataValueField = "BookImageID" ddImages.DataBind( ) Finally 'clean up If (Not IsNothing(dbConn)) Then dbConn.Close( ) End If End Try End If End Sub 'Page_Load '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the view image click event. ''' It is responsible for setting the src attibute of the imgBook tag to ''' the page that will retrieve the image data from the database and ''' stream to the browser. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub btnViewImage_ServerClick(ByVal sender As Object, _   ByVal e As System.EventArgs) 'set the source for the selected image tag imgBook.Src = "CH15ImageFromDatabaseVB.aspx?Imagetitle-IDAOKWP1">Example 15-15. Displaying images from a database code-behind (.cs)

 using System; using System.Configuration; using System.Data; using System.Data.OleDb; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code-behind for /// CH15TestImageFromDatabaseCS.aspx /// </summary> public partial class CH15TestImageFromDatabaseCS : System.Web.UI.Page { ///*********************************************************************** /// <summary> /// This routine provides the event handler for the page load event. /// It is responsible for initializing the controls on the page. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void Page_Load(object sender, EventArgs e) { OleDbConnection dbConn = null; OleDbCommand dc = null; OleDbDataReader dr = null; String strConnection = null; String strSQL = null; if (!Page.IsPostBack) { // initially hide the selected image since one is not selected tdSelectedImage.Visible = false; try { // get the connection string from web.config and open a connection // to the database strConnection = ConfigurationManager. ConnectionStrings["dbConnectionString"].ConnectionString; dbConn = new OleDbConnection(strConnection); dbConn.Open( ); // build the query string and get the data from the database strSQL = "SELECT BookImageID, Title " +  "FROM BookImage"; dc = new OleDbCommand(strSQL, dbConn); dr = dc.ExecuteReader( ); // set the source of the data for the repeater control and bind it ddImages.DataSource = dr; ddImages.DataTextField = "Title"; ddImages.DataValueField = "BookImageID"; ddImages.DataBind( ); } finally { // clean up if (dbConn != null) { dbConn.Close( ); } } } } // Page_Load ///*********************************************************************** /// <summary> /// This routine provides the event handler for the view image click /// event. It is responsible for setting the src attibute of the imgBook /// tag to the page that will retrieve the image data from the database /// and stream it to the browser. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void btnViewImage_ServerClick(Object sender,    System.EventArgs e) { // set the source for the selected image tag imgBook.Src = "CH15ImageFromDatabaseCS.aspx?ImageID=" + ddImages.SelectedItem.Value.ToString( ); // make the selected image visible tdSelectedImage.Visible = true; } // btnViewImage_ServerClick } // CH15TestImageFromDatabaseCS } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net