Platinum Partner

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

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 = '''

Directory Listing
'''
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 += '\n'

    for image in image_list:
      thumbnail(image)
      image_num += 1
      return_value += '\n'

      else:
        return_value += '\n'

  return_value += "
' + image + '' if image_num % images_per_row: return_value += '
" return return_value
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}