如何为Folium地图截图提高DPI以获取高质量图像?
解决Folium高DPI截图问题
Folium自带的_to_png()方法默认使用固定窗口尺寸和标准DPI截图,要获得高质量截图,你可以通过自定义Selenium浏览器配置,调整窗口大小和设备像素比来实现,具体方案如下:
自定义高分辨率截图函数
直接封装一个替代_to_png()的函数,手动控制Selenium的浏览器参数:
import io import os import tempfile from PIL import Image from selenium import webdriver from selenium.webdriver.chrome.options import Options def high_res_screenshot(map_obj, width=3840, height=2160, scale=2): # 配置Chrome无头模式参数 chrome_options = Options() chrome_options.add_argument('--headless=new') chrome_options.add_argument('--disable-gpu') # 设置浏览器窗口尺寸 chrome_options.add_argument(f'--window-size={width},{height}') # 设置设备像素比,模拟高DPI屏幕 chrome_options.add_argument(f'--force-device-scale-factor={scale}') driver = webdriver.Chrome(options=chrome_options) # 将地图保存为临时HTML文件 with tempfile.NamedTemporaryFile(mode='w', suffix='.html', delete=False) as f: map_obj.save(f.name) temp_html = f.name try: driver.get(f'file://{os.path.abspath(temp_html)}') driver.implicitly_wait(10) # 等待地图加载完成 img_data = driver.get_screenshot_as_png() finally: driver.quit() os.unlink(temp_html) # 清理临时文件 return img_data
使用示例
替换你原来的_to_png()调用,用自定义函数获取截图:
# 假设map是你的Folium地图实例 img_data = high_res_screenshot(map, width=3840, height=2160, scale=2) img = Image.open(io.BytesIO(img_data)) # 可选:如果需要将高分辨率截图缩小到目标尺寸(保持清晰度) # img = img.resize((img.width//2, img.height//2), Image.Resampling.LANCZOS) # 保存时指定DPI元数据 img.save(f'image_pci_{fix_pci}.png', dpi=(300, 300))
参数说明
width/height: 浏览器窗口的基础尺寸,越大截图包含的地图范围越广scale: 设备像素比,设置为2即对应200% DPI,截图分辨率会是width*scale × height*scale,数值越高细节越清晰
注意:需要确保已安装selenium和对应版本的浏览器驱动(如ChromeDriver),且浏览器驱动与本地浏览器版本匹配。
内容的提问来源于stack exchange,提问作者Joshua Roy
相关产品推荐
相关产品推荐

