Login

Generate thumbnails on save

Author:
peterw
Posted:
November 7, 2008
Language:
Python
Version:
1.0
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. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks 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.