将JPG图片添加到folium弹出窗口

4
我尝试向folium弹出窗口添加图片,但失败了。我使用的是Python 2.7版本和Folium 0.50版本。
实际上,我遵循其他线程中提到的页面,但仍然无法正常工作。

http://nbviewer.jupyter.org/gist/ocefpaf/0ec5c93138744e5072847822818b4362

import folium

import base64

m = folium.Map(location = [33, -97], zoom_start = 6, tiles = "Mapbox Bright")

encoded = base64.b64encode(open('IMG_1769.JPG', 'rb').read()).decode()

html = '<img src="data:image/jpeg;base64,{}">'.format

iframe = folium.IFrame(html(encoded), width=632+20, height=420+20)

popup = folium.Popup(iframe, max_width=2650)

marker = folium.Marker([30,-100], popup=popup).add_to(m)

m.add_child(marker)

m.save("test.html")

欢迎来到SO!您能详细说明一下“它不起作用”吗?具体是哪里出了问题?您原本期望的结果是什么?实际发生了什么? - Azsgy
我按照你的步骤和答案操作,但我的地图甚至都没有显示出来。 - chaikov
你能否解释一下 html = '<img src="data:image/jpeg;base64,{}">'.format 的含义?末尾的 'format' 是做什么用的? - chaikov
2个回答

2
 import base64
 from folium import IFrame

 #Add Marker
 encoded = base64.b64encode(open('mypict.jpg', 'rb').read())
 html = '<img src="data:image/png;base64,{}">'.format
 iframe = IFrame(html(encoded.decode('UTF-8')), width=400, height=350)
 popup = folium.Popup(iframe, max_width=400)

 folium.Marker(location=[43.591545, 39.728056], tooltip=html, popup = popup, 
 icon=folium.Icon(color = 'gray')).add_to(map)

请不要仅仅发布代码作为答案,还要提供代码的解释以及它是如何解决问题的。带有解释的答案通常更有帮助和更高质量,并且更有可能吸引赞同。 - Ran Marciano

1

我按照这个例子操作,它(几乎)对我有用。图形没有正确地进行base64解码,因为encoded变量是一个字节数组而不是字符串,从而产生了一个b'iVBOR头而不是一个iVBOR头(PNG头的base64版本)。

html(encoded)替换为html(encoded.decode('UTF-8'))解决了问题。

这是输出结果。

Folium Heatmap with Graph


这是代码片段。

    fig, ax = plt.subplots(figsize=(width, height))
    ax = subdf.plot(x='date', y='temperature', ax=ax, legend=False)
    ax.set_ylabel('Temp (°C)')
    png = '/tmp/temperatures_{}.png'.format(counter)
    fig.savefig(png, dpi=resolution)

    encoded = base64.b64encode(open(png, 'rb').read())



    html = '<img src="data:image/png;base64,{}">'.format
    #print(20*'-',encoded.decode('UTF-8'))
    iframe = IFrame(html(encoded.decode('UTF-8')), width=(width*resolution)+20, height=(height*resolution)+20)
    popup = folium.Popup(iframe, max_width=2650)

    icon = folium.Icon(color="red", icon="ok")
    marker = folium.Marker([lat, lon], popup=popup, icon=icon)
    marker.add_to(marker_cluster)

你能解释一下 html = '<img src="data:image/png;base64,{}">'.format 为什么使用 data:image 而不是图片的文件名吗? - chaikov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接