Thumbnail Generation in Django 1.0

What do you do when you have a model with an ImageField, and would like to create an thumbnail when you save the original image?  It get’s pretty complicated and is nowhere near as easy as it should be.

The way we did it over at the TKS is by overriding the save method of our Photo model.  This new save method essentially takes the image, thumbnails it into our various sets of dimensions (for … in self.IMAGE_SIZES…), and save each one (into its own ImageField) before finally call the overwritten method to save the original image.

UPDATE:  Why this code is specific to Django 1.0 is because in previous versions there were convenience methods which would take care of getting the field names get_FIELD_field, or something to that nature.  Those have been eliminated in 1.0.

def save(self):
    from PIL import Image
    #Original photo
    imgFile = Image.open(self.image.path)

    #Convert to RGB
    if imgFile.mode not in ('L', 'RGB'):
        imgFile = imgFile.convert('RGB')

    #Save a thumbnail for each of the given dimensions
    for field_name, size in self.IMAGE_SIZES.iteritems():
        field = getattr(self, field_name)
        working = imgFile.copy()
        working.thumbnail(size, Image.ANTIALIAS)
        fp = StringIO()
        working.save(fp, "JPEG", quality=95)
        cf = ContentFile(fp.getvalue())
        field.save(name=self.image.name, content=cf, save=False);

    #Save instance of Photo
    super(Photo, self).save()
Advertisements

About this entry