DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Thumbnails Of All (gif, Jpeg, And Png) Images In A Directory

  • submit to reddit
        I've gone with just gif, jpeg, and png for now, but it should be easy enough to add any others that PIL supports - just update the regex.

This code generates a basic page with thumbnails of all images in the directory it is run from. It caches thumbnails in the .thumbnails directory. It requires mod_python and PIL to run, though mod_python can be removed trivially.

from mod_python import apache
import os
import re
from PIL import Image

header = '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "">
<head><title>Directory Listing</title></head>
images_per_row = 5
max_width,max_height = 150,150

path = os.path.dirname(__file__)
def thumbnail(filename):
  if os.path.exists(path + "/.thumbnails/" + filename):

  image = + "/" + filename)
  image.thumbnail((max_width, max_height), Image.ANTIALIAS) + "/.thumbnails/" + filename)

def index(req):
  return_value = header

  dir_list = os.listdir(path)
  image_list = []

  search = re.compile("(.*\.[Jj][Pp][Ee]?[Gg]$)|(.*\.[Pp][Nn][Gg]$)|(.*\.[Gg][Ii][Ff]$)")

  image_count = 0
  for file in dir_list:
    if search.match(file):
      image_count += 1

  if image_count > 0:
    num_rows = image_count / images_per_row

    image_num = 0
    return_value += '<table width="100%" border="0"><tr>\n'

    for image in image_list:
      image_num += 1
      return_value += '<td><a href="' + image + '"><img src=".thumbnails/' + image + '" alt="' + image + '"></a>'

      if image_num % images_per_row:
        return_value += '</td>\n'

        return_value += '</td></tr><tr>\n'

  return_value += "</table></body></html>"
  return return_value