To read the article online, visit http://www.4GuysFromRolla.com/articles/011503-1.aspx

Displaying a List of Scaled Images

By Scott Mitchell


Introduction


A question I saw recently on one of the ASPAdvice.com ListServs had to do with enumerating through the list of files in a directory. I helped answer this poster's question, and decided that perhaps 4Guys readers would be interested in this information. So I decided to write up an article on how to display the images residing in a directory using this approach. In creating an ASP.NET Web page that accomplished this, I soon found that if the images in the directory had wildly varying image sizes, the format of the page was quite haphazard.

To fix this problem, I needed to be able to determine the image's width and height and then, if these image properties were greater than some specified maximum, the image needed to be scaled accordingly. In this article we will examine two things: first, how to list the images in a directory (which can be generalized to how to list enumerate through any files in a directory); second, we'll see how to use the .NET Framework's Image class to determine an image's height and width.

Enumerating Through the Files of a Directory


The .NET Framework provides a number of classes to work with the Web server's file system, the most useful two being the Directory and File classes, which both contain a number of static methods that perform a variety of tasks. For example, to create a new text file you can use the File.CreateText() method. (For more information on working with text files in an ASP.NET Web page be sure to read: Reading Text Files in an ASP.NET Web Page.)

In order to enumerate through the files in a directory, use the Directory.GetFiles() method. This method returns a string array, with paths to the files in the directory. The method can be used in one of two ways:

filesInDirectory = Directory.GetFiles(directoryPath)

Which returns the paths to the files in the directory directoryPath as a string array. If you want to only get particular files from the directory, you can specify an option second input parameter like so:

filesInDirectory = Directory.GetFiles(directoryPath, searchPattern)

The searchPattern can have values using the wildcard symbol *, like *.txt, SomeFile*.doc, etc. For example, if you only want to get .txt files from the directory C:\SomeDir you could use the following code:

Dim textFiles as String() = Directory.GetFiles("C:\SomeDir", "*.txt")

Imagine that we have a directory that has a number of image files in it, and we want to display all the GIF files in a Web page. To enumerate through all of the GIF files we can use the following code:

Dim s as String
For Each s in Directory.GetFiles(Image Directory Path, "*.gif")
  ...
Next

But what should go inside of the For Each ... Next loop? In each iteration of the loop, s contains the physical path to the file. We'll want to display the image using an img tag, however, which expects as its src property the virtual path to the file. That is, if the images are stored in the directory C:\Images, which is accessible via our Web site at http://www.pictures.com/images/, the physical path for an image is C:\Images\imgFileName, whereas the virtual path is /images/imgFileName.

In order to properly render an img tag, we can use the following code in the For Each ... Next loop:

For Each s in Directory.GetFiles(Server.MapPath(IMAGE_DIRECTORY), "*.gif")
  html = "<a href=""" & IMAGE_DIRECTORY & Path.GetFileName(s) & """>" & _
         "<img src=""" & IMAGE_DIRECTORY & Path.GetFileName(s) & """>" & _
         "</a>"
Next

where IMAGE_DIRECTORY is the virtual path to the directory where the images are stored (i.e., /images/). (Note that Server.MapPath(virtual path) returns the physical path corresponding to the passed-in virtual path. See Using Server.MapPath() for more information.) The Path.GetFileName() method retrieves the file name portion from a file path. Keep in mind that s has a value like C:\Images\file.gif, and all we want is the file.gif portion for the img's src attribute and the a tag's href attribute - hence, we use Path.GetFileName(s) to snip out the file name portion.

Rather than displaying the contents of the variable html using Response.Write() or a Label Web control, let's use a DataList. In order to display the images in a DataList, we need to place the html value in a collection, such as an ArrayList. The following code will add html's contents to the ArrayList pics, and then bind the ArrayList to the DataList dlPictures.

<%@ Import Namespace="System.IO" %>
<script language="vb" runat="server">
  Sub Page_Load(sender as Object, e as EventArgs)
    Const IMAGE_DIRECTORY as String = "/images/"
    Dim pics as ArrayList = new ArrayList()
    Dim s as String, html as String
    
    For Each s in Directory.GetFiles(Server.MapPath(IMAGE_DIRECTORY), "*.gif")    
      html = "<a href=""" & IMAGE_DIRECTORY & Path.GetFileName(s) & """>" & _
             "<img src=""" & IMAGE_DIRECTORY & Path.GetFileName(s) & """>" & _
             "</a>"
             
      pics.Add(html)
    Next

    dlPictures.DataSource = pics
    dlPictures.DataBind()
  End Sub
</script>

<asp:DataList runat="server" id="dlPictures"  
     RepeatColumns="3" ItemStyle-HorizontalAlign="Center">    
  <ItemTemplate>
    <%# Container.DataItem %>
  </ItemTemplate>
</asp:DataList>
[View a Live Demo!]

A couple quick things to note here. First, note that we must import the System.IO namespace to use the Directory and Path classes. Next, in order to display the value of each ArrayList item, we use the syntax <%# Container.DataItem %> in our DataList's ItemTemplate.

Take a moment to check out the live demo. You'll note that some images are much bigger than others. Those that are, cause their table column to be wider than others, which leads to some ugly formatting, requiring horizontal scrolling. In order to deal with this, we need to dynamically resize our images, so that they are constrained to a specified height and width. We'll examine how to do this in Part 2.

  • Read Part 2!

  • Article Information
    Article Title: ASP.NET.Displaying a List of Scaled Images
    Article Author: Scott Mitchell
    Published Date: January 15, 2003
    Article URL: http://www.4GuysFromRolla.com/articles/011503-1.aspx


    Copyright 2017 QuinStreet Inc. All Rights Reserved.
    Legal Notices, Licensing, Permissions, Privacy Policy.
    Advertise | Newsletters | E-mail Offers