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. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 3 months ago
  2. Python Django CRUD Example Tutorial by tuts_station 3 months, 2 weeks ago
  3. Browser-native date input field by kytta 5 months ago
  4. Generate and render HTML Table by LLyaudet 5 months, 1 week ago
  5. My firs Snippets by GutemaG 5 months, 1 week 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.