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

01.25.2006
| 7049 views |
  • 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" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head><title>Directory Listing</title></head>
<body>'''
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):
    return

  image = Image.open(path + "/" + filename)
  image.thumbnail((max_width, max_height), Image.ANTIALIAS)
  image.save(path + "/.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
      image_list.append(file)

  if image_count > 0:
    image_list.sort()
    num_rows = image_count / images_per_row

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

    for image in image_list:
      thumbnail(image)
      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'

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

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