from django.db import models class Photo(models.Model): """ A photo for my site """ title = models.CharField(maxlength=50) photo = models.ImageField(upload_to="photos/") thumbnail = models.ImageField(upload_to="thumbnails/", editable=False) def save(self): if not self.thumbnail: # We use PIL's Image object # Docs: http://www.pythonware.com/library/pil/handbook/image.htm from PIL import Image # Set our max thumbnail size in a tuple (max width, max height) THUMBNAIL_SIZE = (50, 50) # Save fake thumbnail as empty so we can get the filename from the # original filename, from Django's convenience method # get_FIELD_filename() self.save_thumbnail_file(self.get_photo_filename(), '') # Open original photo which we want to thumbnail using PIL's Image # object image = Image.open(self.get_photo_filename()) # Convert to RGB if necessary # Thanks to Limodou on DjangoSnippets.org # http://www.djangosnippets.org/snippets/20/ if image.mode not in ('L', 'RGB'): image = image.convert('RGB') # We use our PIL Image object to create the thumbnail, which already # has a thumbnail() convenience method that contrains proportions. # Additionally, we use Image.ANTIALIAS to make the image look better. # Without antialiasing the image pattern artifacts may result. image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS) # Save the thumbnail image.save(self.get_thumbnail_filename()) # Save this photo instance super(Photo, self).save() class Admin: pass def __str__(self): return self.title