如何从Python中的URL读取图像数据? [英] How do I read image data from a URL in Python?
问题描述
当我们处理本地文件时,我想做的事情很简单,但是当我尝试使用远程URL时,问题就来了.
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.
基本上,我正在尝试从从URL提取的文件中创建一个PIL图像对象.当然,我总是可以只获取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.
这就是我所拥有的:
Image.open(urlopen(url))
它抱怨说seek()
不可用,所以我尝试了这个:
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?
推荐答案
在Python3中,StringIO和cStringIO模块不见了.
In Python3 the StringIO and cStringIO modules are gone.
在Python3中,您应该使用:
In Python3 you should use:
from PIL import Image
import requests
from io import BytesIO
response = requests.get(url)
img = Image.open(BytesIO(response.content))
这篇关于如何从Python中的URL读取图像数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!