williamsca97 williamsca97 - 4 days ago 5
Python Question

Python - how to read an image from a URL?

I am completely new to Python and I'm trying to figure out how to read an image from a URL.

Here is my current code:

from PIL import Image
import urllib.request, io

URL = 'http://www.w3schools.com/css/trolltunga.jpg'

with urllib.request.urlopen(URL) as url:
s = url.read()
Image.open(s)


I get the following error:

C:\python>python image.py
Traceback (most recent call last):
File "image.py", line 8, in <module>
Image.open(s)
File "C:\Anaconda3\lib\site-packages\PIL\Image.py", line 2272, in open
fp = builtins.open(filename, "rb")
ValueError: embedded null byte


I have no idea what any of this means. What am I doing wrong?

Answer

Image.open() expects filename or file-like object - not file data.

You can write image locally - ie as "temp.jpg" - and then open it

from PIL import Image
import urllib.request

URL = 'http://www.w3schools.com/css/trolltunga.jpg'

with urllib.request.urlopen(URL) as url:
    with open('temp.jpg', 'wb') as f:
        f.write(url.read())

img = Image.open('temp.jpg')

img.show()

Or you can create file-like object in memory using io module

from PIL import Image
import urllib.request
import io

URL = 'http://www.w3schools.com/css/trolltunga.jpg'

with urllib.request.urlopen(URL) as url:
    f = io.BytesIO(url.read())

img = Image.open(f)

img.show()
Comments