You can use this as a model method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | from django.core.files.base import ContentFile
from PIL import Image
from StringIO import StringIO
import requests
def set_photo(self, url, filename):
image_request_result = requests.get(url)
image = Image.open(StringIO(image_request_result.content))
width, height = image.size
max_size = [200, 200]
if width > 200 or height > 200:
image.thumbnail(max_size)
image_io = StringIO()
image.save(image_io, format='JPEG')
self.photo.save(filename, ContentFile(image_io.getvalue()))
|
More like this
- Mask sensitive data from logger by agusmakmun 1 week, 4 days ago
- Template tag - list punctuation for a list of items by shapiromatron 1 year, 2 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 2 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 9 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 10 months ago
Comments
Please login first before commenting.