jwass / mplleaflet

Easily convert matplotlib plots from Python into interactive Leaflet web maps.
BSD 3-Clause "New" or "Revised" License
521 stars 76 forks source link

Support save fig as image #37

Closed philippschw closed 8 years ago

philippschw commented 8 years ago

Do you have any suggestion how easily an image could be extracted of the html, that the user can save as png or alike?

jwass commented 8 years ago

Hi @philippschw, I don't think there's a way to grab a screenshot of the browser programatically like that.

Sorry!

juanmed commented 5 years ago

I needed to do this and this is how I achieved some functionality. Basically it is to automate the process taking an screenshot after the map has been created. In the _display.py file add the pyscreenshot and time libraries and import them (of course you need to install them first):

import pyscreenshot as ImageGrab import time

Then in the same file modify function "show" by adding the parameter "im_name" that will contain the name under which you want to save the image, including file format:

` def show(fig=None, path='_map.html', im_name=None, **kwargs): """ Convert a Matplotlib Figure to a Leaflet map. Open in a browser

Parameters
----------
fig : figure, default gcf()
    Figure used to convert to map
path : string, default '_map.html'
    Filename where output html will be saved

See fig_to_html() for description of keyword args.

"""
import webbrowser
fullpath = os.path.abspath(path)
with open(fullpath, 'w') as f:
    save_html(fig, fileobj=f, **kwargs)
webbrowser.open('file://' + fullpath)
# save an screenshot
if (im_name):
    # wait for some seconds until map is ready
    time.sleep(2)
    im = ImageGrab.grab(bbox=(80, 100, 1905, 1070)) # X1,Y1,X2,Y2
    #im.show()
    im.save(im_name)
    print("Screenshot saved at: "+ im_name)
    im.show()

`

The image wil be saved. Be careful of not modifyin the screen while the screenshot is not taken. You can modify the bounding box of where the image is taken as well. That depends on your situation.