Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

·
Free Resource
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 = '''

Directory Listing
'''
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):
    return

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

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
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") f.write(html); f.close()
Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}