Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - how to read an image from a URL?

Tags:

python

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?

like image 956
connoraw Avatar asked Dec 01 '16 12:12

connoraw


People also ask

How do you access an image in Python?

We use cv2. imread() function to read an image. The image should be placed in the current working directory or else we need to provide the absoluate path.


2 Answers

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()
like image 92
furas Avatar answered Oct 09 '22 13:10

furas


To begin with, you may download the image to your current working directory first

from urllib.request import urlretrieve

url = 'http://www.w3schools.com/css/trolltunga.jpg'
urlretrieve(url, 'pic.jpg')

And then open/read it locally:

from PIL import Image
img = Image.open('pic.jpg')

# For example, check image size and format
print(img.size)
print(img.format)

img.show()
like image 25
mikeqfu Avatar answered Oct 09 '22 13:10

mikeqfu