Login

Download an image using requests, resize it using PIL, and save it to a model ImageField.

Author:
stewx
Posted:
March 24, 2015
Language:
Python
Version:
1.7
Tags:
image pil imagefield
Score:
2 (after 2 ratings)

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

Comments

Please login first before commenting.