pica

repository·master·Indexed 26 days ago

https://github.com/nodeca/pica

A high-quality image resizing library for the browser (v10.0.2) that utilizes WebAssembly, WebWorkers, and createImageBitmap for fast, non-pixelated resizing. It supports various interpolation filters including box, hamming, lanczos2, lanczos3, and mks2013, as well as unsharp mask sharpening. Pica can resize images from Canvas, Image, or ImageBitmap sources to a destination canvas or RGBA buffer, and provides utilities to convert results to Blobs.

Tokens
3K
Snippets
7
Records
24
Agent score
87%

What's inside pica

  1. Migrate from pica v9 to v10

    master

    If you are upgrading from version 9, note the following breaking changes:

    • Browser Support: IE and other legacy browsers are no longer supported.
    • Instantiation: The default export is now a factory function. Use pica() or import the class import { Pica } from 'pica'; new Pica().
    • Canvas Creation: The createCanvas option is removed. To override canvas creation, expose a custom OffscreenCanvas on the global scope.
    • Quality Argument: The positional quality argument is removed. Use the filter option instead (e.g., { filter: 'lanczos3' }). The object form { quality: 3 } is deprecated.
    • Worker Sharing: Multiple Pica instances no longer share a worker pool implicitly. Create and reuse a single instance.
  2. Use split builds for smaller bundles

    master

    By default, pica inlines the webworker code. To reduce your main bundle size or comply with CSP, use the split build by importing pica_main.mjs and providing the workerURL in the config.

    import createPica from 'pica/dist/pica_main.mjs';
    
    const resizer = createPica({
      workerURL: new URL('pica/dist/pica_worker.js', import.meta.url)
    });
  3. Run pica in Node.js

    master

    Pica is primarily designed for browsers. To run it in Node.js, you must expose a canvas library (like @napi-rs/canvas) as the global OffscreenCanvas. Note that WebWorkers will not be used in this mode. For high-performance Node.js image processing, sharp is recommended instead.

    import { Canvas } from '@napi-rs/canvas'; // or any other canvas library
    import pica from 'pica';
    
    global.OffscreenCanvas = Canvas;
    
    const resizer = pica(); // WebWorkers will not be used
  4. Resize and convert an image to a Blob

    master

    You can chain .resize() with .toBlob() to create a resized image as a Blob. .toBlob() provides a promise-based interface and a polyfill for older browsers.

    // Resize & convert to blob
    resizer.resize(from, to)
      .then(result => resizer.toBlob(result, 'image/jpeg', 0.90))
      .then(blob => console.log('resized to canvas & created blob!'));
  5. Configure the Pica instance

    master

    When creating a new Pica instance, you can pass a configuration object to tune performance and features:

    • tile: Tile width/height for region-based processing (default: 1024).
    • features: List of features to use. Default is [ 'js', 'wasm', 'ww' ]. Options include [ 'js', 'wasm', 'cib', 'ww' ] or [ 'all' ]. Note: cib (createImageBitmap) is disabled by default as it is not recommended.
    • idle: Cache timeout in ms for reusing webworkers (default: 2000).
    • workerURL: URL for pica_worker.js when using split builds.
    • concurrency: Max webworkers pool size (default: autodetected CPU count, max 4).
  6. Initialize pica resizer

    master

    You can initialize pica using the default factory function (ESM/CommonJS) or by instantiating the Pica class (ESM).

    // ESM (default factory)
    import pica from 'pica';
    const resizer = pica();
    
    // ESM (class)
    import { Pica } from 'pica';
    const resizer = new Pica();
    
    // CommonJS
    const resizer = require('pica')();
  7. Configure resize filters and unsharp mask options

    master

    The .resize() method accepts an options object to control the quality and sharpening of the output:

    • filter: The filter name. Default is 'mks2013', which performs both resizing and optimal sharpening. Other options include 'box', 'hamming', 'lanczos2', and 'lanczos3'.
    • unsharpAmount: Value >= 0 to activate the unsharp mask (default: 0). Recommended values are between 100 and 200.
    • unsharpRadius: Value between 0.5 and 2.0 for the Gaussian blur radius (default: not set). Values < 0.5 disable the mask.
    • unsharpThreshold: Value between 0 and 255 for the threshold (default: 0).
    • cancelToken: A Promise instance that, if rejected, terminates the current operation.
  8. Resize an image from Canvas or Image to another Canvas

    master

    Use the .resize(from, to, options) method to resize an image. The from parameter can be a Canvas, Image, or ImageBitmap. The to parameter must be a destination canvas with a non-zero size.

    // Resize from Canvas/Image to another Canvas
    resizer.resize(from, to)
      .then(result => console.log('resize done!'));
  9. Configure resize options

    master

    When calling resize methods, you can pass a ResizeOptions object to fine-tune the output quality and sharpening.

    Available options:

    • quality (CibResizeQuality): The resizing quality level (values: 0 | 1 | 2 | 3).
    • filter (Filter): The interpolation filter to use.
    • unsharpAmount (number): The amount of unsharp mask sharpening.
    • unsharpRadius (number): The radius of the unsharp mask.
    • unsharpThreshold (number): The threshold for the unsharp mask.
    • cancelToken (Promise<unknown>): A promise that, when resolved/rejected, can be used to cancel the ongoing resize operation.
  10. Configure Pica instance options

    master

    When initializing a new Pica instance, you can provide a PicaOptions object to control performance and feature usage.

    Available options:

    • tile (number): The size of the tiles used for resizing.
    • concurrency (number): The number of concurrent workers/threads to use.
    • features (PicaFeaturesFlat): A list of preferred features to use (e.g., 'js', 'wasm', 'ww', 'cib', or 'all').
    • idle (number): Idle time threshold.
    • workerURL (string | URL): The path to the worker script.
  11. Check browser feature support with get_supported_features()

    master
    Use get_supported_features() to retrieve a Promise that resolves to a SupportedFeatures object. This object details the capabilities of the current browser environment, such as whether OffscreenCanvas is available, if the environment can run in a Web Worker, and whether specific browser bugs (like orientation issues in drawImage) are present. This is useful for determining the most efficient resizing path available.