16

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.

Thomas Dondorf
  • 23,416
  • 6
  • 84
  • 105
im-i0dum
  • 474
  • 1
  • 5
  • 13
  • Can't you get the src of the HTML image element? – hardkoded Aug 29 '19 at 12:52
  • Yes, but I can't download it, can't redirect to http of that image. Page that host image reports error when trying to save or open in new tab, I tried to get URI in puppeteer but base64 I get is encoded error from page, not image. – im-i0dum Aug 29 '19 at 13:05

3 Answers3

29

another solution is:

const base64 = await page.screenshot({ encoding: "base64" })
Italo José
  • 1,558
  • 1
  • 17
  • 50
18

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.

Thomas Dondorf
  • 23,416
  • 6
  • 84
  • 105
1

Following worked for me

  let screenshot = await page.screenshot({ encoding: "base64" }).then(function(data){
            let base64Encode = `data:image/png;base64,${data}`;
            return base64Encode;
    });

you can use that in addcontext - it will add in mochareport

addContext(this, {
    title: 'screenshot ',
    value: global.backEndData.contactCountTotalImage,
  });
Mahesh Hegde
  • 1,131
  • 10
  • 12