Mercurial > hg > montage
diff montage/formatters.py @ 8:93af41dcff3a
now creates thumbnails using cropresize package
author | k0s <k0scist@gmail.com> |
---|---|
date | Fri, 25 Dec 2009 18:27:45 -0500 |
parents | d60a5ffbf4f4 |
children | 73d18f0cf8bb |
line wrap: on
line diff
--- a/montage/formatters.py Fri Dec 25 17:24:22 2009 -0500 +++ b/montage/formatters.py Fri Dec 25 18:27:45 2009 -0500 @@ -1,20 +1,29 @@ +""" +formatter for decoupage +""" + import mimetypes +import os +import Image +from cropresize import crop_resize from decoupage.formatters import FormatterBase class Images(FormatterBase): """display images with thumbnails""" defaults = { 'size': 'x', - 'columns': None } + 'columns': None, + 'thumb_dir': 'thumbs', + 'thumb_prefix': 'thumb_'} def __init__(self, arg): FormatterBase.__init__(self, arg) # get image size for display width, height = [ i.strip() for i in self.size.split('x', 1) ] - self.width = width or None - self.height = height or None - + self.width = width and int(width) or None + self.height = height and int(height) or None + def __call__(self, request, data): # add width + height data @@ -39,6 +48,50 @@ # thumbnails if 'thumbnails' not in self.args: return - for f in data['files']: + thumb_dir = self.thumb_dir + if not os.path.isabs(thumb_dir): + thumb_dir = os.path.join(data['directory'], self.thumb_dir) + else: raise NotImplementedError - import pdb; pdb.set_trace() + if not os.path.exists(thumb_dir): + os.mkdir(thumb_dir) + for f in data['files']: + filepath = os.path.join(data['directory'], f['name']) + thumbnail = '%s%s' % (self.thumb_prefix, f['name']) + thumbnail_file = os.path.join(data['directory'], thumb_dir, thumbnail) + create_thumbnail = False + if os.path.exists(thumbnail_file): + + # ensure the size is smaller than the specified size + try: + thumb = Image.open(thumbnail_file) + except: + continue + if self.width and thumb.size[0] > self.width: + create_thumbnail = True + if self.height and thumb.size[1] > self.height: + create_thumbnail = True + + # ensure the original file has not been modified + if os.path.getatime(thumbnail_file) < os.path.getatime(filepath): + create_thumbnail = True + else: + # create a new thumbnail + create_thumbnail = True + + if create_thumbnail: # do thumbnail creation + image = Image.open(filepath) + + try: + thumbnail_image = crop_resize(image, (self.width, self.height)) + except: + continue + fd = file(thumbnail_file, 'w') + thumbnail_image.save(fd) + fd.close() + + # fix the path to point to the thumbnail + f['path'] = '%s/%s/%s' % (f['path'].rsplit('/', 1)[0], + self.thumb_dir, + thumbnail) +