Automatically resizing images with Django
Maybe, like me, you'd like to resize images automatically when they are uploaded and saved to you Django site.
If so, here's how I did it (Django Snippet here__)::
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)
This Photo model is a thin wrapper around an ImageField. When a user uploads a new image and it is saved to the database, the overloaded save method first checks that the image source is not blank, then, after letting the super.save() method do it's thing, resizes the image using the optional 'size' parameter.
While there's room for optimisation here, it gets the job done. Depending on your requirements, an improvement might be to only resize the image if it's bigger then 'size'.
Another improvement could be to save multiple versions of the image for use as needed, but in my case, I opted to save the storage space.
Several other approaches to this problem can be seen here and here where multiple copies of the image are kept on the storage system.
__ http://www.djangosnippets.org/snippets/688/ http://www.djangosnippets.org/snippets/20/ http://www.eflorenzano.com/blog/tag/gallery/

TreddyTralley ybog