Generate thumbnails on save

 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. ImageWithThumbsField by zenx 3 years, 5 months ago
  2. Image model with thumbnail by clawlor 1 year, 10 months ago
  3. Resize image on save by David 4 years, 1 month ago
  4. Dynamic thumbnail generator by semente 4 years, 3 months ago
  5. ThumbnailMixIn by johan 3 years, 1 month 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.

#

(Forgotten your password?)