Listing the Images in a Directory Demo with Image Resizing using GetThumbnailImage()

This demo shows how to display a list of images from a directory and use image resizing a la the GetThumbnailImage() method.



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
        Else
          'Scale by the Width
          scaleFactor = maxWidth / imgWidth
        End If
        
        imgWidth *= scaleFactor
        imgHeight *= scaleFactor          
      End If
    
      If imgHeight <> currentImage.Height Or imgWidth <> currentImage.Width then
        html = "<a href=""" & IMAGE_DIRECTORY & Path.GetFileName(s) & """>" & _
             "<img src=""ShowThumbnail.aspx?img=" & Path.GetFileName(s) & "&w=" & _
                  imgWidth & "&h=" & imgHeight & """ " & _
                  "height=""" & imgHeight & """ width=""" & imgWidth & """>" & _
             "</a>"
      Else
        html = "<a href=""" & IMAGE_DIRECTORY & Path.GetFileName(s) & """>" & _
             "<img src=""ShowThumbnail.aspx?img=" & Path.GetFileName(s) & """ " & _
                  "height=""" & imgHeight & """ width=""" & imgWidth & """>" & _
             "</a>"
      End If

      pics.Add(html)
    Next

    dlPictures.DataSource = pics
    dlPictures.DataBind()
  End Sub

</script>

<html>
<body>

  <h1>Listing the Images in a Directory Demo with Image Resizing using <code>GetThumbnailImage()</code></h1>
  This demo shows how to display a list of images from a directory and use image resizing a la
  the <code>GetThumbnailImage()</code> method.
  
  <p><hr><p>

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


[Return to the Article]