9.0.1 • Published 3 years ago

pica v9.0.1

Weekly downloads
32,694
License
MIT
Repository
github
Last release
3 years ago

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.

psd2template-ccngx-pica-8@coturiv/ngx-picakymove-beneficiaries-front@infinitebrahmanuniverse/nolb-picswizi-chat-sdkguangdaiexcalidraw-hp-test@everything-registry/sub-chunk-2434@wooden-script/pyrographytc-site-buildertc-site-builder-betateaching_component_dsahil_ccsahil_pkgsahil_ugresizer-streamvreditor-sdkvtfmint-nft-danizeanhello_excalhello_excaliimage-blob-reduceimage-sketchpadimage-resize-utilimagehash-webjazz-browser-media-imageshelios-webhelios-web-devhol-excalidrawhelpjsmydraw2324marvel-sitemapopengraphicapretty-fast-image-resizernxs-image-resizerprocess-imagengx-img-maxngx-picang2-img-maxng6-picang2-picang2-pica_angular16node-focuspointnie-rssnuudel-corequickimageresizersmc-webappshowy@antv/vis-steg@alkemio/excalidraw@bobaboard/ui-components@bildvitta/quasar-ui-asteroid@betternotion/excalidraw@chaitin_rivers/excalidraw@code-dot-org/bramblevue-poster-editortry_excalidraw_whiteboard@fdezromero/ngx-pica@dwelle/excalidraw@guangdai/excalidraw@hungnguyen157/excalidraw@idn/util-image@fileverse-dev/excalidraw@edwardw483/excali@edwardw483/excaliwhitelist@gaoding/image-utils@gaoding/editor-framework@etsoo/editor@etsoo/materialui@kristiankostecky/excalidraw@live-change/frontend-auto-form@live-change/frontend-template@live-change/image-frontend@live-change/task-frontend@live-change/video-call-frontend@live-change/blog-frontend@live-change/content-frontend@live-change/balance-frontend@live-change/billing-frontend@lushdigital/ui@maposia/excalidraw@excalidraw/excalidraw@qlibs/react-components@rivigo-ui-commons/utilities@npclown/excalidraw@notud/excalidraw@opentechiz/excalidraw@snapmotion/core@snapmotion/node@tdtdev/excalidraw@self.id/image-utils@cocalc/frontend@thenewvu/excalidraw@zsviczian/excalidraw@whitetrefoil/canvas-compressor@weiwenda/excalidraw@twopiece/utils@volverjs/ui-vueangular-pica
9.0.1

3 years ago

9.0.0

3 years ago

7.1.1

3 years ago

8.0.0

3 years ago

7.1.0

3 years ago

7.0.0

4 years ago

6.1.1

4 years ago

6.1.0

4 years ago

6.0.0

4 years ago

5.3.0

4 years ago

5.2.0

4 years ago

5.1.1

5 years ago

5.1.0

5 years ago

5.0.1

5 years ago

5.0.0

6 years ago

4.2.0

6 years ago

4.1.1

7 years ago

4.1.0

7 years ago

4.0.2

7 years ago

4.0.1

7 years ago

4.0.0

7 years ago

3.0.6

7 years ago

3.0.5

7 years ago

3.0.4

8 years ago

3.0.3

8 years ago

3.0.2

8 years ago

3.0.1

8 years ago

3.0.0

8 years ago

2.0.8

8 years ago

2.0.7

8 years ago

2.0.6

8 years ago

2.0.5

8 years ago

2.0.4

8 years ago

2.0.3

8 years ago

2.0.2

9 years ago

2.0.1

9 years ago

2.0.0

9 years ago

1.1.1

9 years ago

1.1.0

9 years ago

1.0.8

9 years ago

1.0.7

10 years ago

1.0.6

10 years ago

1.0.5

10 years ago

1.0.4

10 years ago

1.0.3

10 years ago

1.0.2

10 years ago

1.0.1

10 years ago

1.0.0

10 years ago