This is an override the save method of our Photo model. This new save method essentially takes the image, thumbnails it into our various sets of dimensions (for … in self.IMAGE_SIZES…), and save each one (into its own ImageField) before finally call the overwritten method to save the original image.
Yes, the dimensions are hardcoded, and there is currently not a way to regenerate them in different sizes, but one shouldn't be that hard to come up with, because you just could just load each photo object to regenerate, then save it again (or something along those lines).
mattpdx helped a lot with figuring out this code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | def save(self):
from PIL import Image
#Original photo
imgFile = Image.open(self.image.path)
#Convert to RGB
if imgFile.mode not in ('L', 'RGB'):
imgFile = imgFile.convert('RGB')
#Save a thumbnail for each of the given dimensions
#The IMAGE_SIZES looks like:
#IMAGE_SIZES = { 'image_web' : (300, 348),
# 'image_large' : (600, 450),
# 'image_thumb' : (200, 200) }
#each of which corresponds to an ImageField of the same name
for field_name, size in self.IMAGE_SIZES.iteritems():
field = getattr(self, field_name)
working = imgFile.copy()
working.thumbnail(size, Image.ANTIALIAS)
fp = StringIO()
working.save(fp, "JPEG", quality=95)
cf = ContentFile(fp.getvalue())
field.save(name=self.image.name, content=cf, save=False);
#Save instance of Photo
super(Photo, self).save()
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Where is the ContentFile function located?
#
Ok I found in in django.core.files.base
This snippet came in really handy for me, thanks very much.
#
Please login first before commenting.