【问题标题】:Is this the right way to fetch an image from a URL in Python 3?这是从 Python 3 中的 URL 获取图像的正确方法吗?
【发布时间】: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 对象,然后最后打开图像)。

有没有更好的办法?

【问题讨论】:

  • 您不能跳过readBytesIO 电话吗? urllib.request.urlopen 的返回值应该是 Image.open 想要的类文件对象。
  • @Blckknght 我怀疑是这样的,但我找不到怎么做。 urllib.request.urlopen() 返回一个“http.client.HTTPResponse 对象”,它似乎不能用于太多。
  • @JamesTheAwesomeDude:当您尝试将HTTPResponse 对象直接传递给Image.open 时出现什么错误?
  • @JamesTheAwesomeDude - Image.open 需要一个支持readseektell 的文件对象,后两者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


【解决方案1】:

每厘米——不;这就是文档甚至建议的内容!

如果您有一个字节串中的整个图像,请将其包装在 BytesIO 对象中,然后使用 PIL.Image.open() 加载它。


不过,从 Python 3.5 开始,即使是因为 HTTPResponses are already buffered(这也适用于 other URL libraries,例如 requestsurllib3),这也是不必要的:

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多