我读过类似问题的答案here https://stackoverflow.com/questions/30229231/python-save-image-from-url,但它只说明包含图像文件扩展名的 URL(例如https://i.stack.imgur.com/zuyvH.png https://i.stack.imgur.com/zuyvH.png)并且此方法不适用于没有任何图像文件扩展名的 URL(例如https://picsum.photos/id/128/100/100 https://picsum.photos/id/128/100/100).
当 URL 不包含扩展名时,我使用下面的代码保存并显示图像。但这没有用。
import requests
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
response = requests.get("https://picsum.photos/id/128/100/100")
file = open("sample_image.png", "wb")
file.write(response.content)
file.close()
img = mpimg.imread('sample_image.png')
imgplot = plt.imshow(img)
plt.show()
现在,我如何在 Python 中加载和保存该图像?
收到回复后,您可以执行以下操作:
_, extension = response.headers["content-type"].split("/")
fname = f"sample_image.{extension}"
file = open(fname, "wb")
file.write(response.content)
file.close()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)