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

Mateusz has posted 2 posts at DZone. View Full User Profile

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

  • submit to reddit
        Thanks Dorrin for your Thumbnailer!
I hope you don't mind, but I did some minor fixes and made your script more portable. Now, you can use it on Windows too.
By the way, as I revealed there is no dependency of "from mod_python import apache", so I removed it.

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):
  thumbsdir = os.path.join(path, ".thumbnails")
  thumbfile = os.path.join(thumbsdir, filename)
  if os.path.exists(thumbfile):

  if not os.path.exists(thumbsdir):
  filepath = os.path.join(path, filename)
  image =
  image.thumbnail((max_width, max_height), Image.ANTIALIAS)

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

Here is small test script.
It generates thumbnails with Dorrin's script, then grabs HTML output and writes it to index.html file, so you get nice index page.

import thumbnail
import os

html = thumbnail.index(0)

htmlfile = os.path.join(os.getcwd(), "index.html")
f = open(htmlfile, "w")


Mateusz Loskot replied on Mon, 2006/01/02 - 10:22am

Yup, it is helpful. I want to learn PIL but now I'm encouraged by your code to take a closer look at it. I'm still learning too.

Snippets Manager replied on Wed, 2006/01/25 - 5:18am

Thanks for fixing it - I (obviously) wasn't paying much attention to cross-platform issues at the time, and I don't know much about python. That's why the mod_python bit existed - I forgot that the req wasn't needed. Glad my code was helpful!