Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/65940863/how-can-i-open-and-edit-images-from-url-using-pil

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For those of you who use Pillow, from version 2.8.0 you can:

from PIL import Image
import urllib2

im = Image.open(urllib2.urlopen(url))

or if you use requests:

from PIL import Image
import requests

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

References:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...