我读过类似问题的答案here ,但它只说明包含图像文件扩展名的 URL(例如 /image/zuyvH.png ),并且此方法不适用于没有任何图像文件扩展名的 URL(例如 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()
关于python - 如何在Python中保存不包含任何图像文件扩展名(例如png)的URL中的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70532781/