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
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

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.