robot | | node window screenshot | Search

The screenshotMonitor function captures a screenshot of a specified monitor, resizes it, and returns it as a PNG buffer, using the screenshot-desktop and sharp modules to handle image processing and capture.

Run example

npm run import -- "node screenshots"

node screenshots


const screenshot = require('screenshot-desktop')
const sharp = require('sharp')
//const { Monitor } = require('node-screenshots')

async function screenshotMonitor(monitor) {

  if(!monitor) {
    monitor = 0
  }
  //console.log('Taking screenshot')
  //let monitors = Monitor.all()

  //let capturer = monitors[monitor]
  try {
    let displays = await screenshot.listDisplays()

    let image = await screenshot({ format: 'png', screen: displays[monitor].id })

    console.log(displays[monitor])
    //let rawData = await image.toRaw()

    //console.log('Converting screenshot')
    const imageObj = await sharp(image)
    const metadata = await imageObj.metadata()

    return await imageObj
      .resize(Math.round(metadata.width / 3), Math.round(metadata.height / 3))
      .png()
      .toBuffer()
  } catch (e) {
    console.error(e)
  }
}

module.exports = screenshotMonitor

What the code could have been:

// Import required modules and assign them to constant variables for better readability
const { screenshot, listDisplays } = require('screenshot-desktop');
const sharp = require('sharp');

/**
 * Captures a screenshot from a specified monitor and returns it in a resized format.
 * 
 * @param {number} monitor - The index of the monitor to capture the screenshot from (default: 0)
 * @returns {Buffer} - The resized screenshot image in PNG format
 */
async function screenshotMonitor(monitor = 0) {
  // TODO: Implement error handling for invalid monitor indices

  try {
    // List all available displays
    const displays = await listDisplays();

    // Check if the specified monitor index is valid
    if (monitor < 0 || monitor >= displays.length) {
      throw new Error(`Invalid monitor index: ${monitor}`);
    }

    // Capture the screenshot from the specified monitor
    const image = await screenshot({ format: 'png', screen: displays[monitor].id });

    // Get the metadata of the screenshot
    const imageObj = await sharp(image);
    const metadata = await imageObj.metadata();

    // Resize the screenshot to 1/3 of its original size
    return await imageObj
     .resize(Math.round(metadata.width / 3), Math.round(metadata.height / 3))
     .png()
     .toBuffer();
  } catch (error) {
    // Log any errors that occur during the screenshot process
    globalThis.console.error(error);
    return Promise.reject(error);
  }
}

module.exports = screenshotMonitor;

Code Breakdown

Dependencies

The code requires the following dependencies:

Function: screenshotMonitor

Parameters

Description

The screenshotMonitor function captures a screenshot of the specified monitor and returns the resized image as a buffer in PNG format.

Steps

  1. It checks if the monitor parameter is provided. If not, it sets it to 0.
  2. It lists all displays using screenshot.listDisplays() and selects the specified monitor.
  3. It captures the screenshot of the selected monitor using screenshot({ format: 'png', screen: displayId }).
  4. It extracts metadata from the captured image using sharp(image).metadata().
  5. It resizes the image to 1/3 of its original width and height using sharp(image).resize(width, height).
  6. It converts the resized image to a PNG buffer using sharp(image).png().toBuffer().

Error Handling

If an error occurs during the execution of the function, it logs the error to the console using console.error(e).

Export

The function is exported as a module using module.exports = screenshotMonitor.