如何在Python的Folium Web地图图例中插入PNG图标?
Folium图例本地图片不显示的解决方法
你遇到的问题是Web浏览器出于安全限制,无法直接加载本地绝对路径的图片。Folium生成的是网页,本地路径D:\GIS\sdr\abc.png对浏览器来说是不可访问的,所以图标无法正常显示。下面是两种可行的解决方案:
方案1:将图片转为Base64编码嵌入HTML
把图片内容编码成Base64字符串,直接嵌入到HTML的img标签中,无需依赖外部文件。代码示例:
import base64 # 读取本地图片并转换为Base64编码 with open(r"D:\GIS\sdr\abc.png", "rb") as img_file: img_base64 = base64.b64encode(img_file.read()).decode('utf-8') # 构造包含Base64图片的图例HTML legend_html = ''' <div style="position: fixed; bottom: 40px; left: 50px; width: 100px; height: 110px; border:2px solid grey; z-index:9999; font-size:14px; background-color: white; "> Legend <br> aaa <i class="fa fa-map-marker" style="color:blue"></i><br> bbb <i class="fa fa-truck" style="color:pink"></i><br> ccc <i class="fa fa-map-marker" style="color:green"></i><br> shapefile <img src="data:image/png;base64,{}" width="10" height="10"> </div> '''.format(img_base64)
方案2:使用相对路径放置图片
- 先将Folium地图保存为HTML文件(比如
my_map.html),此时会自动生成对应的my_map_files文件夹。 - 将
abc.png复制到my_map_files目录下。 - 修改图例HTML中的图片路径为相对路径:
legend_html = ''' <div style="position: fixed; bottom: 40px; left: 50px; width: 100px; height: 110px; border:2px solid grey; z-index:9999; font-size:14px; background-color: white; "> Legend <br> aaa <i class="fa fa-map-marker" style="color:blue"></i><br> bbb <i class="fa fa-truck" style="color:pink"></i><br> ccc <i class="fa fa-map-marker" style="color:green"></i><br> shapefile <img src="my_map_files/abc.png" width="10" height="10"> </div> '''
内容的提问来源于stack exchange,提问作者newGIS
相关产品推荐
相关产品推荐

