Convert Figma logo to code with AI

nodeca logopica

Resize image in browser with high quality and high speed

3,760
245
3,760
10

Top Related Projects

29,063

High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, AVIF and TIFF images. Uses the libvips library.

13,975

An image processing library written entirely in JavaScript for Node, with zero external or native dependencies.

6,946

GraphicsMagick for node

Content aware image cropping

3,574

FileAPI — a set of javascript tools for working with files. Multiupload, drag'n'drop and chunked file upload. Images: crop, resize and auto orientation by EXIF.

Pure Javascript OCR for more than 100 Languages 📖🎉🖥

Quick Overview

Pica is a high-quality image resizing library for browsers. It utilizes WebAssembly and Web Workers for fast performance, and supports various resizing algorithms to maintain image quality during resizing operations.

Pros

  • High-performance image resizing using WebAssembly and Web Workers
  • Multiple resizing algorithms available for different quality needs
  • Works in browsers, making it suitable for client-side image processing
  • Supports both Canvas and Image inputs

Cons

  • Limited to browser environments, not suitable for server-side use
  • May have a larger file size compared to simpler resizing libraries
  • Requires additional setup for optimal performance (e.g., loading WebAssembly)
  • Limited to resizing operations, not a full-featured image manipulation library

Code Examples

Resizing an image with default options:

const resizedImage = await pica().resize(sourceImage, {
  width: 300,
  height: 200
});

Resizing with a specific algorithm:

const resizedImage = await pica({
  features: ['js', 'wasm', 'ww'],
  resize: [{ pica: { quality: 3 } }]
}).resize(sourceImage, {
  width: 300,
  height: 200
});

Converting a resized image to a Blob:

const resizedImage = await pica().resize(sourceImage, {
  width: 300,
  height: 200
});
const blob = await pica().toBlob(resizedImage, 'image/jpeg', 0.90);

Getting Started

  1. Install Pica using npm:

    npm install pica
    
  2. Import and use Pica in your project:

    import Pica from 'pica';
    
    const pica = new Pica();
    
    async function resizeImage(sourceImage, width, height) {
      const resizedImage = await pica.resize(sourceImage, {
        width: width,
        height: height
      });
      return resizedImage;
    }
    
  3. Make sure to handle the asynchronous nature of Pica's operations using async/await or Promises in your application.

Competitor Comparisons

29,063

High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, AVIF and TIFF images. Uses the libvips library.

Pros of Sharp

  • Faster performance for most image processing tasks
  • Wider range of supported image formats (including AVIF and HEIF)
  • More comprehensive API with advanced features like image compositing

Cons of Sharp

  • Larger package size due to libvips dependency
  • More complex installation process, especially on some systems
  • Steeper learning curve for beginners

Code Comparison

Sharp:

sharp(input)
  .resize(300, 200)
  .toFile('output.jpg', (err, info) => {
    // Handle result
  });

Pica:

pica().resize(input, output, {
  width: 300,
  height: 200
}).then(result => {
  // Handle result
});

Summary

Sharp offers superior performance and a more extensive feature set, making it ideal for complex image processing tasks. However, it comes with a larger footprint and potentially more challenging setup. Pica, while more limited in scope, provides a simpler API and easier integration, making it suitable for basic resizing needs and projects where a lightweight solution is preferred.

13,975

An image processing library written entirely in JavaScript for Node, with zero external or native dependencies.

Pros of Jimp

  • Pure JavaScript implementation, making it easier to use in various JavaScript environments
  • Supports a wide range of image manipulation operations (resize, crop, rotate, etc.)
  • Can be used in both Node.js and browser environments

Cons of Jimp

  • Generally slower performance compared to Pica, especially for large images
  • Limited support for advanced image processing features
  • May produce lower quality results for certain operations like resizing

Code Comparison

Resizing an image with Jimp:

Jimp.read('input.jpg')
  .then(image => {
    return image.resize(256, 256).write('output.jpg');
  })
  .catch(err => {
    console.error(err);
  });

Resizing an image with Pica:

const from = document.getElementById('from');
const to = document.getElementById('to');

pica().resize(from, to, {
  unsharpAmount: 80,
  unsharpRadius: 0.6,
  unsharpThreshold: 2
})
.then(result => console.log('Resize done!'));

Both libraries offer image resizing capabilities, but Pica focuses on high-quality resizing with better performance, while Jimp provides a broader range of image manipulation features in a pure JavaScript implementation.

6,946

GraphicsMagick for node

Pros of gm

  • Supports a wide range of image processing operations beyond resizing
  • Utilizes GraphicsMagick/ImageMagick, providing robust and tested image manipulation capabilities
  • Offers both synchronous and asynchronous API options

Cons of gm

  • Requires external dependencies (GraphicsMagick or ImageMagick) to be installed
  • May have slower performance for simple resizing operations compared to pica
  • Larger package size due to extensive feature set

Code Comparison

gm:

const gm = require('gm');

gm('input.jpg')
  .resize(200, 200)
  .write('output.jpg', function (err) {
    if (!err) console.log('Image resized');
  });

pica:

const Pica = require('pica');
const pica = new Pica();

pica.resize(inputCanvas, outputCanvas)
  .then(result => console.log('Image resized'));

Summary

gm is a comprehensive image processing library with a wide range of features, while pica focuses specifically on high-quality image resizing. gm requires external dependencies but offers more versatility, whereas pica is lightweight and optimized for browser use. The choice between them depends on the specific project requirements and the desired balance between feature set and performance.

Content aware image cropping

Pros of smartcrop.js

  • Focuses on intelligent content-aware image cropping
  • Suitable for generating thumbnails and previews that preserve important image elements
  • Lightweight and can be used in both browser and Node.js environments

Cons of smartcrop.js

  • Limited to cropping functionality, doesn't offer resizing or other image processing features
  • May not perform as well on complex images or those without clear focal points
  • Requires more processing power compared to simple center-crop methods

Code Comparison

smartcrop.js:

smartcrop.crop(image, { width: 100, height: 100 }).then(function(result) {
  console.log(result);
});

pica:

pica().resize(from, to, {
  unsharpAmount: 80,
  unsharpRadius: 0.6,
  unsharpThreshold: 2
}).then(result => console.log('resize done!'));

Key Differences

  • smartcrop.js is specialized for content-aware cropping, while pica focuses on high-quality image resizing
  • pica offers more advanced image processing options, including unsharp mask and various resizing algorithms
  • smartcrop.js is more suitable for generating thumbnails that preserve important image content, while pica is better for general-purpose image resizing and quality preservation

Both libraries serve different purposes in image processing workflows, with smartcrop.js excelling in intelligent cropping and pica in high-quality resizing.

3,574

FileAPI — a set of javascript tools for working with files. Multiupload, drag'n'drop and chunked file upload. Images: crop, resize and auto orientation by EXIF.

Pros of FileAPI

  • Broader file handling capabilities, including file uploads and AJAX requests
  • Built-in support for drag-and-drop functionality
  • More comprehensive API for file manipulation and processing

Cons of FileAPI

  • Less specialized for image resizing compared to Pica
  • May have a steeper learning curve due to its broader feature set
  • Potentially larger bundle size due to additional features

Code Comparison

FileAPI (file upload example):

FileAPI.upload({
    url: '/upload',
    files: { file: fileInput },
    progress: function (evt) {
        console.log(evt.loaded / evt.total * 100 + '%');
    }
});

Pica (image resizing example):

pica.resize(from, to, {
    unsharpAmount: 80,
    unsharpRadius: 0.6,
    unsharpThreshold: 2
})
.then(result => console.log('Resized successfully'));

Summary

FileAPI is a more comprehensive file handling library with broader capabilities, including file uploads and drag-and-drop support. Pica, on the other hand, specializes in high-quality image resizing with a focus on performance. While FileAPI offers more features, it may be overkill for projects that only require image resizing. Pica provides a simpler, more focused solution for image processing tasks but lacks the extensive file handling capabilities of FileAPI.

Pure Javascript OCR for more than 100 Languages 📖🎉🖥

Pros of Tesseract.js

  • Optical Character Recognition (OCR) capabilities
  • Supports multiple languages and scripts
  • Can be used in both browser and Node.js environments

Cons of Tesseract.js

  • Larger file size and slower performance
  • May require additional training data for optimal results
  • Limited image processing capabilities

Code Comparison

Tesseract.js (OCR example):

Tesseract.recognize(
  'https://example.com/image.jpg',
  'eng',
  { logger: m => console.log(m) }
).then(({ data: { text } }) => {
  console.log(text);
})

Pica (Image resizing example):

pica().resize(from, to)
  .then(result => console.log('Resized successfully'));

Key Differences

Tesseract.js focuses on OCR functionality, while Pica specializes in high-quality image resizing. Tesseract.js is more versatile in terms of text recognition across various languages, but Pica offers better performance for image processing tasks.

Pica is more lightweight and faster for image manipulation, whereas Tesseract.js provides advanced text extraction capabilities at the cost of larger file size and potentially slower processing times.

Choose Tesseract.js for projects requiring text extraction from images, and Pica for efficient image resizing and processing tasks.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

pica - high quality image resize in browser

CI NPM version

Resize images in browser without pixelation and reasonably fast. Autoselect the best of available technologies: webworkers, webassembly, createImageBitmap, pure JS.

demo

With pica you can:

  • Reduce upload size for large images, saving upload time.
  • Saves server resources on image processing.
  • Generate thumbnails in browser.
  • ...

Note. If you need File/Blob resize (from form's file input), consider use image-blob-reduce. It has additional machinery to process orientation, keep EXIF metadata and so on.

Migration from pica v6 to pica v7

Multiply unsharpAmount by 2, divide unsharpThreshold by 2, example:

  • pica@6: pica.resize(a, b, { unsharpAmount: 80, unsharpThreshold: 2 })
  • pica@7: pica.resize(a, b, { unsharpAmount: 160, unsharpThreshold: 1 })

Prior to use

Here is a short list of problems you can face:

  • Loading image:
    • Due to JS security restrictions, you can process images from the same domain or local files only. If you load images from remote domain use proper Access-Control-Allow-Origin header.
    • iOS has a memory limits for canvas elements, that may cause problems in some cases, more details.
    • If your source data is jpeg image, it can be rotated. Consider use image-blob-reduce.
  • Saving image:
    • Some ancient browsers do not support canvas.toBlob() method. Use pica.toBlob(), it includes required shim.
    • For jpeg source, it's a good idea to keep exif data. Consider use image-blob-reduce.
  • Quality
    • JS canvas does not support access to info about gamma correction. Bitmaps have 8 bits per channel. That causes some quality loss, because with gamma correction precision could be 12 bits per channel.
    • Precision loss will not be noticeable for ordinary images like kittens, selfies and so on. But we don't recommend this library for resizing professional quality images.

Install

npm install pica

Use

const pica = require('pica')();

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

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

API

new Pica(config)

Create resizer instance with given config (optional):

  • tile - tile width/height. Images are processed by regions, to restrict peak memory use. Default 1024.
  • features - list of features to use. Default is [ 'js', 'wasm', 'ww' ]. Can be [ 'js', 'wasm', 'cib', 'ww' ] or [ 'all' ]. Note, cib is buggy in Chrome and not supports default mks2013 filter.
  • idle - cache timeout, ms. Webworkers create is not fast. This option allow reuse webworkers effectively. Default 2000.
  • concurrency - max webworkers pool size. Default is autodetected CPU count, but not more than 4.
  • createCanvas - function which returns a new canvas, used internally by pica. Default returns a <canvas> element, but this function could return an OffscreenCanvas instead (to run pica in a Service Worker). Function signature: createCanvas(width: number, height: number): Canvas

Important! Latest browsers may support resize via createImageBitmap. This feature is supported (cib) but disabled by default and not recommended for use. So:

  • createImageBitmap() is used for non-blocking image decode (when available, without downscale).
  • It's resize feature is blocked by default pica config. Enable it only on your own risk. Result with enabled cib will depend on your browser. Result without cib will be predictable and good.

.resize(from, to, options) -> Promise

Resize image from one canvas (or image) to another. Sizes are taken from source and destination objects.

  • from - source, can be Canvas, Image or ImageBitmap.
  • to - destination canvas, its size is supposed to be non-zero.
  • options - quality (number) or object:
    • quality (deprecated, use .filter instead) - 0..3.
    • filter - filter name (Default - mks2013). See resize_filter_info.js for details. mks2013 does both resize and sharpening, it's optimal and not recommended to change.
    • unsharpAmount - >=0. Default = 0 (off). Usually value between 100 to 200 is good. Note, mks2013 filter already does optimal sharpening.
    • unsharpRadius - 0.5..2.0. By default it's not set. Radius of Gaussian blur. If it is less than 0.5, Unsharp Mask is off. Big values are clamped to 2.0.
    • unsharpThreshold - 0..255. Default = 0. Threshold for applying unsharp mask.
    • cancelToken - Promise instance. If defined, current operation will be terminated on rejection.

Result is Promise, resolved with to on success.

(!) If you need to process multiple images, do it sequentially to optimize CPU & memory use. Pica already knows how to use multiple cores (if browser allows).

.toBlob(canvas, mimeType [, quality]) -> Promise

Convenience method, similar to canvas.toBlob(), but with promise interface & polyfill for old browsers.

.resizeBuffer(options) -> Promise

Supplementary method, not recommended for direct use. Resize Uint8Array with raw RGBA bitmap (don't confuse with jpeg / png / ... binaries). It does not use tiles & webworkers. Left for special cases when you really need to process raw binary data (for example, if you decode jpeg files "manually").

  • options:
    • src - Uint8Array with source data.
    • width - src image width.
    • height - src image height.
    • toWidth - output width, >=0, in pixels.
    • toHeight - output height, >=0, in pixels.
    • quality (deprecated, use .filter instead) - 0..3.
    • filter - filter name (Default - mks2013). See resize_filter_info.js for details. mks2013 does both resize and sharpening, it's optimal and not recommended to change.
    • unsharpAmount - >=0. Default = 0 (off). Usually value between 100 to 200 is good. Note, mks2013 filter already does optimal sharpening.
    • unsharpRadius - 0.5..2.0. Radius of Gaussian blur. If it is less than 0.5, Unsharp Mask is off. Big values are clamped to 2.0.
    • unsharpThreshold - 0..255. Default = 0. Threshold for applying unsharp mask.
    • dest - Optional. Output buffer to write data, if you don't wish pica to create new one.

Result is Promise, resolved with resized rgba buffer.

What is "quality"

Pica has presets to adjust speed/quality ratio. Simply use quality option param:

  • 0 - Box filter, window 0.5px
  • 1 - Hamming filter, window 1.0px
  • 2 - Lanczos filter, window 2.0px
  • 3 - Lanczos filter, window 3.0px

In real world you will never need to change default (max) quality. All this variations were implemented to better understand resize math :)

Unsharp mask

After scale down image can look a bit blured. It's good idea to sharpen it a bit. Pica has built-in "unsharp mask" filter (off by default). Set unsharpAmount to positive number to activate the filter.

Filter's parameters are similar to ones from Photoshop. We recommend to start with unsharpAmount = 160, unsharpRadius = 0.6 and unsharpThreshold = 1. There is a correspondence between UnsharpMask parameters in popular graphics software.

Browser support

We didn't have time to test all possible combinations, but in general:

Note. Though you can run this package on node.js, browsers are the main target platform. On server side we recommend to use sharp.

References

You can find these links useful:

pica for enterprise

Available as part of the Tidelift Subscription.

The maintainers of pica and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. Learn more.

NPM DownloadsLast 30 Days