如何从Unsplash API返回的URL获取图像?

2024-04-29 01:14:01 发布

您现在位置:Python中文网/ 问答频道 /正文

import requests


def linkFetch():
    url = "https://api.unsplash.com/photos/random/?client_id=MyAccessKey"

    response = requests.get(url)
    data = response.json()["urls"]["raw"]
    return data


def imageFetch(data):
    print(data)

imageFetch(linkFetch())

在这里,我的代码运行并获取图像的url,但如何在小窗口中自动打开照片。linkFetch()函数实际获取图像链接,我希望imageFetch()实际打开照片。我不熟悉使用API,所以任何帮助都会很有用。我已经尝试使用另一个request.get(),但可能使用不正确。其他解决方案似乎希望在我只想打开的地方无限期地下载图像

注意:MyAccessKey将替换我的实际密钥


Tags: https图像importapiurldatagetresponse
1条回答
网友
1楼 · 发布于 2024-04-29 01:14:01

您必须首先通过发送请求获取图像数据,然后将其传递给pillow package以显示图像

from io import BytesIO

from PIL import Image
import requests

img_url = imageFetch(linkFetch())
response = requests.get(img_url)
img = Image.open(BytesIO(response.content))
img.show()

相关问题 更多 >