How do I open an image from the internet in PIL?

This pull-request adds support for stream-handling native to Pillow (the friendly PIL fork) and should be available from version 2.8.0. This allows the simpler opening remote files with urllib:

from PIL import Image
import urllib2
Image.open(urllib2.urlopen(url))

…or using requests:

from PIL import Image
import requests
Image.open(requests.get(url, stream=True).raw)

As mentioned by mjpieters on the PR requests does not automatically decode gzip responses, so if you’re downloading images that have been further compressed for whatever reason you must set decode_content=True on the response object before accessing .raw.

response = requests.get(url, stream=True)
response.raw.decode_content = True
image = Image.open(response.raw)

Get regular FAQs tips & tutorials direct to your Inbox.

Discussion

Related posts