【问题标题】:How to convert html map into image (png or jpg )如何将 html 地图转换为图像(png 或 jpg )
【发布时间】:2020-12-06 10:06:46
【问题描述】:

我正在尝试将包含标记的地图和热图保存到图像中。 这是显示地图的代码。

from ipywidgets import Layout
import geopandas

defaultLayout=Layout(width='3000px', height='3000px') # A very large image.

lat_lgn = [39.74248, 254.993622]

m_f = Map(center=lat_lgn, zoom=12, layout=defaultLayout)

marker_m = Marker(location=lat_lgn, draggable=False)
m_f.add_layer(marker_m)

m_f

在上面添加一些标记

arr_test1 = [39.74258, 254.993682]
arr_test2 = [39.76288, 254.988932]
arr_test3 = [39.79998, 254.991982]

all_loc = [arr_test1, arr_test2, arr_test3]

for cur_loc in all_loc:
    point = CircleMarker(
        radius=10,
        location=cur_loc,
        color='red',
        fill_color="black",
    )
    m_f.add_layer(point)
    
    time.sleep(0.001)

将地图保存为 html 文件。工作正常。

m_f.save('f_map.html', title='My Map')

当我尝试从 html 获取图像或 pdf 时,会出现问题。

import imgkit
import pdfkit

config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf')
pdfkit.from_file('f_map.html', 'outpdf.pdf', configuration=config)
pdfkit.from_file('f_map.html', 'outjpg.jpg', configuration=config)
pdfkit.from_file('f_map.html', 'outpng.png', configuration=config)

pdf文件为空白

而且 MacBook 无法打开 jpeg 和 png 文件。

为了检查我的依赖关系,我试过这个:

import pdfkit
pdfkit.from_url('http://stackoverflow.com', 'out.pdf', configuration=config)

效果很好。但是,一旦我将out.pdf 更改为out.png,我就无法打开获得的文件。
有没有人有想法,我该如何解决这个问题?
我试图获得巨大的形象。但它也不适用于 300 像素 X 300 像素的图像。
欢迎任何提示。

【问题讨论】:

    标签: python html wkhtmltopdf pdfkit imgkit


    【解决方案1】:

    一个选项(诚然有点粗略)是使用 selenium 库自动打开 HTML,然后从那里截取屏幕截图,然后将其保存为图像。 代码会是这样的(我这里根据MS Edge给出了代码,但是其他浏览器的代码应该类似):

    from selenium import webdriver
    from time import sleep
    filename = '<Name (without path) of your HTML file here>'
    MyBrowser = webdriver.Edge(r"<path to webdriver here>\\msedge.exe")
    murl = r'file:\\{path}\{mapfile}'.format(path='<path to HTML here>',mapfile=mfilename)
    MyBrowser.get(murl)
    sleep(10) #this is not strictly necessary but is here in case you need time for map tiles to load
    MyBrowser.save_screenshot('<Image_file_name>')
    MyBrowser.quit()
    

    请注意,这需要您提前为您的浏览器安装网络驱动程序。

    【讨论】:

    • 感谢@AJ2599 的建议。我在 MacBook 上试过了,得到错误 SessionNotCreatedException: Message: session not created: No matching capabilities found
    猜你喜欢
    • 2012-06-01
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多