The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Book End

--

Chapters
00:00 Question
00:55 Accepted answer (Score 167)
01:15 Answer 2 (Score 426)
01:33 Answer 3 (Score 172)
01:47 Answer 4 (Score 61)
02:02 Thank you

--

Full question
https://stackoverflow.com/questions/7391...

Accepted answer links:
https://github.com/python-pillow/Pillow/...
https://github.com/python-pillow/Pillow/...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pythonimaginglibrary

#avk47



ANSWER 1

Score 460


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



ACCEPTED ANSWER

Score 198


The following works for Python 3:

from PIL import Image
import requests

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

References:




ANSWER 3

Score 173


Using a StringIO

import urllib, cStringIO

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



ANSWER 4

Score 63


Using requests:

from PIL import Image
import requests
from StringIO import StringIO

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