You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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;
     ">&nbsp; Legend <br>
     &nbsp; aaa &nbsp;          <i class="fa fa-map-marker" style="color:blue"></i><br>
     &nbsp; bbb &nbsp;      <i class="fa fa-truck" style="color:pink"></i><br>
     &nbsp; ccc &nbsp;        <i class="fa fa-map-marker" style="color:green"></i><br>
     &nbsp; shapefile &nbsp;    <img src="data:image/png;base64,{}" width="10" height="10"> 

     </div>
     '''.format(img_base64)

方案2:使用相对路径放置图片

  1. 先将Folium地图保存为HTML文件(比如my_map.html),此时会自动生成对应的my_map_files文件夹。
  2. 将abc.png复制到my_map_files目录下。
  3. 修改图例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;
     ">&nbsp; Legend <br>
     &nbsp; aaa &nbsp;          <i class="fa fa-map-marker" style="color:blue"></i><br>
     &nbsp; bbb &nbsp;      <i class="fa fa-truck" style="color:pink"></i><br>
     &nbsp; ccc &nbsp;        <i class="fa fa-map-marker" style="color:green"></i><br>
     &nbsp; shapefile &nbsp;    <img src="my_map_files/abc.png" width="10" height="10"> 

     </div>
     '''

内容的提问来源于stack exchange,提问作者newGIS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 03:21:02