Login

Generate thumbnails on save

Author:
peterw
Posted:
November 7, 2008
Language:
Python
Version:
1.0
Tags:
thumbnail
Score:
1 (after 3 ratings)

This is an override 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.

Yes, the dimensions are hardcoded, and there is currently not a way to regenerate them in different sizes, but one shouldn't be that hard to come up with, because you just could just load each photo object to regenerate, then save it again (or something along those lines).

mattpdx helped a lot with figuring out this code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
    #The IMAGE_SIZES looks like:
    #IMAGE_SIZES = { 'image_web'      : (300, 348),
    #                'image_large'    : (600, 450),
    #                'image_thumb'    : (200, 200) }
    #each of which corresponds to an ImageField of the same name
    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()

More like this

  1. Image model with thumbnail by clawlor 5 years, 2 months ago
  2. ImageWithThumbsField by zenx 6 years, 8 months ago
  3. Resize image on save by David 7 years, 5 months ago
  4. ThumbnailMixIn by johan 6 years, 4 months ago
  5. Dynamic thumbnail generator by semente 7 years, 6 months ago

Comments

cootetom (on November 8, 2008):

Where is the ContentFile function located?

#

cootetom (on November 8, 2008):

Ok I found in in django.core.files.base

This snippet came in really handy for me, thanks very much.

#

Please login first before commenting.