vgalin / html2image

A package acting as a wrapper around the headless mode of existing web browsers to generate images from URLs and from HTML+CSS strings or files.
MIT License
354 stars 43 forks source link

Screenshot without saving the image #153

Closed saguileran closed 3 months ago

saguileran commented 3 months ago

Hello.

Is it possible to make a screenshot without saving the image? I mean, get the image as base64

vgalin commented 3 months ago

Hello,

It is not possible as-is, as browsers launched in headless mode directly generate an image file.

However, if you feel like tinkering, you may try to use html2image with Chrome CDP like so:

from html2image import Html2Image

with Html2Image(browser='chrome-cdp') as hti:
    my_base64_data = hti.screenshot(url='https://python.org', save_as='python_org.png')

But you'll have to modify the screenshot method a tiny bit (locally, on your machine):

https://github.com/vgalin/html2image/blob/e8816ebbde3318e3a94efed16f2884f7e56cea70/html2image/browsers/chrome_cdp.py#L143-L153

Instead of writing the base64 data to a file, you can just add a return img_data instead.


Please note that Chrome CDP support is undocumented, on stand-by, and can sometimes break. If you're not familiar with the principle behind the Chrome DevTools Protocol, you can think of it as:

When using the with context manager like so:

with Html2Image(browser='chrome-cdp') as hti:
    ...

A CDP server is opened behind the scenes, so if you want to take multiple screenshots, it is better to stay in the with block to keep the server open and avoid the startup delay before every screenshot.