【发布时间】:2015-03-15 18:58:17
【问题描述】:
我需要在 Python 中检索一个 URL 并将其作为 Pillow 图像获取。
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()
这似乎是一种相当迂回的方法(获取图像,将其数据读出到 blob 中,将所述 blob 转换为 BytesIO 对象,然后最后打开图像)。
有没有更好的办法?
【问题讨论】:
-
您不能跳过
read和BytesIO电话吗?urllib.request.urlopen的返回值应该是Image.open想要的类文件对象。 -
@Blckknght 我怀疑是这样的,但我找不到怎么做。
urllib.request.urlopen()返回一个“http.client.HTTPResponse对象”,它似乎不能用于太多。 -
@JamesTheAwesomeDude:当您尝试将
HTTPResponse对象直接传递给Image.open时出现什么错误? -
@JamesTheAwesomeDude -
Image.open需要一个支持read、seek和tell的文件对象,后两者http.client.HTTPResponse不支持,所以将其存储在BytesIO 接缝是正确的做法。 -
docs 状态:
If you have an entire image in a string, wrap it in a BytesIO object, and use open() to load it.所以您的解决方案似乎是预期的解决方案。 :)
标签: python-3.x python-imaging-library urllib