我需要在 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
对象,然后,最后,打开图像等).
有没有更好的办法?
最佳答案
根据评论——不;这就是文档的建议!
If you have an entire image in a bytestring, wrap it in a
BytesIO
object, and usePIL.Image.open()
to load it.
不过,从 Python 3.5 开始,自 HTTPResponse
s are already buffered 以来,即使这样也没有必要了。 (这也适用于 other URL libraries ,例如 requests
和 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()
关于python-3.x - 这是在 Python 3 中从 URL 获取图像的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29064829/