<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: pil code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sat, 17 May 2008 02:17:31 GMT</pubDate>
    <description>DZone Snippets: pil code</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>[Multiplatform] Thumbnails of all (gif, jpeg, and png) images in a directory</title>
      <link>http://snippets.dzone.com/posts/show/1297</link>
      <description>Thanks Dorrin for your Thumbnailer!&lt;br /&gt;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.&lt;br /&gt;By the way, as I revealed there is no dependency of "from mod_python import apache", so I removed it.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&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;  thumbsdir = os.path.join(path, ".thumbnails")&lt;br /&gt;  thumbfile = os.path.join(thumbsdir, filename)&lt;br /&gt;  if os.path.exists(thumbfile):&lt;br /&gt;    return&lt;br /&gt;&lt;br /&gt;  if not os.path.exists(thumbsdir):&lt;br /&gt;    os.mkdir(thumbsdir);&lt;br /&gt;    &lt;br /&gt;  filepath = os.path.join(path, filename)&lt;br /&gt;  image = Image.open(filepath)&lt;br /&gt;  image.thumbnail((max_width, max_height), Image.ANTIALIAS)&lt;br /&gt;  image.save(thumbfile)&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;&lt;br /&gt;&lt;br /&gt;Here is small test script.&lt;br /&gt;It generates thumbnails with Dorrin's script, then grabs HTML output and writes it to index.html file, so you get nice index page.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;import thumbnail&lt;br /&gt;import os&lt;br /&gt;&lt;br /&gt;html = thumbnail.index(0)&lt;br /&gt;&lt;br /&gt;htmlfile = os.path.join(os.getcwd(), "index.html")&lt;br /&gt;f = open(htmlfile, "w")&lt;br /&gt;f.write(html);&lt;br /&gt;f.close()&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Wed, 25 Jan 2006 18:21:02 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/1297</guid>
      <author>mloskot (Mateusz &#197;?oskot)</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>
    <item>
      <title>convert a PIL image to a GTK pixbuf</title>
      <link>http://snippets.dzone.com/posts/show/655</link>
      <description>free adaptation of http://slugathon.python-hosting.com/changeset/205&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;import gtk&lt;br /&gt;import Image&lt;br /&gt;&lt;br /&gt;def image2pixbuf(im):  &lt;br /&gt;    file1 = StringIO.StringIO()  &lt;br /&gt;    im.save(file1, "ppm")  &lt;br /&gt;    contents = file1.getvalue()  &lt;br /&gt;    file1.close()  &lt;br /&gt;    loader = gtk.gdk.PixbufLoader("pnm")  &lt;br /&gt;    loader.write(contents, len(contents))  &lt;br /&gt;    pixbuf = loader.get_pixbuf()  &lt;br /&gt;    loader.close()  &lt;br /&gt;    return pixbuf  &lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 08 Sep 2005 01:59:05 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/655</guid>
      <author>manatlan (manatlan)</author>
    </item>
    <item>
      <title>convert a GTK pixbuf to a PIL image</title>
      <link>http://snippets.dzone.com/posts/show/641</link>
      <description>&lt;code&gt;&lt;br /&gt;import gtk&lt;br /&gt;import Image&lt;br /&gt;&lt;br /&gt;def pixbuf2Image(pb):&lt;br /&gt;   width,height = pb.get_width(),pb.get_height()&lt;br /&gt;   return Image.fromstring("RGB",(width,height),pb.get_pixels() )&lt;br /&gt;&lt;br /&gt;pb = gtk.gdk.pixbuf_new_from_file( "p20050424_160333.jpg" )&lt;br /&gt;im = pixbuf2Image(pb)&lt;br /&gt;im.save("welldone.jpg", "JPEG",quality=80)&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Wed, 07 Sep 2005 19:11:04 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/641</guid>
      <author>manatlan (manatlan)</author>
    </item>
    <item>
      <title>Create Image Thumbnails (Python)</title>
      <link>http://snippets.dzone.com/posts/show/502</link>
      <description>&lt;code&gt;&lt;br /&gt;# experiments with the Python Image Library (PIL)&lt;br /&gt;&lt;br /&gt;# free from:  http://www.pythonware.com/products/pil/index.htm&lt;br /&gt;&lt;br /&gt;# create 128x128 (max size) thumbnails of all JPEG images in the working folder&lt;br /&gt;&lt;br /&gt;# Python23 tested    vegaseat    25feb2005&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;import glob&lt;br /&gt;import Image&lt;br /&gt;&lt;br /&gt;# get all the jpg files from the current folder&lt;br /&gt;&lt;br /&gt;for infile in glob.glob("*.jpg"):&lt;br /&gt;  im = Image.open(infile)&lt;br /&gt;  # convert to thumbnail image&lt;br /&gt;&lt;br /&gt;  im.thumbnail((128, 128), Image.ANTIALIAS)&lt;br /&gt;  # don't save if thumbnail already exists&lt;br /&gt;&lt;br /&gt;  if infile[0:2] != "T_":&lt;br /&gt;    # prefix thumbnail file with T_&lt;br /&gt;&lt;br /&gt;    im.save("T_" + infile, "JPEG")&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Sun, 24 Jul 2005 11:42:24 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/502</guid>
      <author>mattisbusy (Matt Kaufman)</author>
    </item>
    <item>
      <title>Sparkline: from PIL to S60</title>
      <link>http://snippets.dzone.com/posts/show/413</link>
      <description>py_s60 1.1.3 has its drawing API very similar to PIL.&lt;br /&gt;Porting from PIL to S60 is very easy. Here's an example&lt;br /&gt;that I port a sparkline drawing function from &lt;br /&gt;Joe Gregorio's article at xml.com&lt;br /&gt;&lt;code&gt;&lt;br /&gt;# modified from  Joe Gregorio's article at&lt;br /&gt;# http://www.xml.com/pub/a/2005/06/22/sparklines.html&lt;br /&gt;&lt;br /&gt;from appuifw import *&lt;br /&gt;import e32&lt;br /&gt;&lt;br /&gt;lock = e32.Ao_lock()&lt;br /&gt;c = Canvas()&lt;br /&gt;app.body = c&lt;br /&gt;draw = c._draw&lt;br /&gt;&lt;br /&gt;red, green, blue, gray = 0xff0000, 0x00ff00, 0x0000ff, 0x777777&lt;br /&gt;&lt;br /&gt;def plot_sparkline(results, step=2, height=20, \&lt;br /&gt;    min_m=None, max_m=None, last_m=None, \&lt;br /&gt;    min_color=blue, max_color=green, last_color=red):&lt;br /&gt;    coords = zip(range(1,len(results)*step+1, step), \&lt;br /&gt;       [height - 3  - y/(101.0/(height-4)) for y in results])&lt;br /&gt;    draw.line(coords, gray)&lt;br /&gt;    if min_m:&lt;br /&gt;        min_pt = coords[results.index(min(results))]&lt;br /&gt;        draw.rectangle([min_pt[0]-1, min_pt[1]-1, min_pt[0]+1, min_pt[1]+1], fill=min_color)&lt;br /&gt;    if max_m:&lt;br /&gt;        max_pt = coords[results.index(max(results))]&lt;br /&gt;        draw.rectangle([max_pt[0]-1, max_pt[1]-1, max_pt[0]+1, max_pt[1]+1], fill=max_color)&lt;br /&gt;    if last_m:&lt;br /&gt;        end = coords[-1]&lt;br /&gt;        draw.rectangle([end[0]-1, end[1]-1, end[0]+1, end[1]+1], fill=last_color)&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;results = [88,84,82,92,82,86,66,82,44,64,66,88,96,80,24,26, \&lt;br /&gt;        14,0,0,26,8,6,6,24,52,66,36,6,10,14,30]&lt;br /&gt;plot_sparkline(results, 3, 30, min_m=1, max_m=1, last_m=1)&lt;br /&gt;&lt;br /&gt;app.exit_key_handler = lock.signal&lt;br /&gt;lock.wait()&lt;/code&gt;</description>
      <pubDate>Sun, 26 Jun 2005 13:50:12 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/413</guid>
      <author>korakot (Korakot Chaovavanich)</author>
    </item>
  </channel>
</rss>
