Listing the Images in a Directory Demo with Image Resizing

This demo builds on the previous one by intelligently resizing the images so that no image's height or width exceeds 200 pixels. The Image class is used to dynamically determine each image's height and width, which is then scaled, if needed.

Source Code
<%@ Import Namespace="System.IO" %>
<script language="vb" runat="server">

  Sub Page_Load(sender as Object, e as EventArgs)
    Const IMAGE_DIRECTORY as String = "/images/"
    Const maxWidth as Integer = 200
    Const maxHeight as Integer = 200
    Dim pics as ArrayList = new ArrayList()
    Dim s as String, html as String
    Dim imgHeight, imgWidth as Integer
    For Each s in Directory.GetFiles(Server.MapPath(IMAGE_DIRECTORY), "*.gif")    
      'Get information about the image
      Dim currentImage as System.Drawing.Image = System.Drawing.Image.FromFile(s)
      imgHeight = currentImage.Height
      imgWidth = currentImage.Width
      If imgWidth > maxWidth OR imgHeight > maxHeight then
        'Determine what dimension is off by more
        Dim deltaWidth as Integer = imgWidth - maxWidth
        Dim deltaHeight as Integer = imgHeight - maxHeight
        Dim scaleFactor as Double
        If deltaHeight > deltaWidth then
          'Scale by the height
          scaleFactor = maxHeight / imgHeight
          'Scale by the Width
          scaleFactor = maxWidth / imgWidth
        End If
        imgWidth *= scaleFactor
        imgHeight *= scaleFactor          
      End If
      html = "<a href=""" & IMAGE_DIRECTORY & Path.GetFileName(s) & """>" & _
             "<img src=""" & IMAGE_DIRECTORY & Path.GetFileName(s) & """" & _
                  "height=""" & imgHeight & """ width=""" & imgWidth & """>" & _


    dlPictures.DataSource = pics
  End Sub


  <asp:DataList runat="server" id="dlPictures"  RepeatColumns="3"
        Width="600" CellPadding="5" ItemStyle-HorizontalAlign="Center">
      <%# Container.DataItem %>

[Return to the Article]