JamesTheAwesomeDude
JamesTheAwesomeDude

Reputation: 1053

Is this the right way to fetch an image from a URL in Python 3?

I need to retrieve a URL in Python and get it as a Pillow image.

from PIL import Image
from io import BytesIO
import urllib.request

url = input('Enter an image URL:\n> ')
r = urllib.request.urlopen(url)
imdata = r.read()
imdata_wrapper = BytesIO(imdata)
im = Image.open(imdata_wrapper)

im.show()

This seems like a rather roundabout way to do this (fetch the image, read out its data into a blob, convert said blob into a BytesIO object, then, finally, open such as an image).

Is there a better way?

Upvotes: 3

Views: 1757

Answers (1)

JamesTheAwesomeDude
JamesTheAwesomeDude

Reputation: 1053

Per comments -- Nope; that's what the docs even suggest!

If you have an entire image in a bytestring, wrap it in a BytesIO object, and use PIL.Image.open() to load it.


Though, as of Python 3.5, even that's unnecessary since HTTPResponses are already buffered (this applies to other URL libraries, too, such as requests and urllib3):

from PIL import Image
import urllib.request

url = input('Enter an image URL:\n> ')

r = urllib.request.urlopen(url)
im = Image.open(r)

im.show()

Upvotes: 2

Related Questions