Python ipyleaflet如何将地图导出为PNG、JPG或SVG格式?

10

我尝试使用ipyleaflet导出数据可视化为PNG或其他文件格式,但是找不到有效的方法。例如,在folium中有map.save(path)。在我的研究中,是否有ipyleaflet库或方法被我忽略了,可以帮助我达成目标?

这里是生成地图的示例代码

from ipyleaflet import *
center = [34.6252978589571, -77.34580993652344]
zoom = 10
m = Map(default_tiles=TileLayer(opacity=1.0), center=center, zoom=zoom)
m

我想以图像文件的形式导出此地图,而不需要手动截屏。

我发现两个可以导出 Javascript Leaflet 地图的资源: https://github.com/aratcliffe/Leaflet.printhttps://github.com/mapbox/leaflet-image

不幸的是,我无法在 Python 中使用它们。

3个回答

10

我和我的同事找到了一个相当不错的解决方案,用于将 ipyleaflet(Python)中的图像导出。以下是它的工作原理。要进行导出,需要使用 folium 库。在这个例子中,GeoJson 数据已经准备好了样式属性:

import folium
map = folium.Map([51., 12.], zoom_start=6,control_scale=True)
folium.GeoJson(data).add_to(map)
map.save('map.html')

这是结果的样子:output

可以使用Python(Windows)中的子进程调用对html文件进行进一步处理,以生成PDF或PNG。希望这能够帮到你,因为ipyleaflet文档在Python中几乎不存在。


只是好奇,那个 data 是什么?谢谢 - denis

5
生成html的方法是使用ipywidgets
from ipywidgets.embed import embed_minimal_html
embed_minimal_html('map.html', views=[m])

如果你想制作PNG,可以使用ipywebrtc,具体来说:

或者在代码中:

from ipywebrtc import WidgetStream, ImageRecorder
widget_stream = WidgetStream(widget=m, max_fps=1)
image_recorder = ImageRecorder(stream=widget_stream)
display(image_recorder)

保存PNG:
with open('map.png', 'wb') as f:
    f.write(image_recorder.image.value)

或将其转换为Pillow图像进行预处理:

import PIL.Image
import io
im = PIL.Image.open(io.BytesIO(image_recorder.image.value))

2
我尝试使用它,但得到了一个空的map.png文件。 - Stefan

0

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