Adding JPG Images to folium popup

2020-07-25 15:05发布

问题:

I try to add an image to folium popup, but failed. I use python 2.7 version, and folium 0.50 version.

Actually, I follow the page mention in other threads, but it still doesn't work

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")

回答1:

I've followed this example and it (almost) worked for me. Plots were not base64-decoded correctly because the encoded variable was a byte array instead of a string, thus producing a b'iVBOR header instead of a iVBOR header (the base64 version of the PNG header).

Replacing html(encoded) to html(encoded.decode('UTF-8')) fixed the problem.

Here is the output.


And this is the code snippet.

    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)