def __getattr__(self, name):
"""
Deploys dynamic methods for on-demand thumbnails creation with any
size.
Syntax::
get_photo_[WIDTH]x[HEIGHT]_[METHOD]
Where *WIDTH* and *HEIGHT* are the pixels of the new thumbnail and
*METHOD* can be ``url`` or ``filename``.
Example usage::
>>> photo = Photo(photo="/tmp/example.jpg", ...)
>>> photo.save()
>>> photo.get_photo_320x240_url()
u"http://media.example.net/photos/2008/02/26/example_320x240.jpg"
>>> photo.get_photo_320x240_filename()
u"/srv/media/photos/2008/02/26/example_320x240.jpg"
"""
match = re.match(GET_THUMB_PATTERN, name)
if match is None:
raise AttributeError, name
width, height, method = match.groups()
size = int(width), int(height)
def get_photo_thumbnail_filename():
file, ext = path.splitext(self.photo.file.name)
return file + '_%sx%s' % size + ext
def get_photo_thumbnail_url():
url, ext = path.splitext(self.photo.url)
return url + '_%sx%s' % size + ext
thumbnail = get_photo_thumbnail_filename()
if not path.exists(thumbnail):
img = Image.open(self.photo.file.name)
img.thumbnail(size, Image.ANTIALIAS)
img.save(thumbnail)
if method == "url":
return get_photo_thumbnail_url
else:
return get_photo_thumbnail_filename
Comments
Fixed a bug:
#
Nice, I can see this coming in very handy and it's a lot more straightforward than I expected it to be (a testament to the very powerful features and libraries of Python).
#
Is it possible to make it delete the generated images if the parent field is edited or deleted?
#
Andrew: check out sorl-thumbnail -- it's a drop-in django thumbnail app; it automatically updates cached thumbnails if they're older than their source images (among other things).
#
In order to automatically clean up old thumbs when a new picture is saved:
#
I did a little modification on this method, that allow to user to specify the field name.
def getattr(self, name): """ Deploys dynamic methods for on-demand thumbnails creation with any size.
#