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