<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: Dorrin's Code Snippets</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Fri, 08 Aug 2008 20:16:04 GMT</pubDate>
    <description>DZone Snippets: Dorrin's Code Snippets</description>
    <item>
      <title>Latest and greatest directory thumbnailer</title>
      <link>http://snippets.dzone.com/posts/show/1655</link>
      <description>This does basically the same thing as my original code (http://www.bigbold.com/snippets/posts/show/1296), but significantly faster. Thumbnail sizes are cached between executions, and they could probably be kept around as static data in the mod_python environment if I could figure out how.&lt;br /&gt;&lt;br /&gt;Also note that the thumbnailing function no longer returns a complete page, but rather a single table (compatible with either HTML or XHTML). This allows the code to be embedded into something like a photo gallery.&lt;br /&gt;&lt;br /&gt;A simple function is shown at the end of this snippet, to set up thumbnailing with mod_python on apache. &lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;from os.path import join,exists&lt;br /&gt;from os import stat,mkdir,listdir&lt;br /&gt;import re&lt;br /&gt;from PIL import Image&lt;br /&gt;import cPickle&lt;br /&gt;&lt;br /&gt;images_per_row = 5&lt;br /&gt;max_width,max_height = 150,150&lt;br /&gt;&lt;br /&gt;search = re.compile("(.*\.jpe?g$)|(.*\.png$)|(.*\.gif$)", re.IGNORECASE)&lt;br /&gt;&lt;br /&gt;def list_directory(path):&lt;br /&gt;  thumbnail_size_cache = {}&lt;br /&gt;  thumbnail_size_cache_changed = False&lt;br /&gt;&lt;br /&gt;  return_value = []&lt;br /&gt;  dir_list = listdir(path)&lt;br /&gt;  images = [file for file in dir_list if search.match(file)]&lt;br /&gt;&lt;br /&gt;  if len(images) &lt; 1:&lt;br /&gt;    return ''&lt;br /&gt;&lt;br /&gt;  # Interesting directories&lt;br /&gt;  thumbsdir = join(path, ".thumbnails")&lt;br /&gt;&lt;br /&gt;  # Try to load the size cache from a file&lt;br /&gt;  cache_file_path = join(thumbsdir, "thumbnail_size_cache.dat")&lt;br /&gt;  if exists (cache_file_path):&lt;br /&gt;    cache_file = open(cache_file_path, "r")&lt;br /&gt;    thumbnail_size_cache = cPickle.load(cache_file)&lt;br /&gt;    cache_file.close()&lt;br /&gt;&lt;br /&gt;  images.sort()&lt;br /&gt;  return_value.append('&lt;table width="100%" border="0"&gt;&lt;tr&gt;\n')&lt;br /&gt;  row_template = '&lt;td&gt;&lt;a href="%(name)s"&gt;&lt;img src=".thumbnails/%(name)s" alt="%(name)s" width="%(width)d" height="%(height)d"/&gt;&lt;/a&gt;'&lt;br /&gt;&lt;br /&gt;  # If the thumbnail directory does not exist, create it&lt;br /&gt;  if not exists(thumbsdir):&lt;br /&gt;    mkdir(thumbsdir)&lt;br /&gt;&lt;br /&gt;  image_num = 0&lt;br /&gt;  for image in images:&lt;br /&gt;    image_num += 1&lt;br /&gt;&lt;br /&gt;    thumbfile = join(thumbsdir, image)&lt;br /&gt;    filepath = join(path, image)&lt;br /&gt;    width,height = 0,0&lt;br /&gt;&lt;br /&gt;    # Check if there is an already-existing thumbnail&lt;br /&gt;    create_new_thumbnail = True&lt;br /&gt;    if exists(thumbfile):&lt;br /&gt;      thumb_stat = stat(thumbfile)&lt;br /&gt;      img_stat = stat(filepath)&lt;br /&gt;&lt;br /&gt;      # Check if the thumbnail is newer than the image&lt;br /&gt;      if img_stat.st_mtime &lt; thumb_stat.st_mtime:&lt;br /&gt;        try:&lt;br /&gt;          width,height = thumbnail_size_cache[image]&lt;br /&gt;          create_new_thumbnail = False&lt;br /&gt;        except KeyError:&lt;br /&gt;          pass&lt;br /&gt;&lt;br /&gt;    if create_new_thumbnail:&lt;br /&gt;      # Thumbnail the image&lt;br /&gt;      thumbnail = Image.open(filepath)&lt;br /&gt;      thumbnail.thumbnail((max_width, max_height), Image.ANTIALIAS)&lt;br /&gt;      thumbnail.save(thumbfile)&lt;br /&gt;      thumbnail_size_cache[image] = thumbnail.size&lt;br /&gt;      thumbnail_size_cache_changed = True&lt;br /&gt;      width,height = thumbnail.size&lt;br /&gt;&lt;br /&gt;    return_value.append(row_template % {'name': image, 'width': width, 'height': height})&lt;br /&gt;&lt;br /&gt;    if image_num % images_per_row:&lt;br /&gt;      return_value.append('&lt;/td&gt;\n')&lt;br /&gt;&lt;br /&gt;    else:&lt;br /&gt;      return_value.append('&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;\n')&lt;br /&gt;&lt;br /&gt;  return_value.append("&lt;/tr&gt;&lt;/table&gt;")&lt;br /&gt;&lt;br /&gt;  # Save the cache&lt;br /&gt;  if thumbnail_size_cache_changed:&lt;br /&gt;    return_value.append("Saved cache")&lt;br /&gt;    cache_file = open(cache_file_path, "w")&lt;br /&gt;    cPickle.dump(thumbnail_size_cache, cache_file, cPickle.HIGHEST_PROTOCOL)&lt;br /&gt;    cache_file.close()&lt;br /&gt;&lt;br /&gt;  return ''.join(return_value)&lt;br /&gt;&lt;br /&gt;####################################&lt;br /&gt;### mod_python stuff starts here ###&lt;br /&gt;####################################&lt;br /&gt;&lt;br /&gt;from mod_python import apache&lt;br /&gt;&lt;br /&gt;html_header = '''&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;&lt;br /&gt;&lt;html&gt;&lt;br /&gt;&lt;head&gt;&lt;title&gt;Directory Listing&lt;/title&gt;&lt;/head&gt;&lt;br /&gt;&lt;body&gt;&lt;div&gt;'''&lt;br /&gt;&lt;br /&gt;xhtml_header = '''&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;br /&gt;&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml111/DTD/xhtml111.dtd"&gt;&lt;br /&gt;&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"&gt;&lt;br /&gt;&lt;head&gt;&lt;title&gt;Directory Listing&lt;/title&gt;&lt;/head&gt;&lt;br /&gt;&lt;body&gt;&lt;div&gt;'''&lt;br /&gt;&lt;br /&gt;def handler(req):&lt;br /&gt;  if not os.path.isdir(req.filename):&lt;br /&gt;    file = open(req.filename)&lt;br /&gt;    req.write(file.read())&lt;br /&gt;    return apache.OK&lt;br /&gt;&lt;br /&gt;  return_value = []&lt;br /&gt;  # Check for XHTML acceptance&lt;br /&gt;  accept_types = req.headers_in["Accept"].split(",")&lt;br /&gt;&lt;br /&gt;  # Don't do any measure of preference for now&lt;br /&gt;  if "application/xhtml+xml" in accept_types:&lt;br /&gt;    # Accepts XHTML&lt;br /&gt;    return_value.append(xhtml_header)&lt;br /&gt;    req.content_type="application/xhtml+xml"&lt;br /&gt;  else:&lt;br /&gt;    # Does not accept XHTML&lt;br /&gt;    return_value.append(html_header)&lt;br /&gt;    req.content_type="text/html"&lt;br /&gt;&lt;br /&gt;  return_value.append(list_directory(req.filename))&lt;br /&gt;  return_value.append("&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;")&lt;br /&gt;  req.write(''.join(return_value))&lt;br /&gt;  return apache.OK&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Wed, 08 Mar 2006 12:51:45 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/1655</guid>
      <author>Dorrin ()</author>
    </item>
    <item>
      <title>Thumbnails of all (gif, jpeg, and png) images in a directory</title>
      <link>http://snippets.dzone.com/posts/show/1296</link>
      <description>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.&lt;br /&gt;&lt;br /&gt;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.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;from mod_python import apache&lt;br /&gt;import os&lt;br /&gt;import re&lt;br /&gt;from PIL import Image&lt;br /&gt;&lt;br /&gt;header = '''&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;&lt;br /&gt;&lt;html&gt;&lt;br /&gt;&lt;head&gt;&lt;title&gt;Directory Listing&lt;/title&gt;&lt;/head&gt;&lt;br /&gt;&lt;body&gt;'''&lt;br /&gt;images_per_row = 5&lt;br /&gt;max_width,max_height = 150,150&lt;br /&gt;&lt;br /&gt;path = os.path.dirname(__file__)&lt;br /&gt;  &lt;br /&gt;def thumbnail(filename):&lt;br /&gt;  if os.path.exists(path + "/.thumbnails/" + filename):&lt;br /&gt;    return&lt;br /&gt;&lt;br /&gt;  image = Image.open(path + "/" + filename)&lt;br /&gt;  image.thumbnail((max_width, max_height), Image.ANTIALIAS)&lt;br /&gt;  image.save(path + "/.thumbnails/" + filename)&lt;br /&gt;&lt;br /&gt;def index(req):&lt;br /&gt;  return_value = header&lt;br /&gt;&lt;br /&gt;  dir_list = os.listdir(path)&lt;br /&gt;  image_list = []&lt;br /&gt;&lt;br /&gt;  search = re.compile("(.*\.[Jj][Pp][Ee]?[Gg]$)|(.*\.[Pp][Nn][Gg]$)|(.*\.[Gg][Ii][Ff]$)")&lt;br /&gt;&lt;br /&gt;  image_count = 0&lt;br /&gt;  for file in dir_list:&lt;br /&gt;    if search.match(file):&lt;br /&gt;      image_count += 1&lt;br /&gt;      image_list.append(file)&lt;br /&gt;&lt;br /&gt;  if image_count &gt; 0:&lt;br /&gt;    image_list.sort()&lt;br /&gt;    num_rows = image_count / images_per_row&lt;br /&gt;&lt;br /&gt;    image_num = 0&lt;br /&gt;    return_value += '&lt;table width="100%" border="0"&gt;&lt;tr&gt;\n'&lt;br /&gt;&lt;br /&gt;    for image in image_list:&lt;br /&gt;      thumbnail(image)&lt;br /&gt;      image_num += 1&lt;br /&gt;      return_value += '&lt;td&gt;&lt;a href="' + image + '"&gt;&lt;img src=".thumbnails/' + image + '" alt="' + image + '"&gt;&lt;/a&gt;'&lt;br /&gt;&lt;br /&gt;      if image_num % images_per_row:&lt;br /&gt;        return_value += '&lt;/td&gt;\n'&lt;br /&gt;&lt;br /&gt;      else:&lt;br /&gt;        return_value += '&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;\n'&lt;br /&gt;&lt;br /&gt;  return_value += "&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;"&lt;br /&gt;  return return_value&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Wed, 25 Jan 2006 11:27:57 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/1296</guid>
      <author>Dorrin ()</author>
    </item>
  </channel>
</rss>
