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
- Template tag - list punctuation for a list of items by shapiromatron 9 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 4 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
Please login first before commenting.