Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

puppeteer: Get base64 encoded image without separate download

On a page that does not support downloading images or opening them in new tab, I can use the Chrome Developer (Tools->Network) to right click the image and do "copy image as URI".

Is it possible to do the same with puppeteer?

I tried to use few Node.js modules that are intended to convert an image to its base64 representation but they all seem to download the image and then return base64 representation.

like image 896
im-i0dum Avatar asked Aug 29 '19 12:08

im-i0dum


2 Answers

Yes, you can use response.buffer() to get the buffer of a resource. You can then turn the buffer into a base64-encoded string by using buffer.toString('base64').

Code Sample

The following example goes to the google.com website, waits for the first PNG resource and then prints its base64-encoded image.

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    const [response] = await Promise.all([
        page.waitForResponse(response => response.url().includes('.png')),
        page.goto('https://www.google.com/')
    ]);
    const buffer = await response.buffer();
    console.log('data:image/png;base64,' + buffer.toString('base64'));

    await browser.close();
})();

This code sample waits for a single resource. Alternatively, you could listen to the response event to download multiple images in the same way.

like image 89
Thomas Dondorf Avatar answered Sep 20 '22 09:09

Thomas Dondorf


another solution is:

const base64 = await page.screenshot({ encoding: "base64" })
like image 38
Italo José Avatar answered Sep 18 '22 09:09

Italo José