Resize image on save

 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. Function to create resized versions of an image from a URL and saving it to a local path by obeattie 6 years, 2 months ago
  2. Yet Another Image Resizer by stephen_mcd 3 years, 2 months ago
  3. ImageWithThumbsField by zenx 4 years, 4 months ago
  4. Image model with thumbnail by clawlor 2 years, 10 months ago
  5. Image resize on demand by VidJa 4 years, 4 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.

#

(Forgotten your password?)