How do I read image data from a URL in Python?

The following works for Python 3:

from PIL import Image
import requests

im = Image.open(requests.get(url, stream=True).raw)

References:

  • https://github.com/python-pillow/Pillow/pull/1151
  • https://github.com/python-pillow/Pillow/blob/master/CHANGES.rst#280-2015-04-01

In Python3 the StringIO and cStringIO modules are gone.

In Python3 you should use:

from PIL import Image
import requests
from io import BytesIO

response = requests.get(url)
img = Image.open(BytesIO(response.content))

Using requests:

from PIL import Image
import requests
from StringIO import StringIO

response = requests.get(url)
img = Image.open(StringIO(response.content))

Using a StringIO

import urllib, cStringIO

file = cStringIO.StringIO(urllib.urlopen(URL).read())
img = Image.open(file)