Login

Resize image on save

Author:
David
Posted:
April 7, 2008
Language:
Python
Version:
.96
Tags:
image pil resize
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. Function to create resized versions of an image from a URL and saving it to a local path by obeattie 8 years, 1 month ago
  2. Async PIL resize of images by FarmKing 3 years, 1 month ago
  3. Image resize on demand by VidJa 6 years, 3 months ago
  4. Download an image using requests, resize it using PIL, and save it to a model ImageField. by stewx 1 week ago
  5. Image Standarization by garcia_marc 6 years, 11 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.