gpt4 book ai didi

Python - 如何从 URL 读取图像?

转载 作者:太空狗 更新时间:2023-10-30 00:26:02 33 4
gpt4 key购买 nike

我是 Python 的新手,我正在尝试弄清楚如何从 URL 读取图像。

这是我当前的代码:

from PIL import Image
import urllib.request, io

URL = 'http://www.w3schools.com/css/trolltunga.jpg'

with urllib.request.urlopen(URL) as url:
s = url.read()
Image.open(s)

我收到以下错误:

C:\python>python image.py
Traceback (most recent call last):
File "image.py", line 8, in <module>
Image.open(s)
File "C:\Anaconda3\lib\site-packages\PIL\Image.py", line 2272, in open
fp = builtins.open(filename, "rb")
ValueError: embedded null byte

我不知道这意味着什么。我做错了什么?

最佳答案

Image.open()期待 filenamefile-like object - 不是 file data .

您可以在本地写入图像 - 即 "temp.jpg" - 然后打开它

from PIL import Image
import urllib.request

URL = 'http://www.w3schools.com/css/trolltunga.jpg'

with urllib.request.urlopen(URL) as url:
with open('temp.jpg', 'wb') as f:
f.write(url.read())

img = Image.open('temp.jpg')

img.show()

或者您可以创建 file-like object在内存中使用 io模块

from PIL import Image
import urllib.request
import io

URL = 'http://www.w3schools.com/css/trolltunga.jpg'

with urllib.request.urlopen(URL) as url:
f = io.BytesIO(url.read())

img = Image.open(f)

img.show()

编辑:2022

因为 urlopen()还给出了 file-like object所以你甚至可以跳过io并直接使用url (没有 .read() )在 Image.open()

from PIL import Image
import urllib.request

URL = 'http://www.w3schools.com/css/trolltunga.jpg'

with urllib.request.urlopen(URL) as url:
img = Image.open(url)
img.show()

关于Python - 如何从 URL 读取图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40911170/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com