python裁剪图片并保存_Python打开html文件,截图,裁剪并保存为图像

1586010002-jmsa.png

I am using the Bokeh package to generate maps to show the results of a simulation. The output is individual maps in html format with interactivity. The interactivity is needed for individual maps.

See this link for an example:

The simulation can automatically be set to run a number of times and will produce a map for each run. This could be 100's of maps. I would like to be able to stitch together the maps to create a movie - the interactivity is not required for this. Bokeh has functionality to create PNG files via the browser so it is possible to manually save each map as a file and use ffmpeg to create a movie. However this is not really an option if you need to do it for 100's of files. Currently there is no way to automatically generate PNG files via Bokeh but I believe it will be added at some point.

So I need a workaround. My thought is to open each html file from the location they are stored on the local drive, take a screen shot, crop the image to keep the required section and save. But I have not yet found a solution that works.

Cropping an image is easy:

from PIL import Image

img = Image.open(file_name)

box = (1, 1, 1000, 1000)

area = img.crop(box)

area.save('saved_image', 'jpeg')

My problem is opening the html file and taking the screen shot in the first place to feed to the above code.

For this I have tried the following but both require a URL rather than an html file. Also both use Firefox which doesn't work for me but I have installed chrome and altered the code appropriately.

My code for this is:

from selenium import webdriver

driver = webdriver.Chrome()

driver.get('file_name')

driver.save_screenshot('image.png')

driver.quit()

Which returns:

{"code":-32603,"message":"Cannot navigate to invalid URL"}

Clearly a filename is not a url so that is clear. It works fine if you pass it a website. Any help in getting a html loaded and a picture taken would be greatly appreciated! It does not have to involve Selenium.

解决方案

As of Bokeh 0.12.6, it is now easier to take those screenshots directly from Python without needing to open a browser.

Exporting PNGs looks like this

export_png(plot, filename="plot.png")

And exporting SVGs looks like this

plot.output_backend = "svg"

export_svgs(plot, filename="plot.svg")

There are some optional dependencies that need to be installed.

You can find more information in the Exporting Plots section of the User Guide.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值