node-screenshots

repository·master·Indexed 18 days ago

https://github.com/nashaofu/node-screenshots

A native Node.js library for capturing screenshots of monitors and specific windows across Windows, macOS, and Linux. It provides the Monitor and Window classes for screen capture and an Image class for cropping and encoding images into PNG, JPEG, BMP, or raw RGBA formats. Based on XCap, the library supports both synchronous and asynchronous execution.

Tokens
2.7K
Snippets
6
Records
12
Agent score
64%

What's inside node-screenshots

  1. Capture screenshots from Windows

    master

    The Window class allows you to capture specific application windows. You can list all visible windows using Window.all() and then capture individual windows either synchronously or asynchronously.

    const fs = require('fs')
    const { Window } = require('node-screenshots')
    
    let windows = Window.all()
    
    windows.forEach((item) => {
      // Capture and save as BMP synchronously
      let image = item.captureImageSync()
      fs.writeFileSync(`${item.id()}-sync.bmp`, image.toBmpSync())
    
      // Capture, crop, and save as PNG asynchronously
      item.captureImage().then(async (data) => {
        let newImage = await data.crop(10, 10, 10, 10)
        fs.writeFileSync(`${item.id()}.png`, await newImage.toPng())
      })
    })
  2. Capture screenshots from Monitors

    master

    You can interact with physical monitors using the Monitor class. You can retrieve all available monitors or find a specific monitor based on screen coordinates. The library provides both synchronous (captureImageSync) and asynchronous (captureImage) methods to capture the monitor's content as an Image object.

    const fs = require('fs')
    const { Monitor } = require('node-screenshots')
    
    // Get monitor at specific coordinates
    let monitor = Monitor.fromPoint(100, 100)
    
    // Synchronous capture
    let image = monitor.captureImageSync()
    fs.writeFileSync(`${monitor.id()}-sync.png`, image.toPngSync())
    
    // Asynchronous capture
    monitor.captureImage().then((data) => {
      fs.writeFileSync(`${monitor.id()}.jpeg`, data.toJpegSync())
    })
    
    // List all monitors and their properties
    const monitors = Monitor.all()
    monitors.forEach((item) => {
      console.log(
        'Monitor:',
        item.id(),
        item.name(),
        [item.x(), item.y(), item.width(), item.height()],
        item.rotation(),
        item.scaleFactor(),
        item.frequency(),
        item.isPrimary(),
      )
    })
  3. Install Linux system requirements

    master

    On Linux, you must install libxcb, libxrandr, and dbus for the library to function. Use the command corresponding to your distribution:

    Debian / Ubuntu:

    apt-get install libxcb1 libxrandr2 libdbus-1-3

    Alpine:

    apk add libxcb libxrandr dbus
    apt-get install libxcb1 libxrandr2 libdbus-1-3
  4. Capture screenshots of Monitors

    master

    Use the Monitor class to interact with physical displays. You can retrieve all available monitors using Monitor.all() or find a specific monitor based on screen coordinates using Monitor.fromPoint(x, y).

    Once you have a Monitor instance, you can capture its content using either captureImageSync() for synchronous execution or captureImage() for an asynchronous Promise-based approach.

    const { Monitor } = require('node-screenshots');
    const fs = require('fs');
    
    // Get monitor at specific coordinates
    let monitor = Monitor.fromPoint(100, 100);
    
    if (monitor) {
      // Synchronous capture
      let image = monitor.captureImageSync();
      fs.writeFileSync(`${monitor.id()}-sync.png`, image.toPngSync());
    
      // Asynchronous capture
      monitor.captureImage().then((data) => {
        fs.writeFileSync(`${monitor.id()}.jpeg`, data.toJpegSync());
      });
    }
    
    // List all monitors and their properties
    const monitors = Monitor.all();
    monitors.forEach((item) => {
      console.log(
        'Monitor:',
        item.id(),
        item.name(),
        [item.x(), item.y(), item.width(), item.height()],
        item.rotation(),
        item.scaleFactor(),
        item.frequency(),
        item.isPrimary()
      );
    });
  5. Manipulate and convert Images

    master

    The Image object returned by capture methods supports cropping and multiple format conversions.

    Cropping:

    • cropSync(x, y, width, height): Synchronous crop.
    • crop(x, y, width, height): Asynchronous crop.

    Format Conversion: All conversion methods support both synchronous and asynchronous versions. Supported formats include:

    • PNG: toPngSync() / toPng()
    • JPEG: toJpegSync() / toJpeg()
    • BMP: toBmpSync() / toBmp()
    • Raw (RGBA): toRawSync() / toRaw()

    Note on copyOutputData: When using this library within Electron, you may need to pass a boolean to the conversion methods to prevent crashes. For standard Node.js usage, do not pass this argument or set it to false for better performance.

  6. Capture screenshots of Windows

    master

    Use the Window class to capture specific application windows. Use Window.all() to get an array of all visible windows. Each Window instance provides methods to capture its content via captureImageSync() or captureImage().

    const { Window } = require('node-screenshots');
    const fs = require('fs');
    
    let windows = Window.all();
    
    windows.forEach((item) => {
      // Capture and save as BMP synchronously
      let image = item.captureImageSync();
      fs.writeFileSync(`${item.id()}-sync.bmp`, image.toBmpSync());
    
      // Capture, crop, and save as PNG asynchronously
      item.captureImage().then(async (data) => {
        let newImage = await data.crop(10, 10, 10, 10);
        fs.writeFileSync(`${item.id()}.png`, await newImage.toPng());
      });
    });
  7. Configure native binding loading with environment variables

    master

    You can control how node-screenshots loads its native components using the following environment variables:

    • NAPI_RS_NATIVE_LIBRARY_PATH: Specify a custom path to the native library file to bypass automatic detection.
    • NAPI_RS_FORCE_WASI: Forces the use of WASI bindings. If set to 'error', the process will throw an error if WASI bindings cannot be found.
    • NAPI_RS_ENFORCE_VERSION_CHECK: If set to a non-zero value, the library will strictly enforce that the installed native binding package version matches the expected version (e.g., 0.2.6).
  8. Monitor API Reference

    master

    The Monitor class provides the following static and instance methods:

    Static Methods:

    • static all(): Array<Monitor>: Returns an array of all available monitors.
    • static fromPoint(x: number, y: number): Monitor | null: Returns the monitor located at the specified x, y coordinates.

    Instance Methods:

    • captureImageSync(): Image: Synchronously captures the monitor content.
    • captureImage(): Promise<Image>: Asynchronously captures the monitor content.
  9. Image API Reference

    master

    The Image class handles post-capture processing and encoding.

    Cropping Methods:

    • cropSync(x: number, y: number, width: number, height: number): Image
    • crop(x: number, y: number, width: number, height: number): Promise<Image>

    Encoding Methods (Sync/Async): All methods accept an optional copyOutputData?: boolean | undefined | null parameter.

    • toPngSync() / toPng(): Convert to PNG.
    • toJpegSync() / toJpeg(): Convert to JPEG.
    • toBmpSync() / toBmp(): Convert to BMP.
    • toRawSync() / toRaw(): Convert to raw (RGBA data).
  10. Window API Reference

    master

    The Window class provides the following static and instance methods:

    Static Methods:

    • static all(): Array<Window>: Returns an array of all available windows.

    Instance Methods:

    • captureImageSync(): Image: Synchronously captures the window content.
    • captureImage(): Promise<Image>: Asynchronously captures the window content.
  11. Use node-screenshots API

    master

    The node-screenshots package provides a native interface for capturing screenshots of monitors, windows, and images. The main entry point exports the following classes:

    • Monitor: Used for interacting with physical or virtual monitors.
    • Window: Used for interacting with specific application windows.
    • Image: Used for image-related operations.

    Note that the package relies on native bindings. If you encounter loading errors, it may be due to npm optional dependency issues; try deleting node_modules and package-lock.json and running npm i again.

    const { Monitor, Window, Image } = require('node-screenshots');
    
    // Example usage (actual method calls depend on the native binding implementation)
    // const monitor = new Monitor();
    // const window = new Window();
    // const image = new Image();