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

Question

Asked By – Daniel Quinn

What I’m trying to do is fairly simple when we’re dealing with a local file, but the problem comes when I try to do this with a remote URL.

Basically, I’m trying to create a PIL image object from a file pulled from a URL. Sure, I could always just fetch the URL and store it in a temp file, then open it into an image object, but that feels very inefficient.

Here’s what I have:

Image.open(urlopen(url))

It flakes out complaining that seek() isn’t available, so then I tried this:

Image.open(urlopen(url).read())

But that didn’t work either. Is there a Better Way to do this, or is writing to a temporary file the accepted way of doing this sort of thing?

Now we will see solution for issue: How do I read image data from a URL in Python?


Answer

The following works for Python 3:

from PIL import Image
import requests

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

References:

This question is answered By – Giovanni Cappellotto

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0