簡體   English   中英

如何在Jupyter Notebook中顯示來自API響應的圖像?

[英]How to display image from API response in Jupyter Notebook?

我在Jupyter Notebook中有一個Azure Maps API調用,該調用返回.png格式的地圖圖塊。 該調用的效果很好,但我不知道如何將其顯示為圖像而不是二進制文本。

-API調用:

import requests
from ipywidgets import Image

url = "https://atlas.microsoft.com/map/static/png"

querystring = {
    "api-version":"1.0",
    "subscription-key":"<myRedactedAPIkey>",
    "layer":"basic",
    "zoom":"5",
    "center":"-122.3950336,47.566848",
    "height":"600",
    "width":"600",
    "pins":"default||-121.95066667 45.9135|-121.062 46.707",
    "format":"png",
    "path":"ra300||-122.3950336 47.566848"
}

payload = ""
headers = {
    'cache-control': "no-cache"
    }

response = requests.request("GET", url, data=payload, headers=headers, params=querystring)

print(response.text)

結果是:

�PNG

IHDRX�f��sRGB���gAMA���a    pHYs���o�d��IDATx^��wt,K~�  �2ÕYqGg4+�iGsVgGg5Z�ќ]IT�Rs9\J䈤4r$r%�a���nv������}��wͻ������{[�By�20U\�6��@T"
��
�A�E��ֵ���|�%۶��O�N�#���dX��F��Y�p����y�l3�T�8;�Y�p�O҉#�վ8���yf����+5.����@0���q���Jތ�k��(�5�О���u���gBl�=�E���@�J����m=f�k&h��^��Z��Ms��̊\�J���if��C��:2_ <etc.>

想:

在此處輸入圖片說明

有什么建議嗎? 謝謝。

EDIT2:這是有效的查詢。 感謝大家的幫助。

import requests
from IPython.display import Image, display

url = "https://atlas.microsoft.com/map/static/png"
payload = ""
querystring = {
        "api-version":"1.0",
        "subscription-key":"<myApiKeyRedacted>",
        "format":"png",
        "layer":"basic",
        "zoom":"5",
        "center":"-122.3950336,47.566848",
        "height":"600",
        "width":"600",
        "pins":"default||-121.95066667 45.9135|-121.062 46.707",
        "path":"ra300000||-122.3950336 47.566848"
    }
headers = {
    'cache-control': "no-cache"
    }

r = requests.get(url,data=payload, headers=headers, params=querystring, stream=all)

display(Image(r.content))

這就是最終的結果:出現了stream=allIpython.display.content的組合。

import requests
from IPython.display import Image, display

url = "https://atlas.microsoft.com/map/static/png"
payload = ""
querystring = {
        "api-version":"1.0",
        "subscription-key":"<myApiKeyRedacted>",
        "format":"png",
        "layer":"basic",
        "zoom":"5",
        "center":"-122.3950336,47.566848",
        "height":"600",
        "width":"600",
        "pins":"default||-121.95066667 45.9135|-121.062 46.707",
        "path":"ra300000||-122.3950336 47.566848"
    }
headers = {
    'cache-control': "no-cache"
    }

r = requests.get(url,data=payload, headers=headers, params=querystring, stream=all)

display(Image(r.content))

由於response.text似乎是有效的PNG圖像,並且您使用的是ipywidgets Image ,您是否嘗試使用它?

widgets.Image(
    value=response.text,
    format='png',
    width=300,
    height=400,
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM