Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

pica

nodeca221.7kMIT9.0.1TypeScript support: definitely-typed

High quality image resize in browser.

resize, scale, image, lanczos, canvas

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.

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

9.0.1 - 2021-12-14

Fixed

  • Fixed feature test in ServiceWorker, #255.

9.0.0 - 2021-12-10

Fixed

  • Fixed resize of images with transparency. Thanks to @chebum.

Changed

  • Dropped .alpha option.
  • Increased 2x data precision between convolver passes.

8.0.0 - 2021-11-22

Changed

  • Replaced .quality with .filter.
  • Added mks2013 filter and use it by default.

7.1.1 - 2021-11-22

Fixed

  • Force webworker always return typed array, to avoid artifacts in Chrome, #223.

7.1.0 - 2021-06-21

Changed

  • In FireFox experimental resist fingerprinting mode pica.resize() now returns an error instead of returning random data, nodeca/image-blob-reduce#28.

Fixed

  • Images with Exif orientation are now resized correctly in Chromium-based browsers (it was previously broken in pica 7.0.0), #211.

7.0.0 - 2021-05-23

Changed

  • [BREAKING] Rewrite unsharp mask, use V channel of HSV instead of L channel of HSL, to reduce color shift (#209).
  • [BREAKING] Unsharp mask options are now more close to Photoshop (unsharpAmount should be multiplied by 2 and unsharpThreshold should be divided by 2 if you switch from v6.x).
  • Splitted big Pica methods to smaller ones.
  • Use docker to build webassembly modules.

Added

  • Use OffscreenCanvas when possible (extract image bitmap in webworker).

6.1.1 - 2020-08-20

Fixed

  • Aded Safari canvas GC workaround, #199.

6.1.0 - 2020-07-10

Added

  • Aded OffscreenCanvas support, #195.

6.0.0 - 2020-06-25

Changed

  • Use dist/pica.js as main entry. No more workarounds needed for webpack.
  • Avoid babelify dependency in dependent packages if browserify used.
  • Rewrite build scripts.

Added

  • Added ImageBitmap input support.

5.3.0 - 2020-06-09

Changed

  • Use derequire to allow nested browserify for /dist/pica.js.

5.2.0 - 2020-05-25

Added

  • Aded OffscreenCanvas support, #195.

5.1.1 - 2020-05-18

Fixed

  • Suppress createImageBitmap errors to use fallback, #190.

5.1.0 - 2019-07-15

Changed

  • Bump multimath dependency.

Fixed

  • Avoid possible CSP warnings, caused by WASM check, when feature not requested in options.

5.0.1 - 2019-07-12

Fixed

  • Fix unsharp crash when CIB enabled (from 4.0.0), #160.

Changed

  • Dev deps bump.

5.0.0 - 2018-11-02

Changed

  • Maintenance, babelify upgrade: switch to @babel/core and @babel/preset-env.

4.2.0 - 2018-10-25

Fixed

  • Added bounds check for invalid output canvas size (#155).

Changed

  • Maintenance: dev deps bump.

4.1.1 - 2018-03-31

Changed

  • Should return result via promise (regression), fix #139.

4.1.0 - 2018-03-27

Changed

  • Resize in multiple steps for big scales, fix #135.

4.0.2 - 2018-03-05

Fixed

  • Multimath bump, should fix issue with broken WebAssembly engine in IOS 11.2.x Webkit (Safary/Chrome).

4.0.1 - 2017-10-13

Fixed

  • Attempt to fix failure when WebAssembly disabled via CSP.

4.0.0 - 2017-09-30

Changed

  • Internals rewritten to use multimath library.
  • WebAssembly implementation for unsharp mask, as bonus.

3.0.6 - 2017-07-13

Fixed

  • More constrains for createImageBitmap() use. Filter out browsers without ImageBitmap.prototype.close() method (Chrome 51 etc).

3.0.5 - 2017-06-30

Fixed

  • Avoid Promise use in webworker. Should help with IE11, which suddently fixed creating of webworkers from data URI.

3.0.4 - 2017-04-20

Fixed

  • IE fix.

3.0.3 - 2017-04-18

Fixed

  • Fixed non working .createImageBitmap() resize, but disabled by default due bad quality.

Added

  • Added debug messages.

3.0.2 - 2017-04-16

Fixed

  • Fix wasm crash on upscale, #87.

3.0.1 - 2017-04-14

Fixed

  • Add missed .set() fallback for ancient browsers.

3.0.0 - 2017-04-11

Added

  • Add WebAssembly resizer.
  • Add createImageBitmap() resizer.
  • Add .toBlob() method.

Changed

  • Major rewrite. New API, promise-based.
  • Add async image decode via createImageBitmap().

Removed

  • Drop WebGL resizer.

2.0.8 - 2016-10-01

Changed

  • Set default number of CPUs (workers) to 1 if navigator.hardwareConcurrency not supported (ancient browsers).

2.0.7 - 2016-10-01

Fixed

  • Fix Safary bug (grid could appear on downscaled image).

Changed

  • WEBGL shaders rework (still buggy, not for production).

2.0.6 - 2016-08-04

Fixed

  • Fix tiler math: bad rounding could produce tiles out of src area, #61.

2.0.5 - 2016-07-19

Fixed

  • Fix mem leak: release objectURL, used to create Web Workers.

2.0.4 - 2016-06-24

Changed

  • Deps bump (webworkify). Previous version had problems with IE Edge, #56.

2.0.3 - 2016-06-07

Changed

  • Deps bump. Use fresh webworkify with proper ObjectURL release, #55.

2.0.2 - 2016-03-30

Changed

  • Optimised previous fix.

2.0.1 - 2016-03-30

Fixed

  • Fixed garbage on image edge tiles when alpha exists.

2.0.0 - 2016-03-12

Added

  • Support Image() as input src.

Changed

  • Architecture rework: images are now splitted to tiles to restrict memory use and allow parallel processing.
  • Built-in WebWorkers manager to use all available CPU cores.
  • Feature flags (WW, WEBGL) are forced to false after resize call, if feature not supported or disabled due fatal error.
  • unsharpRadius range restricted to 0.5..2.0.
  • Experimental code for WebGL support (noisy & buggy, disabled by default).
  • .resizeBuffer() is no longer recommended for use. It does not use webworkers anymore (and option transferable is not used too).

1.1.1 - 2015-11-10

Changed

  • Bumped glur version to fix bug in unsharp mask with vertical images.

1.1.0 - 2015-11-09

Changed

  • Unsharp mask now useable.

1.0.8 - 2015-10-28

Fixed

  • Fixed brightness loss due missed value rounding in convolvers.

1.0.7 - 2014-11-18

Fixed

  • Fixed alpha reset for images without alpha channel (regression in 1.0.5).

1.0.6 - 2014-11-08

Changed

  • Removed alpha correction, because canvas data is not premultipled (#13). Thanks to @devongovett.

1.0.5 - 2014-11-03

Changed

  • Expose WebWorker on pica call, to allow early termination of task.
  • Minor speed opts.

1.0.4 - 2014-10-04

Added

  • Added transferable objects support.

Fixed

  • Fixed demo to fork over ssl too.

1.0.3 - 2014-09-29

Added

  • Added unsharp mask implementation (very naive). Need futher work.

Changed

  • ~25% speed boost (thanks to @mraleph for advice).

1.0.2 - 2014-09-27

Fixed

  • Improved capabilities detection.
  • .WW now shows if pica can use Web Workers or not.

1.0.1 - 2014-09-25

Added

  • Enchanced API to allow pass destination buffer by reference.

Fixed

  • Added IE workarounds. Thanks to @noomorph.

1.0.0 - 2014-09-24

Changed

  • First release.