Login

Resize image on save

Author:
David
Posted:
April 7, 2008
Language:
Python
Version:
.96
Score:
1 (after 3 ratings)

This snippet is extracted from my Photo model. I use it to ensure that any uploaded image is constrained to a specified size (resized on save).

In my case, I don't need to maintain a "thumbnail" and "fullsize" version, so I just store the resized version to save space.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from PIL import Image

class Photo(models.Model):
    source = models.ImageField(upload_to='images')

    def save(self, size=(400, 300)):
        """
        Save Photo after ensuring it is not blank.  Resize as needed.
        """

        if not self.id and not self.source:
            return

        super(Photo, self).save()

        filename = self.get_source_filename()
        image = Image.open(filename)
    
        image.thumbnail(size, Image.ANTIALIAS)
        image.save(filename)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 8 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
  5. Help text hyperlinks by sa2812 1 year, 5 months ago

Comments

rennat (on September 30, 2008):

Thank you, this didn't work correctly on my Python/Django installation but it did get me started writing my own.

#

Please login first before commenting.