The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Beneath the City Looping

--

Chapters
00:00 How Do I Read Image Data From A Url In Python?
00:42 Answer 1 Score 452
00:53 Accepted Answer Score 195
01:14 Answer 3 Score 173
01:27 Answer 4 Score 62
01:41 Answer 5 Score 52
02:02 Thank you

--

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

--

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