With conventional XHTML coding, graphic images are displayed on a page by using an <img> tag. Under ASP.NET, the <asp:Image> control takes on this function. It identifies an area on the page where a static image is displayed or where a script can dynamically place or interchange images. Its general format is shown below.
<asp:Image id="id" Runat="Server" AlternateText="string" ImageAlign="Bottom|Left|Middle|Right|Top|TextTop|AbsBottom|AbsMiddle| AbsBaseLine|NotSet" ImageURL="url" property="value"... />
The ImageUrl property gives the URL of the image; this can be a relative or absolute URL address. The AlternateText property gives alternate text displayed when the mouse is positioned over the image, and the ImageAlign attribute specifies text alignment around an in-line image. Width and Height properties can be applied to display a revised size for the image. Normally, one or the other of these settings is coded to maintain proportionality of the image.
Displaying Static Images
The following output shows three images with various alignments in relation to their accompanying text. All are static images requiring no scripting.
Here is an image with text aligned with its middle.
Here is an image floated to the left of this text.
<form Runat="Server"> <asp:Panel HorizontalAlign="Center" Runat="Server"> <asp:Image Runat="Server" ImageURL="aspnet2.gif" AlternateText="ASP.NET Logo"/> </asp:Panel> <p>The above image is centered on a line by itself.</p> <p>Here is an image <asp:Image Runat="Server" ImageURL="aspnet2.gif" AlternateText="ASP.NET Logo" ImageAlign="AbsMiddle"/> with text aligned with its middle.</p> <asp:Image Runat="Server" ImageURL="aspnet2.gif" AlternateText="ASP.NET Logo" Style="float:left"/> <p>Here is an image floated to the left of this text.</p> </form>
The first of the images is centered on a line by itself. An Image control itself cannot be aligned horizontally across a line. It must be placed inside a page-width (block-level) container tag to which alignment is applied. In this example, an <asp:Panel> control contains the image to which it applies the HorizontalAlign="Center" style property.
The second of the images appears in-line with surrounding text. This Image control's ImageAlign="AbsMiddle" property aligns the accompanying text vertically with the middle of the image.
The third of the images floats to the left of its accompanying text. There is no server style property for floating controls to the left or right of the page. Therefore, the Image control is styled with the CSS float:left property.
Scripting Image Displays
An Image control can be scripted. One of the ways to script an image is to set its Visible property to show or hide a picture. In the following example, clicking the button makes an image appear; clicking the button again hides the image. The text label of the button changes to indicate its action.
<SCRIPT Runat="Server"> Sub Show_Image (Src As Object, Args As EventArgs) If MyButton.Text = "Show Image" Then MyImage.Visible = "True" MyButton.Text = "Hide Image" Else MyImage.Visible = "False" MyButton.Text = "Show Image" End If End Sub </SCRIPT> <form Runat="Server"> <asp:Button id="MyButton" Text="Show Image" Runat="Server" OnClick="Show_Image"/> <asp:Image id="MyImage" Runat="Server" ImageURL="aspnet2.gif" ImageAlign="Top" AlternateText="ASP.NET 2.0 logo" Visible="False"/> </form>
Initially, the Visible property of the image is set to "False" to hide its display, and the button's label (its Text property) is set to "Show Image". When the button is clicked, the subprogram checks the button's Text property. If the label reads "Show Image", then the Visible property of the image is changed to True and the button's Text is changed to "Hide Image". Alternately, the Visible property of the image is set to False and the button's label is set to "Show Image".
A second method of scripting an Image control is to change its ImageURL property to assign a different image to the control. The following script is a variation on the above script. This time, rather than showing and hiding a single image, two images are alternated after testing which one currently is being displayed.
<SCRIPT Runat="Server"> Sub Switch_Image (Src As Object, Args As EventArgs) If MyImage.ImageURL = "aspnet2.gif" Then MyImage.ImageURL = "xhtml.gif" Else MyImage.ImageURL = "aspnet2.gif" End If End Sub </SCRIPT> <form Runat="Server"> <asp:Button Text="Switch Image" OnClick="Switch_Image" Runat="Server"/> <asp:Image id="MyImage" Runat="Server" ImageURL="aspnet2.gif" ImageAlign="Top"/> </form>
Using Arrays for Image Display
When displaying a sequence of several images, their URLs can be conveniently stored in a Visual Basic array to keep track of the sequence in which they are displayed. A called subprogram can reference the next image in sequence by referencing its array index, moving from the first through the last index. This technique is used in the following example of displaying three different images through the same <asp:Image> control. The array index is displayed in a Label below the image.
Array index: 0
<SCRIPT Runat="Server"> Sub Page_Load If Not Page.IsPostBack Then '-- Load an array with image urls and save to View State Dim ImageArray(3) As String ImageArray(0) = "aspnet2.gif" ImageArray(1) = "xhtml.gif" ImageArray(2) = "jsdhtml.gif" ViewState("PictureArray") = ImageArray '-- Establish a counter to keep track of the array index ViewState("Counter") = 0 MyImage.ImageURL = ImageArray(ViewState("Counter")) Index.Text = ViewState("Counter") End If End Sub Sub Get_Next_Image (Src As Object, Args As EventArgs) '-- Retrieve the array from view state Dim ImageArray() As String ImageArray = ViewState("PictureArray") '-- Increment the image counter ViewState("Counter") += 1 If ViewState("Counter") > 2 Then ViewState("Counter") = 0 End If '-- Assign the next image to the control MyImage.ImageURL = ImageArray(ViewState("Counter")) Index.Text = ViewState("Counter") End Sub </SCRIPT> <form Runat="Server"> <asp:Image id="MyImage" ImageAlign="AbsMiddle" Runat="Server"/> <asp:Button Text="Next Image" OnClick="Get_Next_Image" Runat="Server"/> <p>Array index: <asp:Label id="Index" Runat="Server"/></p> </form>
Consider first the form controls. An <asp:Image> control identifies an area on the page to display an image. No ImageURL property is coded since this assignment is under script control. An <asp:Button> control triggers the Get_Next_Image subprogram to increment through three images retrieved from the current the folder. An <asp:Label> control displays the array index of the current image.
To keep track of images available for display, a Visual Basic array named ImageArray is declared and loaded with image URLs (just the file names are stored since the images are in the same folder as the page). ImageArray is built only the first time the page is loaded. It is assigned to ViewState("PictureArray"), ensuring that the array of values will be maintained in the page's View State and be available to the page on subsequent post-backs.
In addition, ViewState("Counter") is declared to keep track of the array index of the appropriate image to display. It is initalized with a value of 0 to point to the first image in the array, the initial image displayed. Therefore, the image referenced by ImageArray(ViewState("Counter")), i.e., ImageArray(0), is assigned as the ImageURL of the Image control the first time the page loads.
When the button is clicked, subprogram Get_Next_Image assigns the next URL in the array to the ImageUrl property of the Image control. First, the array saved in View State is retrieved to make it available to this subprogram. Then, the index counter is incremented to point to the next image in the array. Of course, if ViewState("Counter") increments past the last element of the array (2), it is reset to point to the first element (0). Again, the image referenced by ImageArray(ViewState("Counter")) is assigned as the ImageURL of the Image control. The index value also is displayed in the Label for visual verification of the current array index.
Creating Arrays from Databases
The previous example creates an array of image references by assigning fixed values to array elements. You can, instead, load an array from information stored in a database and use these references to point to picture files. In the following example, BookID values from the BooksDB.mdb database are loaded into an array. A button increments through the array to display associated pictures.
The layout of the page is shown in the following listing. A Panel encompasses an Image control and a Label to display a picture and its file name. A Button calls the Get_Book_Picture subprogram to display the next picture in sequence from image references stored in an array.
<h3>Book Pictures</h3> <asp:Panel HorizontalAlign="Center" Style="float:left" Runat="Server"> <asp:Image id="BookPicture" Runat="Server"/><br/> <asp:Label id="BookName" Runat="Server"/> </asp:Panel> <asp:Button Text="Next Picture" OnClick="Get_Next_Picture" Runat="Server"/>
When this page is first loaded, an array of picture names is created. All BookID values in the database are retrieved, and picture file names are stored in the array. These file names are concatenations of the BookIDs and the ".jpg" extension. The final array is saved to a View State variable for recreation each time the page is posted back by the button click.
<%@ Import Namespace="System.Data.OleDb" %> <SCRIPT Runat="Server"> Sub Page_Load If Not Page.IsPostBack Then '-- Load an array with images and save to View State Dim DBConnection As OleDbConnection Dim DBCommand As OleDbCommand Dim DBReader As OleDbDataReader Dim SQLString As String Dim RecordCount As Integer DBConnection = New OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & Server.MapPath("../Databases/BooksDB.mdb")) DBConnection.Open() '-- Get a count of records SQLString = "SELECT Count(*) FROM Books" DBCommand = New OleDbCommand(SQLString, DBConnection) RecordCount = DBCommand.ExecuteScalar() '-- Create an array of size RecordCount of picture file names SQLString = "SELECT BookID FROM Books ORDER BY BookID" DBCommand = New OleDbCommand(SQLString, DBConnection) DBReader = DBCommand.ExecuteReader() Dim BookArray(RecordCount) As String Dim BookIndex As Integer = 0 While DBReader.Read() BookArray(BookIndex) = DBReader("BookID") & ".jpg" BookIndex += 1 End While DBReader.Close() DBConnection.Close() '-- Save array and variables to View State ViewState("BookArray") = BookArray ViewState("BookIndex") = 0 ViewState("RecordCount") = RecordCount '-- Display first picture BookPicture.ImageURL = "../BookPictures/" & BookArray(0) BookName.Text = BookArray(0) End If End Sub </SCRIPT>
Although it is known that there are 30 records in the database, this count may change over time. Therefore, the array of picture file names is dimensioned to a size of however many records are currently in the database. This size is given by issuing a "SELECT Count(*) FROM Books" statement and storing the returned count in variable RecordCount. This variable, then, is used to dimension the array: Dim BookArray(RecordCount) As String.
After the array is built, it is saved to View StateViewState("BookArray")along with an index to the array and the record count: ViewState("BookIndex") and ViewState("RecordCount"). All of these data elements are needed in subsequent post-backs of the page.
The first picture is displayed when the page loads. The ImageUrl of the Image control is set to the URL given by concatenating the path to the picture files with the first element in the array: "../BookPictures/" & BookArray(0). The name of the picture is assigned to the Text property of the accompanying Label.
When the "Next Picture" button is clicked, subprogram Get_Next_Picture is called. This subprogram creates a new array from ViewState("BookArray"), increments ViewState("BookIndex") to point to the next element in the array, and assigns new values to the ImageUrl and Text properties of the page controls.
Sub Get_Next_Picture (Src As Object, Args As EventArgs) '-- Retrieve array from view state Dim BookArray() As String = ViewState("BookArray") '-- Increment the image counter ViewState("BookIndex") += 1 If ViewState("BookIndex") = ViewState("RecordCount") Then ViewState("BookIndex") = 0 End If '-- Assign the next image to the control BookPicture.ImageURL = "../BookPictures/" & BookArray(ViewState("BookIndex")) BookName.Text = BookArray(ViewState("BookIndex")) End Sub
If the ViewState("BookIndex") value is incremented past the last element of the arrayas given by ViewState("RecordCount")it is reset to 0 to begin anew at the first element of the array. Note that the array element containing the picture reference is given by BookArray(ViewState("BookIndex")). That is, ViewState("BookIndex"), which is incremented and maintained between page posts, is the index to BookArray, which is recreated from ViewState("BookArray") each time the page is posted back.
Sizing Images
The common Width and Height server styles can be applied to the Image control to resize an image. Normally, either Width or Height is applied, but not both, in order to let the browser determine the other dimension to maintain proportionality of the image. The following example dynamically changes the Width of an image to increase or decrease its size.
<SCRIPT Runat="Server"> Sub Size_Image_Down (Src As Object, Args As EventArgs) Dim Size As Integer = Replace(MyImage3.Width.toString(), "px", "") Size -= 20 If Size < 20 Then Size = 20 End If MyImage.Width = Size End Sub Sub Size_Image_Up (Src As Object, Args As EventArgs) Dim Size As Integer = Replace(MyImage3.Width.toString(), "px", "") Size += 20 If Size > 300 Then Size = 300 End If MyImage.Width = Size End Sub </SCRIPT> <form Runat="Server"> <asp:Button Text=" « " OnClick="Size_Image_Down" Runat="Server"/> <asp:Button Text=" » " OnClick="Size_Image_Up" Runat="Server"/> <asp:Image id="MyImage" Runat="Server" ImageURL="aspnet2.gif" Width="150" ImageAlign="Top"/> </form>
When subprogram Size_Image_Down is called, it resets the width of the image to -20 pixels less than its current size. First, it captures the current Width property of the image as integer variable Size in order to perform the computation. Recall that server Width (and Height) properties are expressed in special styling "Units." This unit measurement must be converted to string format for further manipulation using the Visual Basic toString() method (MyImage.Width.toString()). Also, the Width value gives the measurement in pixels, for example, "150px". Therefore, this string must have the "px" suffix removed before it can be assigned to integer variable Size.
Dim Size As Integer = Replace(MyImage3.Width.toString(), "px", "")
Once these conversions are made, variable Size is reduced by 20 pixels (Size -= 20) and the new value is assigned as the new Width property of the image. A test is made to ensure that the calculated width does not fall below 20 pixels, causing the image to disappear and producing invalid negative measurements. If it does, it is reset to 20 pixels.
Similar coding is used for the Size_Image_Up subprogram. In this case, the image width is incremented by 20 pixels each time the button is clicked.