Technical Documentation: lovell/sharp
ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference
Overview (README.md)
sharp
The typical use case for this high speed Node-API module
is to convert large images in common formats to
smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions.
It can be used with all JavaScript runtimes
that provide support for Node-API v9, including
Node.js (>= 20.9.0), Deno and Bun.
Resizing an image is typically 4x-5x faster than using the
quickest ImageMagick and GraphicsMagick settings
due to its use of libvips.
Colour spaces, embedded ICC profiles and alpha transparency channels are all handled correctly.
Lanczos resampling ensures quality is not sacrificed for speed.
As well as image resizing, operations such as
rotation, extraction, compositing and gamma correction are available.
Most modern macOS, Windows and Linux systems
do not require any additional install or runtime dependencies.
Documentation
Visit sharp.pixelplumbing.com for complete
installation instructions,
API documentation,
benchmark tests and
changelog.
Examples
npm install sharp// ESM
import sharp from 'sharp';
// CJS
const sharp = require('sharp');await sharp(inputBuffer)
.resize({ width: 320, height: 240 })
.toFile('output.webp', (err, info) => { ... });const output = await sharp('input.jpg')
.autoOrient()
.resize({ width: 200 })
.jpeg({ mozjpeg: true })
.toBuffer();const semiTransparentRedPng = await sharp({
create: {
width: 48,
height: 48,
channels: 4,
background: { r: 255, g: 0, b: 0, alpha: 0.5 }
}
})
.png()
.toBuffer();const roundedCorners = Buffer.from(
'<svg><rect x="0" y="0" width="200" height="200" rx="50" ry="50"/></svg>'
);
const roundedCornerResizer =
sharp()
.resize(200, 200)
.composite([{
input: roundedCorners,
blend: 'dest-in'
}])
.png();
readableStream
.pipe(roundedCornerResizer)
.pipe(writableStream);Contributing
A guide for contributors
covers reporting bugs, requesting features and submitting code changes.
Licensing
Copyright 2013 Lovell Fuller and others.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Src Content Docs Index (`docs/src/content/docs/index.md`)
title: "High performance Node.js image processing"
The typical use case for this high speed Node-API module
is to convert large images in common formats to
smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions.
It can be used with all JavaScript runtimes
that provide support for Node-API v9, including
Node.js >= 20.9.0, Deno and Bun.
Resizing an image is typically 4x-5x faster than using the
quickest ImageMagick and GraphicsMagick settings
due to its use of libvips.
Colour spaces, embedded ICC profiles and alpha transparency channels are all handled correctly.
Lanczos resampling ensures quality is not sacrificed for speed.
As well as image resizing, operations such as
rotation, extraction, compositing and gamma correction are available.
Most modern macOS, Windows and Linux systems
do not require any additional install or runtime dependencies.
npm install sharpFormats
This module supports reading JPEG, PNG, WebP, GIF, AVIF, TIFF and SVG images.
Output images can be in JPEG, PNG, WebP, GIF, AVIF and TIFF formats as well as uncompressed raw pixel data.
Streams, Buffer objects and the filesystem can be used for input and output.
A single input Stream can be split into multiple processing pipelines and output Streams.
Deep Zoom image pyramids can be generated,
suitable for use with "slippy map" tile viewers like
OpenSeadragon.
Fast
This module is powered by the blazingly fast
libvips image processing library,
originally created in 1989 at Birkbeck College
and currently maintained by a small team led by
John Cupitt.
Only small regions of uncompressed image data
are held in memory and processed at a time,
taking full advantage of multiple CPU cores and L1/L2/L3 cache.
Everything remains non-blocking thanks to libuv,
no child processes are spawned and Promises/async/await are supported.
Optimal
The features of mozjpeg and pngquant can be used
to optimise the file size of JPEG and PNG images respectively,
without having to invoke separate imagemin processes.
Huffman tables are optimised when generating JPEG output images
without having to use separate command line tools like
jpegoptim and
jpegtran.
PNG filtering is disabled by default,
which for diagrams and line art often produces the same result
as pngcrush.
The file size of animated GIF output is optimised
without having to use separate command line tools such as
gifsicle.
Contributing
A guide for contributors
covers reporting bugs, requesting features and submitting code changes.
Licensing
Copyright 2013 Lovell Fuller and others.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Public Humans (`docs/public/humans.txt`)
/* TEAM */
Name: Lovell Fuller
GitHub: https://github.com/lovell
/* THANKS */
Name: John Cupitt
GitHub: https://github.com/jcupitt
Name: Pierre Inglebert
GitHub: https://github.com/pierreinglebert
Name: Jonathan Ong
GitHub: https://github.com/jonathanong
Name: Chanon Sajjamanochai
GitHub: https://github.com/chanon
Name: Juliano Julio
GitHub: https://github.com/julianojulio
Name: Daniel Gasienica
GitHub: https://github.com/gasi
Name: Julian Walker
GitHub: https://github.com/julianwa
Name: Amit Pitaru
GitHub: https://github.com/apitaru
Name: Brandon Aaron
GitHub: https://github.com/brandonaaron
Name: Andreas Lind
GitHub: https://github.com/papandreou
Name: Maurus Cuelenaere
GitHub: https://github.com/mcuelenaere
Name: Linus Unnebäck
GitHub: https://github.com/LinusU
Name: Victor Mateevitsi
GitHub: https://github.com/mvictoras
Name: Alaric Holloway
GitHub: https://github.com/skedastik
Name: Bernhard K. Weisshuhn
GitHub: https://github.com/bkw
Name: David A. Carley
GitHub: https://github.com/dacarley
Name: John Tobin
GitHub: https://github.com/jtobinisaniceguy
Name: Kenton Gray
GitHub: https://github.com/kentongray
Name: Felix Bünemann
GitHub: https://github.com/felixbuenemann
Name: Samy Al Zahrani
GitHub: https://github.com/salzhrani
Name: Chintan Thakkar
GitHub: https://github.com/lemnisk8
Name: F. Orlando Galashan
GitHub: https://github.com/frulo
Name: Kleis Auke Wolthuizen
GitHub: https://github.com/kleisauke
Name: Matt Hirsch
GitHub: https://github.com/mhirsch
Name: Rahul Nanwani
GitHub: https://github.com/rnanwani
Name: Matthias Thoemmes
GitHub: https://github.com/cmtt
Name: Patrick Paskaris
GitHub: https://github.com/ppaskaris
Name: Jérémy Lal
GitHub: https://github.com/kapouer
Name: Alice Monday
GitHub: https://github.com/alice0meta
Name: Kristo Jorgenson
GitHub: https://github.com/kristojorg
Name: Yves Bos
GitHub: https://github.com/YvesBos
Name: Nicolas Coden
GitHub: https://github.com/ncoden
Name: Matt Parrish
GitHub: https://github.com/pbomb
Name: Matthew McEachen
GitHub: https://github.com/mceachen
Name: Jarda Kotěšovec
GitHub: https://github.com/jardakotesovec
Name: Kenric D'Souza
GitHub: https://github.com/AzureByte
Name: Oleh Aleinyk
GitHub: https://github.com/oaleynik
Name: Marcel Bretschneider
GitHub: https://github.com/3epnm
Name: Andrea Bianco
GitHub: https://github.com/BiancoA
Name: Rik Heywood
GitHub: https://github.com/rikh42
Name: Thomas Parisot
GitHub: https://github.com/oncletom
Name: Nathan Graves
GitHub: https://github.com/woolite64
Name: Tom Lokhorst
GitHub: https://github.com/tomlokhorst
Name: Espen Hovlandsdal
GitHub: https://github.com/rexxars
Name: Sylvain Dumont
GitHub: https://github.com/sylvaindumont
Name: Alun Davies
GitHub: https://github.com/alundavies
Name: Aidan Hoolachan
GitHub: https://github.com/ajhool
Name: Axel Eirola
GitHub: https://github.com/aeirola
Name: Freezy
GitHub: https://github.com/freezy
Name: Julian Aubourg
GitHub: https://github.com/jaubourg
Name: Keith Belovay
GitHub: https://github.com/fromkeith
Name: Michael B. Klein
GitHub: https://github.com/mbklein
Name: Jakub Michálek
GitHub: https://github.com/Goues
Name: Ilya Ovdin
GitHub: https://github.com/iovdin
Name: Andargor
GitHub: https://github.com/Andargor
Name: Nicolas Stepien
GitHub: https://github.com/MayhemYDG
Name: Paul Neave
GitHub: https://github.com/neave
Name: Brendan Kennedy
GitHub: https://github.com/rustyguts
Name: Brychan Bennett-Odlum
GitHub: https://github.com/BrychanOdlum
Name: Edward Silverton
GitHub: https://github.com/edsilv
Name: Dumitru Deveatii
GitHub: https://github.com/dimadeveatii
Name: Roland Asmann
GitHub: https://github.com/malice00
Name: Roman Malieiev
GitHub: https://github.com/romaleev
Name: Jerome Vouillon
GitHub: https://github.com/vouillon
Name: Tomáš Szabo
GitHub: https://github.com/deftomat
Name: Robert O'Rourke
GitHub: https://github.com/roborourke
Name: Denis Soldatov
GitHub: https://github.com/derom
Name: Stefan Probst
GitHub: https://github.com/stefanprobst
Name: Thomas Beiganz
GitHub: https://github.com/beig
Name: Florian Busch
GitHub: https://github.com/florian-busch
Name: Matthieu Salettes
GitHub: https://github.com/msalettes
Name: Taneli Vatanen
GitHub: https://github.com/Daiz
Name: Mart Jansink
GitHub: https://github.com/mart-jansink
Name: Tenpi
GitHub: https://github.com/Tenpi
Name: Zaruike
GitHub: https://github.com/Zaruike
Name: Erlend F
GitHub: https://github.com/erf
Name: Drian Naude
GitHub: https://github.com/driannaude
Name: Max Gordon
GitHub: https://github.com/gforge
Name: Chris Banks
GitHub: https://github.com/christopherbradleybanks
Name: codepage949
GitHub: https://github.com/codepage949
Name: Chris Hranj
GitHub: https://github.com/Brodan
Name: Ankur Parihar
GitHub: https://github.com/ankurparihar
Name: Joona Heinikoski
GitHub: https://github.com/joonamo
Name: AlexanderTheGrey
GitHub: https://github.com/AlexanderTheGrey
Name: Blayne Chard
GitHub: https://github.com/blacha
Name: Brahim
GitHub: https://github.com/brahima
Name: Anton Marsden
GitHub: https://github.com/antonmarsden
Name: Marcos Casagrande
GitHub: https://github.com/marcosc90
Name: Emanuel Jöbstl
GitHub: https://github.com/ejoebstl
Name: Tomasz Janowski
GitHub: https://github.com/janaz
Name: Lachlan Newman
GitHub: https://github.com/LachlanNewman
Name: BJJ
GitHub: https://github.com/bianjunjie1981
Name: Dennis Beatty
GitHub: https://github.com/dnsbty
Name: Ingvar Stepanyan
GitHub: https://github.com/RReverser
Name: Tamás András Horváth
GitHub: https://github.com/icetee
Name: Aaron Che
GitHub: https://github.com/yolopunk
Name: Mert Alev
GitHub: https://github.com/mertalev
Name: Adriaan Meuris
GitHub: https://github.com/adriaanmeuris
Name: Richard Hillmann
GitHub: https://github.com/project0
Name: Pongsatorn Manusopit
GitHub: https://github.com/ton11797
Name: Nathan Keynes
GitHub: https://github.com/nkeynes
Name: Sumit D
GitHub: https://github.com/sumitd2
Name: Caleb Meredith
GitHub: https://github.com/calebmer
Name: Don Denton
GitHub: https://github.com/happycollision
Name: Florent Zabera
GitHub: https://github.com/florentzabera
Name: Quentin Pinçon
GitHub: https://github.com/qpincon
Name: Hans Chen
GitHub: https://github.com/hans00
Name: Thibaut Patel
GitHub: https://github.com/tpatel
Name: Maël Nison
GitHub: https://github.com/arcanis
Name: Dmytro Tiapukhin
GitHub: https://github.com/eddienubes
Name: Florian Lefebvre
GitHub: https://github.com/florian-lefebvre
Public Robots (`docs/public/robots.txt`)
User-agent: *
Disallow:
Sitemap: https://sharp.pixelplumbing.com/sitemap-index.xml
Src Content Docs Api Channel (`docs/src/content/docs/api-channel.md`)
This file was auto-generated from JSDoc in lib/channel.js
title: Channel manipulation
removeAlpha
removeAlpha() ⇒
Sharp
Remove alpha channels, if any. This is a no-op if the image does not have an alpha channel.
See also flatten.
Example
sharp('rgba.png')
.removeAlpha()
.toFile('rgb.png', function(err, info) {
// rgb.png is a 3 channel image without an alpha channel
});ensureAlpha
ensureAlpha([alpha]) ⇒
Sharp
Ensure the output image has an alpha transparency channel.
If missing, the added alpha channel will have the specified
transparency level, defaulting to fully-opaque (1).
This is a no-op if the image already has an alpha channel.
Throws:
ErrorInvalid alpha transparency level
Since: 0.21.2
| Param | Type | Default | Description |
|---|---|---|---|
| [alpha] | number |
1 |
alpha transparency level (0=fully-transparent, 1=fully-opaque) |
Example
// rgba.png will be a 4 channel image with a fully-opaque alpha channel
await sharp('rgb.jpg')
.ensureAlpha()
.toFile('rgba.png')Example
// rgba is a 4 channel image with a fully-transparent alpha channel
const rgba = await sharp(rgb)
.ensureAlpha(0)
.toBuffer();extractChannel
extractChannel(channel) ⇒
Sharp
Extract a single channel from a multi-channel image.
The output colourspace will be either b-w (8-bit) or grey16 (16-bit).
Throws:
ErrorInvalid channel
| Param | Type | Description |
|---|---|---|
| channel | number | string |
zero-indexed channel/band number to extract, or red, green, blue or alpha. |
Example
// green.jpg is a greyscale image containing the green channel of the input
await sharp(input)
.extractChannel('green')
.toFile('green.jpg');Example
// red1 is the red value of the first pixel, red2 the second pixel etc.
const [red1, red2, ...] = await sharp(input)
.extractChannel(0)
.raw()
.toBuffer();joinChannel
joinChannel(images, options) ⇒
Sharp
Join one or more channels to the image.
The meaning of the added channels depends on the output colourspace, set with toColourspace().
By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.
Channel ordering follows vips convention:
- sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha.
- CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha.
Buffers may be any of the image formats supported by sharp.
For raw pixel input, the options object should contain a raw attribute, which follows the format of the attribute of the same name in the sharp() constructor.
Throws:
ErrorInvalid parameters
| Param | Type | Description |
|---|---|---|
| images | Array.<(string|Buffer)> | string | Buffer |
one or more images (file paths, Buffers). |
| options | Object |
image options, see sharp() constructor. |
bandbool
bandbool(boolOp) ⇒
Sharp
Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image.
Throws:
ErrorInvalid parameters
| Param | Type | Description |
|---|---|---|
| boolOp | string |
one of and, or or eor to perform that bitwise operation, like the C logic operators &, ` |
Example
sharp('3-channel-rgb-input.png')
.bandbool(sharp.bool.and)
.toFile('1-channel-output.png', function (err, info) {
// The output will be a single channel image where each pixel `P = R & G & B`.
// If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]`
// then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`.
});Src Content Docs Api Colour (`docs/src/content/docs/api-colour.md`)
This file was auto-generated from JSDoc in lib/colour.js
title: Colour manipulation
tint
tint(tint) ⇒
Sharp
Tint the image using the provided colour.
An alpha channel may be present and will be unchanged by the operation.
Throws:
ErrorInvalid parameter
| Param | Type | Description |
|---|---|---|
| tint | string | Object |
Parsed by the color module. |
Example
const output = await sharp(input)
.tint({ r: 255, g: 240, b: 16 })
.toBuffer();greyscale
greyscale([greyscale]) ⇒
Sharp
Convert to 8-bit greyscale; 256 shades of grey.
This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use gamma() with greyscale() for the best results.
By default the output image will be web-friendly sRGB and contain three (identical) colour channels.
This may be overridden by other sharp operations such as toColourspace('b-w'),
which will produce an output image containing one colour channel.
An alpha channel may be present, and will be unchanged by the operation.
| Param | Type | Default |
|---|---|---|
| [greyscale] | Boolean |
true |
Example
const output = await sharp(input).greyscale().toBuffer();grayscale
grayscale([grayscale]) ⇒
Sharp
Alternative spelling of greyscale.
| Param | Type | Default |
|---|---|---|
| [grayscale] | Boolean |
true |
pipelineColourspace
pipelineColourspace([colourspace]) ⇒
Sharp
Set the pipeline colourspace.
The input image will be converted to the provided colourspace at the start of the pipeline.
All operations will use this colourspace before converting to the output colourspace,
as defined by toColourspace.
Throws:
ErrorInvalid parameters
Since: 0.29.0
| Param | Type | Description |
|---|---|---|
| [colourspace] | string |
pipeline colourspace e.g. rgb16, scrgb, lab, grey16 ... |
Example
// Run pipeline in 16 bits per channel RGB while converting final result to 8 bits per channel sRGB.
await sharp(input)
.pipelineColourspace('rgb16')
.toColourspace('srgb')
.toFile('16bpc-pipeline-to-8bpc-output.png')pipelineColorspace
pipelineColorspace([colorspace]) ⇒
Sharp
Alternative spelling of pipelineColourspace.
Throws:
ErrorInvalid parameters
| Param | Type | Description |
|---|---|---|
| [colorspace] | string |
pipeline colorspace. |
toColourspace
toColourspace([colourspace]) ⇒
Sharp
Set the output colourspace.
By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.
Throws:
ErrorInvalid parameters
| Param | Type | Description |
|---|---|---|
| [colourspace] | string |
output colourspace e.g. srgb, rgb, cmyk, lab, b-w ... |
Example
// Output 16 bits per pixel RGB
await sharp(input)
.toColourspace('rgb16')
.toFile('16-bpp.png')toColorspace
toColorspace([colorspace]) ⇒
Sharp
Alternative spelling of toColourspace.
Throws:
ErrorInvalid parameters
| Param | Type | Description |
|---|---|---|
| [colorspace] | string |
output colorspace. |
Src Content Docs Api Composite (`docs/src/content/docs/api-composite.md`)
This file was auto-generated from JSDoc in lib/composite.js
title: Compositing images
composite
composite(images) ⇒
Sharp
Composite image(s) over the processed (resized, extracted etc.) image.
The images to composite must be the same size or smaller than the processed image.
If both top and left options are provided, they take precedence over gravity.
Other operations in the same processing pipeline (e.g. resize, rotate, flip,
flop, extract) will always be applied to the input image before composition.
The blend option can be one of clear, source, over, in, out, atop,dest, dest-over, dest-in, dest-out, dest-atop,xor, add, saturate, multiply, screen, overlay, darken, lighten,colour-dodge, color-dodge, colour-burn,color-burn,hard-light, soft-light, difference, exclusion.
More information about blend modes can be found at
https://www.libvips.org/API/current/enum.BlendMode.html
and https://www.cairographics.org/operators/
Throws:
ErrorInvalid parameters
Since: 0.22.0
| Param | Type | Default | Description |
|---|---|---|---|
| images | Array.<Object> |
Ordered list of images to composite | |
| [images[].input] | Buffer | String |
Buffer containing image data, String containing the path to an image file, or Create object (see below) | |
| [images[].input.create] | Object |
describes a blank overlay to be created. | |
| [images[].input.create.width] | Number |
||
| [images[].input.create.height] | Number |
||
| [images[].input.create.channels] | Number |
3-4 | |
| [images[].input.create.background] | String | Object |
parsed by the color module to extract values for red, green, blue and alpha. | |
| [images[].input.text] | Object |
describes a new text image to be created. | |
| [images[].input.text.text] | string |
text to render as a UTF-8 string. It can contain Pango markup, for example *Le*Monde. |
|
| [images[].input.text.font] | string |
font name to render with. | |
| [images[].input.text.fontfile] | string |
absolute filesystem path to a font file that can be used by font. |
|
| [images[].input.text.width] | number |
0 |
integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. |
| [images[].input.text.height] | number |
0 |
integral number of pixels high. When defined, dpi will be ignored and the text will automatically fit the pixel resolution defined by width and height. Will be ignored if width is not specified or set to 0. |
| [images[].input.text.align] | string |
"'left'" |
text alignment ('left', 'centre', 'center', 'right'). |
| [images[].input.text.justify] | boolean |
false |
set this to true to apply justification to the text. |
| [images[].input.text.dpi] | number |
72 |
the resolution (size) at which to render the text. Does not take effect if height is specified. |
| [images[].input.text.rgba] | boolean |
false |
set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like Red!. |
| [images[].input.text.spacing] | number |
0 |
text line height in points. Will use the font line height if none is specified. |
| [images[].autoOrient] | Boolean |
false |
set to true to use EXIF orientation data, if present, to orient the image. |
| [images[].blend] | String |
'over' |
how to blend this image with the image below. |
| [images[].gravity] | String |
'centre' |
gravity at which to place the overlay. |
| [images[].top] | Number |
the pixel offset from the top edge, an integer between -100000000 and 100000000. | |
| [images[].left] | Number |
the pixel offset from the left edge, an integer between -100000000 and 100000000. | |
| [images[].tile] | Boolean |
false |
set to true to repeat the overlay image across the entire image with the given gravity. |
| [images[].premultiplied] | Boolean |
false |
set to true to avoid premultiplying the image below. Equivalent to the --premultiplied vips option. |
| [images[].density] | Number |
72 |
number representing the DPI for vector overlay image. |
| [images[].raw] | Object |
describes overlay when using raw pixel data. | |
| [images[].raw.width] | Number |
||
| [images[].raw.height] | Number |
||
| [images[].raw.channels] | Number |
||
| [images[].animated] | boolean |
false |
Set to true to read all frames/pages of an animated image. |
| [images[].failOn] | string |
"'warning'" |
@see constructor parameters |
| [images[].limitInputPixels] | number | boolean |
268402689 |
@see constructor parameters |
| [images[].limitInputChannels] | number | boolean |
5 |
@see constructor parameters |
Example
await sharp(background)
.composite([
{ input: layer1, gravity: 'northwest' },
{ input: layer2, gravity: 'southeast' },
])
.toFile('combined.png');Example
const output = await sharp('input.gif', { animated: true })
.composite([
{ input: 'overlay.png', tile: true, blend: 'saturate' }
])
.toBuffer();Example
sharp('input.png')
.rotate(180)
.resize(300)
.flatten( { background: '#ff6600' } )
.composite([{ input: 'overlay.png', gravity: 'southeast' }])
.sharpen()
.withMetadata()
.webp( { quality: 90 } )
.toBuffer()
.then(function(outputBuffer) {
// outputBuffer contains upside down, 300px wide, alpha channel flattened
// onto orange background, composited with overlay.png with SE gravity,
// sharpened, with metadata, 90% quality WebP image data. Phew!
});Src Content Docs Api Constructor (`docs/src/content/docs/api-constructor.md`)
This file was auto-generated from JSDoc in lib/constructor.js
title: Constructor
Sharp
Sharp
Emits: Sharp#event:info, Sharp#event:warning
new
new Sharp([input], [options])
Constructor factory to create an instance of sharp, to which further methods are chained.
JPEG, PNG, WebP, GIF, AVIF or TIFF format image data can be streamed out from this object.
When using Stream based output, derived attributes are available from the info event.
Non-critical problems encountered during processing are emitted as warning events.
Implements the stream.Duplex class.
When loading more than one page/frame of an animated image,
these are combined as a vertically-stacked "toilet roll" image
where the overall height is the pageHeight multiplied by the number of pages.
Throws:
ErrorInvalid parameters
| Param | Type | Default | Description |
|---|---|---|---|
| [input] | Buffer | ArrayBuffer | Uint8Array | Uint8ClampedArray | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array | string | Array |
if present, can be a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or a TypedArray containing raw pixel image data, or a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. An array of inputs can be provided, and these will be joined together. JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. | |
| [options] | Object |
if present, is an Object with optional attributes. | |
| [options.failOn] | string |
"'warning'" |
When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort. Use the default 'warning' level with untrusted input. |
| [options.limitInputPixels] | number | boolean |
268402689 |
Do not process input images where the number of pixels (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted. An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). |
| [options.limitInputChannels] | number | boolean |
5 |
Do not process input images where the number of channels exceeds this limit. Assumes image metadata can be trusted. An integral Number of channels, zero or false to remove limit, true to use default limit of 5. |
| [options.unlimited] | boolean |
false |
Set this to true to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). |
| [options.autoOrient] | boolean |
false |
Set this to true to rotate/flip the image to match EXIF Orientation, if any. |
| [options.sequentialRead] | boolean |
true |
Set this to false to use random access rather than sequential read. Some operations will do this automatically. |
| [options.density] | number |
72 |
The DPI at which to render SVG and PDF images, in the range 1 to 100000. |
| [options.ignoreIcc] | number |
false |
should the embedded ICC profile, if any, be ignored. |
| [options.pages] | number |
1 |
Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages. |
| [options.page] | number |
0 |
Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based. |
| [options.animated] | boolean |
false |
Set to true to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting pages to -1. |
| [options.raw] | Object |
describes raw pixel input image data. See raw() for pixel ordering. |
|
| [options.raw.width] | number |
integral number of pixels wide. | |
| [options.raw.height] | number |
integral number of pixels high. | |
| [options.raw.channels] | number |
integral number of channels, between 1 and 4. | |
| [options.raw.premultiplied] | boolean |
specifies that the raw input has already been premultiplied, set to true to avoid sharp premultiplying the image. (optional, default false) |
|
| [options.raw.pageHeight] | number |
The pixel height of each page/frame for animated images, must be an integral factor of raw.height. |
|
| [options.create] | Object |
describes a new image to be created. | |
| [options.create.width] | number |
integral number of pixels wide. | |
| [options.create.height] | number |
integral number of pixels high. | |
| [options.create.channels] | number |
integral number of channels, either 3 (RGB) or 4 (RGBA). | |
| [options.create.background] | string | Object |
parsed by the color module to extract values for red, green, blue and alpha. | |
| [options.create.pageHeight] | number |
The pixel height of each page/frame for animated images, must be an integral factor of create.height. |
|
| [options.create.noise] | Object |
describes a noise to be created. | |
| [options.create.noise.type] | string |
type of generated noise, currently only gaussian is supported. |
|
| [options.create.noise.mean] | number |
128 |
Mean value of pixels in the generated noise. |
| [options.create.noise.sigma] | number |
30 |
Standard deviation of pixel values in the generated noise. |
| [options.text] | Object |
describes a new text image to be created. | |
| [options.text.text] | string |
text to render as a UTF-8 string. It can contain Pango markup, for example *Le*Monde. |
|
| [options.text.font] | string |
font name to render with. | |
| [options.text.fontfile] | string |
absolute filesystem path to a font file that can be used by font. |
|
| [options.text.width] | number |
0 |
Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. |
| [options.text.height] | number |
0 |
Maximum integral number of pixels high. When defined, dpi will be ignored and the text will automatically fit the pixel resolution defined by width and height. Will be ignored if width is not specified or set to 0. |
| [options.text.align] | string |
"'left'" |
Alignment style for multi-line text ('left', 'centre', 'center', 'right'). |
| [options.text.justify] | boolean |
false |
set this to true to apply justification to the text. |
| [options.text.dpi] | number |
72 |
the resolution (size) at which to render the text. Does not take effect if height is specified. |
| [options.text.rgba] | boolean |
false |
set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like Red!. |
| [options.text.spacing] | number |
0 |
text line height in points. Will use the font line height if none is specified. |
| [options.text.wrap] | string |
"'word'" |
word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'. |
| [options.join] | Object |
describes how an array of input images should be joined. | |
| [options.join.across] | number |
1 |
number of images to join horizontally. |
| [options.join.animated] | boolean |
false |
set this to true to join the images as an animated image, cannot be used with across or shim. |
| [options.join.shim] | number |
0 |
number of pixels to insert between joined images. |
| [options.join.background] | string | Object |
parsed by the color module to extract values for red, green, blue and alpha. | |
| [options.join.halign] | string |
"'left'" |
horizontal alignment style for images joined horizontally ('left', 'centre', 'center', 'right'). |
| [options.join.valign] | string |
"'top'" |
vertical alignment style for images joined vertically ('top', 'centre', 'center', 'bottom'). |
| [options.tiff] | Object |
Describes TIFF specific options. | |
| [options.tiff.subifd] | number |
-1 |
Sub Image File Directory to extract for OME-TIFF, defaults to main image. |
| [options.svg] | Object |
Describes SVG specific options. | |
| [options.svg.stylesheet] | string |
Custom CSS for SVG input, applied with a User Origin during the CSS cascade. | |
| [options.svg.highBitdepth] | boolean |
false |
Set to true to render SVG input at 32-bits per channel (128-bit) instead of 8-bits per channel (32-bit) RGBA. |
| [options.pdf] | Object |
Describes PDF specific options. Requires the use of a globally-installed libvips compiled with support for PDFium, Poppler, ImageMagick or GraphicsMagick. | |
| [options.pdf.background] | string | Object |
Background colour to use when PDF is partially transparent. Parsed by the color module to extract values for red, green, blue and alpha. | |
| [options.openSlide] | Object |
Describes OpenSlide specific options. Requires the use of a globally-installed libvips compiled with support for OpenSlide. | |
| [options.openSlide.level] | number |
0 |
Level to extract from a multi-level input, zero based. |
| [options.jp2] | Object |
Describes JPEG 2000 specific options. Requires the use of a globally-installed libvips compiled with support for OpenJPEG. | |
| [options.jp2.oneshot] | boolean |
false |
Set to true to decode tiled JPEG 2000 images in a single operation, improving compatibility. |
Example
sharp('input.jpg')
.resize(300, 200)
.toFile('output.jpg', function(err) {
// output.jpg is a 300 pixels wide and 200 pixels high image
// containing a scaled and cropped version of input.jpg
});Example
// Read image data from remote URL,
// resize to 300 pixels wide,
// emit an 'info' event with calculated dimensions
// and finally write image data to writableStream
const { body } = await fetch('https://...');
const readableStream = Readable.fromWeb(body);
const transformer = sharp()
.resize(300)
.on('info', ({ height }) => {
console.log(`Image height is ${height}`);
});
readableStream.pipe(transformer).pipe(writableStream);Example
// Web Streams API, requires Node.js >= 24.15.0
import { Duplex } from 'node:stream';
const { body } = await fetch('https://...');
const transformer = Duplex.toWeb(
sharp().resize(300),
{ readableType: 'bytes' }
);
body.pipeThrough(transformer).pipeTo(writable);Example
// Create a blank 300x200 PNG image of semi-translucent red pixels
sharp({
create: {
width: 300,
height: 200,
channels: 4,
background: { r: 255, g: 0, b: 0, alpha: 0.5 }
}
})
.png()
.toBuffer()
.then( ... );Example
// Convert an animated GIF to an animated WebP
await sharp('in.gif', { animated: true }).toFile('out.webp');Example
// Read a raw array of pixels and save it to a png
const input = Uint8Array.from([255, 255, 255, 0, 0, 0]); // or Uint8ClampedArray
const image = sharp(input, {
// because the input does not contain its dimensions or how many channels it has
// we need to specify it in the constructor options
raw: {
width: 2,
height: 1,
channels: 3
}
});
await image.toFile('my-two-pixels.png');Example
// Generate RGB Gaussian noise
await sharp({
create: {
width: 300,
height: 200,
channels: 3,
noise: {
type: 'gaussian',
mean: 128,
sigma: 30
}
}
}).toFile('noise.png');Example
// Generate an image from text
await sharp({
text: {
text: 'Hello, world!',
width: 400, // max width
height: 300 // max height
}
}).toFile('text_bw.png');Example
// Generate an rgba image from text using pango markup and font
await sharp({
text: {
text: '<span foreground="red">Red!</span><span background="cyan">blue</span>',
font: 'sans',
rgba: true,
dpi: 300
}
}).toFile('text_rgba.png');Example
// Join four input images as a 2x2 grid with a 4 pixel gutter
const data = await sharp(
[image1, image2, image3, image4],
{ join: { across: 2, shim: 4 } }
).toBuffer();Example
// Generate a two-frame animated image from emoji
const images = ['😀', '😛'].map(text => ({
text: { text, width: 64, height: 64, channels: 4, rgba: true }
}));
await sharp(images, { join: { animated: true } }).toFile('out.gif');clone
clone() ⇒
Sharp
Take a "snapshot" of the Sharp instance, returning a new instance.
Cloned instances inherit the input of their parent instance.
This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream.
Example
// firstWritableStream receives auto-rotated, resized readableStream
// secondWritableStream receives auto-rotated, extracted region of readableStream
const pipeline = sharp().rotate();
pipeline
.clone()
.resize(800, 600)
.pipe(firstWritableStream);
pipeline
.clone()
.extract({ left: 20, top: 20, width: 100, height: 100 })
.pipe(secondWritableStream);
readableStream.pipe(pipeline);Example
// Create a pipeline that will download an image, resize it and format it to different files
// Using Promises to know when the pipeline is complete
const sharpStream = sharp();
const promises = [];
promises.push(
sharpStream
.clone()
.jpeg({ quality: 100 })
.toFile("originalFile.jpg")
);
promises.push(
sharpStream
.clone()
.resize({ width: 500 })
.jpeg({ quality: 80 })
.toFile("optimized-500.jpg")
);
promises.push(
sharpStream
.clone()
.resize({ width: 500 })
.webp({ quality: 80 })
.toFile("optimized-500.webp")
);
const res = await fetch("https://www.example.com/some-file.jpg")
Readable.fromWeb(res.body).pipe(sharpStream);
await Promise.all(promises);Src Content Docs Api Input (`docs/src/content/docs/api-input.md`)
This file was auto-generated from JSDoc in lib/input.js
title: Input metadata
metadata
metadata([callback]) ⇒
Promise.<Object>|Sharp
Fast access to (uncached) image metadata without decoding any compressed pixel data.
This is read from the header of the input image.
It does not take into consideration any operations to be applied to the output image,
such as resize or rotate.
Dimensions in the response will respect the page and pages properties of the
constructor parameters.
A Promise is returned when callback is not provided.
format: Name of decoder used to parse image e.g.jpeg,png,webp,gif,svg,heif,tiffmediaType: Media Type (MIME Type) e.g.image/jpeg,image/png,image/svg+xml,image/avifsize: Total size of image in bytes, for Stream and Buffer input onlywidth: Number of pixels wide (EXIF orientation is not taken into consideration, see example below)height: Number of pixels high (EXIF orientation is not taken into consideration, see example below)space: Name of colour space interpretation e.g.srgb,rgb,cmyk,lab,b-w...channels: Number of bands e.g.3for sRGB,4for CMYKdepth: Name of pixel depth format e.g.uchar,char,ushort,float...density: Number of pixels per inch (DPI), if presentchromaSubsampling: String containing JPEG chroma subsampling,4:2:0or4:4:4for RGB,4:2:0:4or4:4:4:4for CMYKisProgressive: Boolean indicating whether the image is interlaced using a progressive scanisPalette: Boolean indicating whether the image is palette-based (GIF, PNG).bitsPerSample: Number of bits per sample for each channel (GIF, PNG, HEIF).pages: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebPpageHeight: Number of pixels high each page in a multi-page image will be.loop: Number of times to loop an animated image, zero refers to a continuous loop.delay: Delay in ms between each page in an animated image, provided as an array of integers.pagePrimary: Number of the primary page in a HEIF imagelevels: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlidesubifds: Number of Sub Image File Directories in an OME-TIFF imagebackground: Default background colour, if present, for PNG (bKGD) and GIF imagescompression: The encoder used to compress an HEIF file,av1(AVIF) orhevc(HEIC)resolutionUnit: The unit of resolution (density), eitherinchorcm, if presenthasProfile: Boolean indicating the presence of an embedded ICC profilehasAlpha: Boolean indicating the presence of an alpha transparency channelorientation: Number value of the EXIF Orientation header, if presentexif: Buffer containing raw EXIF data, if presenticc: Buffer containing raw ICC profile data, if presentiptc: Buffer containing raw IPTC data, if presentxmp: Buffer containing raw XMP data, if presentxmpAsString: String containing XMP data, if valid UTF-8.tifftagPhotoshop: Buffer containing raw TIFFTAG_PHOTOSHOP data, if presentformatMagick: String containing format for images loaded via *magickcomments: Array of keyword/text pairs representing PNG text blocks, if present.gainMap.image: HDR gain map, if present, as compressed JPEG image.
| Param | Type | Description |
|---|---|---|
| [callback] | function |
called with the arguments (err, metadata) |
Example
const metadata = await sharp(input).metadata();Example
const image = sharp(inputJpg);
image
.metadata()
.then(function(metadata) {
return image
.resize(Math.round(metadata.width / 2))
.webp()
.toBuffer();
})
.then(function(data) {
// data contains a WebP image half the width and height of the original JPEG
});Example
// Get dimensions taking EXIF Orientation into account.
const { autoOrient } = await sharp(input).metadata();
const { width, height } = autoOrient;stats
stats([callback]) ⇒
Promise.<Object>
Access to pixel-derived image statistics for every channel in the image.
A Promise is returned when callback is not provided.
channels: Array of channel statistics for each channel in the image. Each channel statistic containsmin(minimum value in the channel)max(maximum value in the channel)sum(sum of all values in a channel)squaresSum(sum of squared values in a channel)mean(mean of the values in a channel)stdev(standard deviation for the values in a channel)minX(x-coordinate of one of the pixel where the minimum lies)minY(y-coordinate of one of the pixel where the minimum lies)maxX(x-coordinate of one of the pixel where the maximum lies)maxY(y-coordinate of one of the pixel where the maximum lies)
isOpaque: Is the image fully opaque? Will betrueif the image has no alpha channel or if every pixel is fully opaque.entropy: Histogram-based estimation of greyscale entropy, discarding alpha channel if any.sharpness: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any.dominant: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram.
Note: Statistics are derived from the original input image. Any operations performed on the image must first be
written to a buffer in order to run stats on the result (see third example).
| Param | Type | Description |
|---|---|---|
| [callback] | function |
called with the arguments (err, stats) |
Example
const image = sharp(inputJpg);
image
.stats()
.then(function(stats) {
// stats contains the channel-wise statistics array and the isOpaque value
});Example
const { entropy, sharpness, dominant } = await sharp(input).stats();
const { r, g, b } = dominant;Example
const image = sharp(input);
// store intermediate result
const part = await image.extract(region).toBuffer();
// create new instance to obtain statistics of extracted region
const stats = await sharp(part).stats();Src Content Docs Api Operation (`docs/src/content/docs/api-operation.md`)
This file was auto-generated from JSDoc in lib/operation.js
title: Image operations
rotate
rotate([angle], [options]) ⇒
Sharp
Rotate the output image.
The provided angle is converted to a valid positive degree rotation.
For example, -450 will produce a 270 degree rotation.
When rotating by an angle other than a multiple of 90,
the background colour can be provided with the background option.
For backwards compatibility, if no angle is provided, .autoOrient() will be called.
Only one rotation can occur per pipeline (aside from an initial call without
arguments to orient via EXIF data). Previous calls to rotate in the same
pipeline will be ignored.
Multi-page images can only be rotated by 180 degrees.
Method order is important when rotating, resizing and/or extracting regions,
for example .rotate(x).extract(y) will produce a different result to .extract(y).rotate(x).
Throws:
ErrorInvalid parameters
| Param | Type | Default | Description |
|---|---|---|---|
| [angle] | number |
auto |
angle of rotation. |
| [options] | Object |
if present, is an Object with optional attributes. | |
| [options.background] | string | Object |
"\"#000000\"" |
parsed by the color module to extract values for red, green, blue and alpha. |
Example
const rotateThenResize = await sharp(input)
.rotate(90)
.resize({ width: 16, height: 8, fit: 'fill' })
.toBuffer();
const resizeThenRotate = await sharp(input)
.resize({ width: 16, height: 8, fit: 'fill' })
.rotate(90)
.toBuffer();autoOrient
autoOrient() ⇒
Sharp
Auto-orient based on the EXIF Orientation tag, then remove the tag.
Mirroring is supported and may infer the use of a flip operation.
Only the EXIF Orientation tag is considered; orientation carried in other
places, such as an XMP tiff:Orientation element, is left untouched and
remains the responsibility of the consumer.
Previous or subsequent use of rotate(angle) and either flip() or flop()
will logically occur after auto-orientation, regardless of call order.
Example
const output = await sharp(input).autoOrient().toBuffer();Example
const pipeline = sharp()
.autoOrient()
.resize(null, 200)
.toBuffer(function (err, outputBuffer, info) {
// outputBuffer contains 200px high JPEG image data,
// auto-oriented using EXIF Orientation tag
// info.width and info.height contain the dimensions of the resized image
});
readableStream.pipe(pipeline);flip
flip([flip]) ⇒
Sharp
Mirror the image vertically (up-down) about the x-axis.
This always occurs before rotation, if any.
This operation does not work correctly with multi-page images.
| Param | Type | Default |
|---|---|---|
| [flip] | Boolean |
true |
Example
const output = await sharp(input).flip().toBuffer();flop
flop([flop]) ⇒
Sharp
Mirror the image horizontally (left-right) about the y-axis.
This always occurs before rotation, if any.
| Param | Type | Default |
|---|---|---|
| [flop] | Boolean |
true |
Example
const output = await sharp(input).flop().toBuffer();affine
affine(matrix, [options]) ⇒
Sharp
Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.
You must provide an array of length 4 or a 2x2 affine transformation matrix.
By default, new pixels are filled with a black background. You can provide a background colour with the background option.
A particular interpolator may also be specified. Set the interpolator option to an attribute of the sharp.interpolators Object e.g. sharp.interpolators.nohalo.
In the case of a 2x2 matrix, the transform is:
- X =
matrix[0, 0]* (x +idx) +matrix[0, 1]* (y +idy) +odx - Y =
matrix[1, 0]* (x +idx) +matrix[1, 1]* (y +idy) +ody
where:
- x and y are the coordinates in input image.
- X and Y are the coordinates in output image.
- (0,0) is the upper left corner.
Throws:
ErrorInvalid parameters
Since: 0.27.0
| Param | Type | Default | Description |
|---|---|---|---|
| matrix | Array.<Array.<number>> | Array.<number> |
affine transformation matrix | |
| [options] | Object |
if present, is an Object with optional attributes. | |
| [options.background] | String | Object |
"#000000" |
parsed by the color module to extract values for red, green, blue and alpha. |
| [options.idx] | Number |
0 |
input horizontal offset |
| [options.idy] | Number |
0 |
input vertical offset |
| [options.odx] | Number |
0 |
output horizontal offset |
| [options.ody] | Number |
0 |
output vertical offset |
| [options.interpolator] | String |
sharp.interpolators.bicubic |
interpolator |
Example
const pipeline = sharp()
.affine([[1, 0.3], [0.1, 0.7]], {
background: 'white',
interpolator: sharp.interpolators.nohalo
})
.toBuffer((err, outputBuffer, info) => {
// outputBuffer contains the transformed image
// info.width and info.height contain the new dimensions
});
inputStream
.pipe(pipeline);sharpen
sharpen([options]) ⇒
Sharp
Sharpen the image.
When used without parameters, performs a fast, mild sharpen of the output image.
When a sigma is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space.
Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available.
See libvips sharpen operation.
Throws:
ErrorInvalid parameters
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object |
if present, is an Object with attributes | |
| [options.sigma] | number |
the sigma of the Gaussian mask, where sigma = 1 + radius / 2, between 0.000001 and 10 |
|
| [options.m1] | number |
1.0 |
the level of sharpening to apply to "flat" areas, between 0 and 1000000 |
| [options.m2] | number |
2.0 |
the level of sharpening to apply to "jagged" areas, between 0 and 1000000 |
| [options.x1] | number |
2.0 |
threshold between "flat" and "jagged", between 0 and 1000000 |
| [options.y2] | number |
10.0 |
maximum amount of brightening, between 0 and 1000000 |
| [options.y3] | number |
20.0 |
maximum amount of darkening, between 0 and 1000000 |
Example
const data = await sharp(input).sharpen().toBuffer();Example
const data = await sharp(input).sharpen({ sigma: 2 }).toBuffer();Example
const data = await sharp(input)
.sharpen({
sigma: 2,
m1: 0,
m2: 3,
x1: 3,
y2: 15,
y3: 15,
})
.toBuffer();median
median([size]) ⇒
Sharp
Apply median filter.
When used without parameters the default window is 3x3.
Throws:
ErrorInvalid parameters
| Param | Type | Default | Description |
|---|---|---|---|
| [size] | number |
3 |
square mask size: size x size |
Example
const output = await sharp(input).median().toBuffer();Example
const output = await sharp(input).median(5).toBuffer();blur
blur([options]) ⇒
Sharp
Blur the image.
When used without parameters, performs a fast 3x3 box blur (equivalent to a box linear filter).
When a sigma is provided, performs a slower, more accurate Gaussian blur.
Throws:
ErrorInvalid parameters
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object | number | Boolean |
||
| [options.sigma] | number |
a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where sigma = 1 + radius / 2. |
|
| [options.precision] | string |
"'integer'" |
How accurate the operation should be, one of: integer, float, approximate. |
| [options.minAmplitude] | number |
0.2 |
A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask. |
Example
const boxBlurred = await sharp(input)
.blur()
.toBuffer();Example
const gaussianBlurred = await sharp(input)
.blur(5)
.toBuffer();dilate
dilate([width]) ⇒
Sharp
Expand foreground objects using the dilate morphological operator.
Throws:
ErrorInvalid parameters
| Param | Type | Default | Description |
|---|---|---|---|
| [width] | Number |
1 |
dilation width in pixels. |
Example
const output = await sharp(input)
.dilate()
.toBuffer();erode
erode([width]) ⇒
Sharp
Shrink foreground objects using the erode morphological operator.
Throws:
ErrorInvalid parameters
| Param | Type | Default | Description |
|---|---|---|---|
| [width] | Number |
1 |
erosion width in pixels. |
Example
const output = await sharp(input)
.erode()
.toBuffer();flatten
flatten([options]) ⇒
Sharp
Merge alpha transparency channel, if any, with a background, then remove the alpha channel.
See also removeAlpha.
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object |
||
| [options.background] | string | Object |
"{r: 0, g: 0, b: 0}" |
background colour, parsed by the color module, defaults to black. |
Example
await sharp(rgbaInput)
.flatten({ background: '#F0A703' })
.toBuffer();unflatten
unflatten()
Ensure the image has an alpha channel
with all white pixel values made fully transparent.
Existing alpha channel values for non-white pixels remain unchanged.
Since: 0.32.1
Example
await sharp(rgbInput)
.unflatten()
.toBuffer();Example
await sharp(rgbInput)
.threshold(128, { grayscale: false }) // converter bright pixels to white
.unflatten()
.toBuffer();gamma
gamma([gamma], [gammaOut]) ⇒
Sharp
Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of 1/gamma
then increasing the encoding (brighten) post-resize at a factor of gamma.
This can improve the perceived brightness of a resized image in non-linear colour spaces.
JPEG and WebP input images will not take advantage of the shrink-on-load performance optimisation
when applying a gamma correction.
Supply a second argument to use a different output gamma value, otherwise the first value is used in both cases.
Throws:
ErrorInvalid parameters
| Param | Type | Default | Description |
|---|---|---|---|
| [gamma] | number |
2.2 |
value between 1.0 and 3.0. |
| [gammaOut] | number |
value between 1.0 and 3.0. (optional, defaults to same as gamma) |
negate
negate([options]) ⇒
Sharp
Produce the "negative" of the image.
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object |
||
| [options.alpha] | Boolean |
true |
Whether or not to negate any alpha channel |
Example
const output = await sharp(input)
.negate()
.toBuffer();Example
const output = await sharp(input)
.negate({ alpha: false })
.toBuffer();normalise
normalise([options]) ⇒
Sharp
Enhance output image contrast by stretching its luminance to cover a full dynamic range.
Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes.
Luminance values below the lower percentile will be underexposed by clipping to zero.
Luminance values above the upper percentile will be overexposed by clipping to the max pixel value.
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object |
||
| [options.lower] | number |
1 |
Percentile below which luminance values will be underexposed. |
| [options.upper] | number |
99 |
Percentile above which luminance values will be overexposed. |
Example
const output = await sharp(input)
.normalise()
.toBuffer();Example
const output = await sharp(input)
.normalise({ lower: 0, upper: 100 })
.toBuffer();normalize
normalize([options]) ⇒
Sharp
Alternative spelling of normalise.
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object |
||
| [options.lower] | number |
1 |
Percentile below which luminance values will be underexposed. |
| [options.upper] | number |
99 |
Percentile above which luminance values will be overexposed. |
Example
const output = await sharp(input)
.normalize()
.toBuffer();clahe
clahe(options) ⇒
Sharp
Perform contrast limiting adaptive histogram equalization
CLAHE.
This will, in general, enhance the clarity of the image by bringing out darker details.
Throws:
ErrorInvalid parameters
Since: 0.28.3
| Param | Type | Default | Description |
|---|---|---|---|
| options | Object |
||
| options.width | number |
Integral width of the search window, in pixels, between 1 and 65536. | |
| options.height | number |
Integral height of the search window, in pixels, between 1 and 65536. | |
| [options.maxSlope] | number |
3 |
Integral level of brightening, between 0 and 100, where 0 disables contrast limiting. |
Example
const output = await sharp(input)
.clahe({
width: 3,
height: 3,
})
.toBuffer();convolve
convolve(kernel) ⇒
Sharp
Convolve the image with the specified kernel.
Throws:
ErrorInvalid parameters
| Param | Type | Default | Description |
|---|---|---|---|
| kernel | Object |
||
| kernel.width | number |
width of the kernel in pixels. | |
| kernel.height | number |
height of the kernel in pixels. | |
| kernel.kernel | Array.<number> |
Array of length width*height containing the kernel values. |
|
| [kernel.scale] | number |
sum |
the scale of the kernel in pixels. |
| [kernel.offset] | number |
0 |
the offset of the kernel in pixels. |
Example
sharp(input)
.convolve({
width: 3,
height: 3,
kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1]
})
.raw()
.toBuffer(function(err, data, info) {
// data contains the raw pixel data representing the convolution
// of the input image with the horizontal Sobel operator
});threshold
threshold([threshold], [options]) ⇒
Sharp
Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0.
Throws:
ErrorInvalid parameters
| Param | Type | Default | Description |
|---|---|---|---|
| [threshold] | number |
128 |
a value in the range 0-255 representing the level at which the threshold will be applied. |
| [options] | Object |
||
| [options.greyscale] | Boolean |
true |
convert to single channel greyscale. |
| [options.grayscale] | Boolean |
true |
alternative spelling for greyscale. |
boolean
boolean(operand, operator, [options]) ⇒
Sharp
Perform a bitwise boolean operation with operand image.
This operation creates an output image where each pixel is the result of
the selected bitwise boolean operation between the corresponding pixels of the input images.
Throws:
ErrorInvalid parameters
| Param | Type | Description |
|---|---|---|
| operand | Buffer | string |
Buffer containing image data or string containing the path to an image file. |
| operator | string |
one of and, or or eor to perform that bitwise operation, like the C logic operators &, ` |
| [options] | Object |
|
| [options.raw] | Object |
describes operand when using raw pixel data. |
| [options.raw.width] | number |
|
| [options.raw.height] | number |
|
| [options.raw.channels] | number |
linear
linear([a], [b]) ⇒
Sharp
Apply the linear formula a * input + b to the image to adjust image levels.
When a single number is provided, it will be used for all image channels.
When an array of numbers is provided, the array length must match the number of channels.
Throws:
ErrorInvalid parameters
| Param | Type | Default | Description |
|---|---|---|---|
| [a] | number | Array.<number> |
[] |
multiplier |
| [b] | number | Array.<number> |
[] |
offset |
Example
await sharp(input)
.linear(0.5, 2)
.toBuffer();Example
await sharp(rgbInput)
.linear(
[0.25, 0.5, 0.75],
[150, 100, 50]
)
.toBuffer();recomb
recomb(inputMatrix) ⇒
Sharp
Recombine the image with the specified matrix.
Throws:
ErrorInvalid parameters
Since: 0.21.1
| Param | Type | Description |
|---|---|---|
| inputMatrix | Array.<Array.<number>> |
3x3 or 4x4 Recombination matrix |
Example
sharp(input)
.recomb([
[0.3588, 0.7044, 0.1368],
[0.2990, 0.5870, 0.1140],
[0.2392, 0.4696, 0.0912],
])
.raw()
.toBuffer(function(err, data, info) {
// data contains the raw pixel data after applying the matrix
// With this example input, a sepia filter has been applied
});modulate
modulate([options]) ⇒
Sharp
Transforms the image using brightness, saturation, hue rotation, and lightness.
Brightness and lightness both operate on luminance, with the difference being that
brightness is multiplicative whereas lightness is additive.
Since: 0.22.1
| Param | Type | Description |
|---|---|---|
| [options] | Object |
|
| [options.brightness] | number |
Brightness multiplier |
| [options.saturation] | number |
Saturation multiplier |
| [options.hue] | number |
Degrees for hue rotation |
| [options.lightness] | number |
Lightness addend |
Example
// increase brightness by a factor of 2
const output = await sharp(input)
.modulate({
brightness: 2
})
.toBuffer();Example
// hue-rotate by 180 degrees
const output = await sharp(input)
.modulate({
hue: 180
})
.toBuffer();Example
// increase lightness by +50
const output = await sharp(input)
.modulate({
lightness: 50
})
.toBuffer();Example
// decrease brightness and saturation while also hue-rotating by 90 degrees
const output = await sharp(input)
.modulate({
brightness: 0.5,
saturation: 0.5,
hue: 90,
})
.toBuffer();Src Content Docs Api Output (`docs/src/content/docs/api-output.md`)
This file was auto-generated from JSDoc in lib/output.js
title: Output options
toFile
toFile(fileOut, [callback]) ⇒
Promise.<Object>
Write output image data to a file.
If an explicit output format is not selected, it will be inferred from the extension,
with JPEG, PNG, WebP, AVIF, TIFF, GIF, DZI, and libvips' V format supported.
Note that raw pixel data is only supported for buffer output.
By default all metadata will be removed, which includes EXIF-based orientation.
See withMetadata for control over this.
The caller is responsible for ensuring directory structures and permissions exist.
A Promise is returned when callback is not provided.
Returns: Promise.<Object> - - when no callback is provided
Throws:
ErrorInvalid parameters
| Param | Type | Description |
|---|---|---|
| fileOut | string |
the path to write the image data to. |
| [callback] | function |
called on completion with two arguments (err, info). info contains the output image format, size (bytes), width, height, channels and premultiplied (indicating if premultiplication was used). When using a crop strategy also contains cropOffsetLeft and cropOffsetTop. When using the attention crop strategy also contains attentionX and attentionY, the focal point of the cropped region. Animated output will also contain pageHeight and pages. May also contain textAutofitDpi (dpi the font was rendered at) if image was created from text. |
Example
sharp(input)
.toFile('output.png', (err, info) => { ... });Example
sharp(input)
.toFile('output.png')
.then(info => { ... })
.catch(err => { ... });toBuffer
toBuffer([options], [callback]) ⇒
Promise.<Buffer>
Write output to a Buffer.
JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.
Use toFormat or one of the format-specific functions such as jpeg, png etc. to set the output format.
If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output.
By default all metadata will be removed, which includes EXIF-based orientation.
See withMetadata for control over this.
callback, if present, gets three arguments (err, data, info) where:
erris an error, if any.datais the output image data.infocontains the output imageformat,size(bytes),width,height,channelsandpremultiplied(indicating if premultiplication was used).
When using a crop strategy also containscropOffsetLeftandcropOffsetTop.
Animated output will also containpageHeightandpages.
May also containtextAutofitDpi(dpi the font was rendered at) if image was created from text.
The underlying ArrayBuffer may be marked as non-transferable by some JavaScript runtimes.
Use toUint8Array for a guaranteed transferable ArrayBuffer.
A Promise is returned when callback is not provided.
Returns: Promise.<Buffer> - - when no callback is provided
| Param | Type | Description |
|---|---|---|
| [options] | Object |
|
| [options.resolveWithObject] | boolean |
Resolve the Promise with an Object containing data and info properties instead of resolving only with data. |
| [callback] | function |
Example
const data = await sharp(input)
.png()
.toBuffer();Example
const { data, info } = await sharp(input)
.png()
.toBuffer({ resolveWithObject: true });Example
const { data, info } = await sharp('my-image.jpg')
// output the raw pixels
.raw()
.toBuffer({ resolveWithObject: true });
// create a more type safe way to work with the raw pixel data
// this will not copy the data, instead it will change `data`s underlying ArrayBuffer
// so `data` and `pixelArray` point to the same memory location
const pixelArray = new Uint8ClampedArray(data.buffer);
// When you are done changing the pixelArray, sharp takes the `pixelArray` as an input
const { width, height, channels } = info;
await sharp(pixelArray, { raw: { width, height, channels } })
.toFile('my-changed-image.jpg');toUint8Array
toUint8Array() ⇒
Promise.<{data: Uint8Array, info: Object}>
Write output to a Uint8Array backed by a transferable ArrayBuffer.
JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.
Use toFormat or one of the format-specific functions such as jpeg, png etc. to set the output format.
If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output.
By default all metadata will be removed, which includes EXIF-based orientation.
See keepExif and similar methods for control over this.
Resolves with an Object containing:
datais the output image as aUint8Arraybacked by a transferableArrayBuffer.infocontains properties relating to the output image such aswidthandheight.
Since: v0.35.0
Example
const { data, info } = await sharp(input).toUint8Array();Example
const { data } = await sharp(input)
.avif()
.toUint8Array();
const base64String = data.toBase64();withDensity
withDensity(density) ⇒
Sharp
Set output density (DPI) in EXIF metadata.
Throws:
ErrorInvalid parameters
Since: 0.35.0
| Param | Type | Description |
|---|---|---|
| density | number |
Number of pixels per inch (DPI), between 1 and 100000. |
Example
const data = await sharp(input)
.withDensity(96)
.toBuffer();keepExif
keepExif() ⇒
Sharp
Keep all EXIF metadata from the input image in the output image.
EXIF metadata is unsupported for TIFF output.
Since: 0.33.0
Example
const outputWithExif = await sharp(inputWithExif)
.keepExif()
.toBuffer();withExif
withExif(exif) ⇒
Sharp
Set EXIF metadata in the output image, ignoring any EXIF in the input image.
Throws:
ErrorInvalid parameters
Since: 0.33.0
| Param | Type | Description |
|---|---|---|
| exif | Object.<string, Object.<string, string>> |
Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. |
Example
const dataWithExif = await sharp(input)
.withExif({
IFD0: {
Copyright: 'The National Gallery'
},
IFD3: {
GPSLatitudeRef: 'N',
GPSLatitude: '51/1 30/1 3230/100',
GPSLongitudeRef: 'W',
GPSLongitude: '0/1 7/1 4366/100'
}
})
.toBuffer();withExifMerge
withExifMerge(exif) ⇒
Sharp
Update EXIF metadata from the input image in the output image.
Throws:
ErrorInvalid parameters
Since: 0.33.0
| Param | Type | Description |
|---|---|---|
| exif | Object.<string, Object.<string, string>> |
Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. |
Example
const dataWithMergedExif = await sharp(inputWithExif)
.withExifMerge({
IFD0: {
Copyright: 'The National Gallery'
}
})
.toBuffer();keepIccProfile
keepIccProfile() ⇒
Sharp
Keep ICC profile from the input image in the output image.
When input and output colour spaces differ, use with toColourspace and optionally pipelineColourspace.
Since: 0.33.0
Example
const outputWithIccProfile = await sharp(inputWithIccProfile)
.keepIccProfile()
.toBuffer();Example
const cmykOutputWithIccProfile = await sharp(cmykInputWithIccProfile)
.pipelineColourspace('cmyk')
.toColourspace('cmyk')
.keepIccProfile()
.toBuffer();withIccProfile
withIccProfile(icc, [options]) ⇒
Sharp
Transform using an ICC profile and attach to the output image.
This can either be an absolute filesystem path or
built-in profile name (srgb, p3, cmyk).
Throws:
ErrorInvalid parameters
Since: 0.33.0
| Param | Type | Default | Description |
|---|---|---|---|
| icc | string |
Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk). | |
| [options] | Object |
||
| [options.attach] | number |
true |
Should the ICC profile be included in the output image metadata? |
Example
const outputWithP3 = await sharp(input)
.withIccProfile('p3')
.toBuffer();keepGainMap
keepGainMap() ⇒
Sharp
If the input contains gain map metadata, attempt to process the image and gain map separately,
recombining them into a single output image.
This approach is faster and should produce better results than withGainMap,
however not all operations are supported.
Only JPEG input and output are supported.
JPEG output options other than quality are ignored.
This feature is experimental and the API may change.
Since: 0.35.0
Example
const outputWithResizedGainMap = await sharp(inputWithGainMap)
.keepGainMap()
.resize({ width: 64 })
.toBuffer();withGainMap
withGainMap() ⇒
Sharp
If the input contains gain map metadata, use it to convert the main image to HDR (High Dynamic Range) before further processing.
The input gain map is discarded.
If the output is JPEG, generate and attach a new ISO 21496-1 gain map.
JPEG output options other than quality are ignored.
This feature is experimental and the API may change.
Since: 0.35.0
Example
const outputWithRegeneratedGainMap = await sharp(inputWithGainMap)
.withGainMap()
.toBuffer();keepXmp
keepXmp() ⇒
Sharp
Keep XMP metadata from the input image in the output image.
Since: 0.34.3
Example
const outputWithXmp = await sharp(inputWithXmp)
.keepXmp()
.toBuffer();withXmp
withXmp(xmp) ⇒
Sharp
Set XMP metadata in the output image.
Supported by PNG, JPEG, WebP, and TIFF output.
Throws:
ErrorInvalid parameters
Since: 0.34.3
| Param | Type | Description |
|---|---|---|
| xmp | string |
String containing XMP metadata to be embedded in the output image. |
Example
const xmpString = `
<?xml version="1.0"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">
<dc:creator><rdf:Seq><rdf:li>John Doe</rdf:li></rdf:Seq></dc:creator>
</rdf:Description>
</rdf:RDF>
</x:xmpmeta>`;
const data = await sharp(input)
.withXmp(xmpString)
.toBuffer();keepMetadata
keepMetadata() ⇒
Sharp
Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image.
The default behaviour, when keepMetadata is not used, is to convert to the device-independent
sRGB colour space and strip all metadata, including the removal of any ICC profile.
Since: 0.33.0
Example
const outputWithMetadata = await sharp(inputWithMetadata)
.keepMetadata()
.toBuffer();withMetadata
withMetadata([options]) ⇒
Sharp
Keep most metadata (EXIF, XMP, IPTC) from the input image in the output image.
This will also convert to and add a web-friendly sRGB ICC profile if appropriate.
Allows orientation and density to be set or updated.
Throws:
ErrorInvalid parameters
| Param | Type | Description |
|---|---|---|
| [options] | Object |
|
| [options.orientation] | number |
Used to update the EXIF Orientation tag, integer between 1 and 8. |
| [options.density] | number |
Number of pixels per inch (DPI), between 1 and 100000. |
Example
const outputSrgbWithMetadata = await sharp(inputRgbWithMetadata)
.withMetadata()
.toBuffer();Example
// Set output metadata to 96 DPI
const data = await sharp(input)
.withMetadata({ density: 96 })
.toBuffer();toFormat
toFormat(format, options) ⇒
Sharp
Force output to a given format.
Throws:
Errorunsupported format or options
| Param | Type | Description |
|---|---|---|
| format | string | Object |
as a string or an Object with an 'id' attribute |
| options | Object |
output options |
Example
// Convert any input to PNG output
const data = await sharp(input)
.toFormat('png')
.toBuffer();jpeg
jpeg([options]) ⇒
Sharp
Use these JPEG options for output image.
Throws:
ErrorInvalid options
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object |
output options | |
| [options.quality] | number |
80 |
quality, integer 1-100 |
| [options.progressive] | boolean |
false |
use progressive (interlace) scan |
| [options.chromaSubsampling] | string |
"'4:2:0'" |
set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling |
| [options.optimiseCoding] | boolean |
true |
optimise Huffman coding tables |
| [options.optimizeCoding] | boolean |
true |
alternative spelling of optimiseCoding |
| [options.mozjpeg] | boolean |
false |
use mozjpeg defaults, equivalent to { trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 } |
| [options.trellisQuantisation] | boolean |
false |
apply trellis quantisation |
| [options.overshootDeringing] | boolean |
false |
apply overshoot deringing |
| [options.optimiseScans] | boolean |
false |
optimise progressive scans, forces progressive |
| [options.optimizeScans] | boolean |
false |
alternative spelling of optimiseScans |
| [options.quantisationTable] | number |
0 |
quantization table to use, integer 0-8 |
| [options.quantizationTable] | number |
0 |
alternative spelling of quantisationTable |
| [options.force] | boolean |
true |
force JPEG output, otherwise attempt to use input format |
Example
// Convert any input to very high quality JPEG output
const data = await sharp(input)
.jpeg({
quality: 100,
chromaSubsampling: '4:4:4'
})
.toBuffer();Example
// Use mozjpeg to reduce output JPEG file size (slower)
const data = await sharp(input)
.jpeg({ mozjpeg: true })
.toBuffer();png
png([options]) ⇒
Sharp
Use these PNG options for output image.
By default, PNG output is full colour at 8 bits per pixel.
Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel.
Set palette to true for slower, indexed PNG output.
For 16 bits per pixel output, convert to rgb16 via
toColourspace.
Throws:
ErrorInvalid options
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object |
||
| [options.progressive] | boolean |
false |
use progressive (interlace) scan |
| [options.compressionLevel] | number |
6 |
zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest) |
| [options.adaptiveFiltering] | boolean |
false |
use adaptive row filtering |
| [options.palette] | boolean |
false |
quantise to a palette-based image with alpha transparency support |
| [options.quality] | number |
100 |
use the lowest number of colours needed to achieve given quality, sets palette to true |
| [options.effort] | number |
7 |
CPU effort, between 1 (fastest) and 10 (slowest), sets palette to true |
| [options.colours] | number |
256 |
maximum number of palette entries, sets palette to true |
| [options.colors] | number |
256 |
alternative spelling of options.colours, sets palette to true |
| [options.dither] | number |
1.0 |
level of Floyd-Steinberg error diffusion, sets palette to true |
| [options.force] | boolean |
true |
force PNG output, otherwise attempt to use input format |
Example
// Convert any input to full colour PNG output
const data = await sharp(input)
.png()
.toBuffer();Example
// Convert any input to indexed PNG output (slower)
const data = await sharp(input)
.png({ palette: true })
.toBuffer();Example
// Output 16 bits per pixel RGB(A)
const data = await sharp(input)
.toColourspace('rgb16')
.png()
.toBuffer();webp
webp([options]) ⇒
Sharp
Use these WebP options for output image.
Throws:
ErrorInvalid options
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object |
output options | |
| [options.quality] | number |
80 |
quality, integer 1-100 |
| [options.alphaQuality] | number |
100 |
quality of alpha layer, integer 0-100 |
| [options.lossless] | boolean |
false |
use lossless compression mode |
| [options.nearLossless] | boolean |
false |
use near_lossless compression mode |
| [options.smartSubsample] | boolean |
false |
use high quality chroma subsampling |
| [options.smartDeblock] | boolean |
false |
auto-adjust the deblocking filter, can improve low contrast edges (slow) |
| [options.preset] | string |
"'default'" |
named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text |
| [options.effort] | number |
4 |
CPU effort, between 0 (fastest) and 6 (slowest) |
| [options.loop] | number |
0 |
number of animation iterations, use 0 for infinite animation |
| [options.delay] | number | Array.<number> |
delay(s) between animation frames (in milliseconds) | |
| [options.minSize] | boolean |
false |
prevent use of animation key frames to minimise file size (slow) |
| [options.mixed] | boolean |
false |
allow mixture of lossy and lossless animation frames (slow) |
| [options.exact] | boolean |
false |
preserve the colour data in transparent pixels |
| [options.force] | boolean |
true |
force WebP output, otherwise attempt to use input format |
Example
// Convert any input to lossless WebP output
const data = await sharp(input)
.webp({ lossless: true })
.toBuffer();Example
// Optimise the file size of an animated WebP
const outputWebp = await sharp(inputWebp, { animated: true })
.webp({ effort: 6 })
.toBuffer();gif
gif([options]) ⇒
Sharp
Use these GIF options for the output image.
The first entry in the palette is reserved for transparency.
The palette of the input image will be re-used if possible.
Throws:
ErrorInvalid options
Since: 0.30.0
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object |
output options | |
| [options.reuse] | boolean |
true |
re-use existing palette, otherwise generate new (slow) |
| [options.progressive] | boolean |
false |
use progressive (interlace) scan |
| [options.colours] | number |
256 |
maximum number of palette entries, including transparency, between 2 and 256 |
| [options.colors] | number |
256 |
alternative spelling of options.colours |
| [options.effort] | number |
7 |
CPU effort, between 1 (fastest) and 10 (slowest) |
| [options.dither] | number |
1.0 |
level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) |
| [options.interFrameMaxError] | number |
0 |
maximum inter-frame error for transparency, between 0 (lossless) and 32 |
| [options.interPaletteMaxError] | number |
3 |
maximum inter-palette error for palette reuse, between 0 and 256 |
| [options.keepDuplicateFrames] | boolean |
false |
keep duplicate frames in the output instead of combining them |
| [options.loop] | number |
0 |
number of animation iterations, use 0 for infinite animation |
| [options.delay] | number | Array.<number> |
delay(s) between animation frames (in milliseconds) | |
| [options.force] | boolean |
true |
force GIF output, otherwise attempt to use input format |
Example
// Convert PNG to GIF
await sharp(pngBuffer)
.gif()
.toBuffer();Example
// Convert animated WebP to animated GIF
await sharp('animated.webp', { animated: true })
.toFile('animated.gif');Example
// Create a 128x128, cropped, non-dithered, animated thumbnail of an animated GIF
const out = await sharp('in.gif', { animated: true })
.resize({ width: 128, height: 128 })
.gif({ dither: 0 })
.toBuffer();Example
// Lossy file size reduction of animated GIF
await sharp('in.gif', { animated: true })
.gif({ interFrameMaxError: 8 })
.toFile('optim.gif');jp2
jp2([options]) ⇒
Sharp
Use these JP2 options for output image.
Requires libvips compiled with support for OpenJPEG.
The prebuilt binaries do not include this - see
installing a custom libvips.
Throws:
ErrorInvalid options
Since: 0.29.1
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object |
output options | |
| [options.quality] | number |
80 |
quality, integer 1-100 |
| [options.lossless] | boolean |
false |
use lossless compression mode |
| [options.tileWidth] | number |
512 |
horizontal tile size |
| [options.tileHeight] | number |
512 |
vertical tile size |
| [options.chromaSubsampling] | string |
"'4:4:4'" |
set to '4:2:0' to use chroma subsampling |
Example
// Convert any input to lossless JP2 output
const data = await sharp(input)
.jp2({ lossless: true })
.toBuffer();Example
// Convert any input to very high quality JP2 output
const data = await sharp(input)
.jp2({
quality: 100,
chromaSubsampling: '4:4:4'
})
.toBuffer();tiff
tiff([options]) ⇒
Sharp
Use these TIFF options for output image.
The density can be set in pixels/inch via withMetadata
instead of providing xres and yres in pixels/mm.
Throws:
ErrorInvalid options
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object |
output options | |
| [options.quality] | number |
80 |
quality, integer 1-100 |
| [options.force] | boolean |
true |
force TIFF output, otherwise attempt to use input format |
| [options.compression] | string |
"'jpeg'" |
compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k |
| [options.bigtiff] | boolean |
false |
use BigTIFF variant (has no effect when compression is none) |
| [options.predictor] | string |
"'horizontal'" |
compression predictor options: none, horizontal, float |
| [options.pyramid] | boolean |
false |
write an image pyramid |
| [options.tile] | boolean |
false |
write a tiled tiff |
| [options.tileWidth] | number |
256 |
horizontal tile size, valid values are integers in the range 1-32768 |
| [options.tileHeight] | number |
256 |
vertical tile size, valid values are integers in the range 1-32768 |
| [options.xres] | number |
1.0 |
horizontal resolution in pixels/mm, valid values are numbers in the range 0.001-1000000 |
| [options.yres] | number |
1.0 |
vertical resolution in pixels/mm, valid values are numbers in the range 0.001-1000000 |
| [options.resolutionUnit] | string |
"'inch'" |
resolution unit options: inch, cm |
| [options.bitdepth] | number |
0 |
reduce bitdepth to 1, 2 or 4 bit |
| [options.miniswhite] | boolean |
false |
write 1-bit images as miniswhite |
Example
// Convert SVG input to LZW-compressed, 1 bit per pixel TIFF output
sharp('input.svg')
.tiff({
compression: 'lzw',
bitdepth: 1
})
.toFile('1-bpp-output.tiff')
.then(info => { ... });avif
avif([options]) ⇒
Sharp
Use these AVIF options for output image.
AVIF image sequences are not supported.
Throws:
ErrorInvalid options
Since: 0.27.0
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object |
output options | |
| [options.quality] | number |
50 |
quality, integer 1-100 |
| [options.lossless] | boolean |
false |
use lossless compression |
| [options.effort] | number |
4 |
CPU effort, between 0 (fastest) and 9 (slowest) |
| [options.chromaSubsampling] | string |
"'4:4:4'" |
set to '4:2:0' to use chroma subsampling |
| [options.bitdepth] | number |
8 |
set bitdepth to 8, 10 or 12 bit |
| [options.tune] | string |
"'auto'" |
tune output for a quality metric, one of 'auto' (default), 'iq', 'psnr' or 'ssim' |
Example
const data = await sharp(input)
.avif({ effort: 2 })
.toBuffer();Example
const data = await sharp(input)
.avif({ lossless: true })
.toBuffer();heif
heif(options) ⇒
Sharp
Use these HEIF options for output image.
Support for patent-encumbered HEIC images using hevc compression requires the use of a
globally-installed libvips compiled with support for libheif, libde265 and x265.
Throws:
ErrorInvalid options
Since: 0.23.0
| Param | Type | Default | Description |
|---|---|---|---|
| options | Object |
output options | |
| options.compression | string |
compression format: av1, hevc | |
| [options.quality] | number |
50 |
quality, integer 1-100 |
| [options.lossless] | boolean |
false |
use lossless compression |
| [options.effort] | number |
4 |
CPU effort, between 0 (fastest) and 9 (slowest) |
| [options.chromaSubsampling] | string |
"'4:4:4'" |
set to '4:2:0' to use chroma subsampling |
| [options.bitdepth] | number |
8 |
set bitdepth to 8, 10 or 12 bit |
| [options.tune] | string |
"'auto'" |
tune output for a quality metric, one of 'auto' (av1 default), 'iq' (av1 only), 'psnr' or 'ssim' (hevc default) |
Example
const data = await sharp(input)
.heif({ compression: 'hevc' })
.toBuffer();jxl
jxl([options]) ⇒
Sharp
Use these JPEG-XL (JXL) options for output image.
This feature is experimental, please do not use in production systems.
Requires libvips compiled with support for libjxl.
The prebuilt binaries do not include this - see
installing a custom libvips.
Throws:
ErrorInvalid options
Since: 0.31.3
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object |
output options | |
| [options.distance] | number |
1.0 |
maximum encoding error, between 0 (highest quality) and 15 (lowest quality) |
| [options.quality] | number |
calculate distance based on JPEG-like quality, between 1 and 100, overrides distance if specified |
|
| [options.decodingTier] | number |
0 |
target decode speed tier, between 0 (highest quality) and 4 (lowest quality) |
| [options.lossless] | boolean |
false |
use lossless compression |
| [options.effort] | number |
7 |
CPU effort, between 1 (fastest) and 9 (slowest) |
| [options.loop] | number |
0 |
number of animation iterations, use 0 for infinite animation |
| [options.delay] | number | Array.<number> |
delay(s) between animation frames (in milliseconds) |
raw
raw([options]) ⇒
Sharp
Force output to be raw, uncompressed pixel data.
Pixel ordering is left-to-right, top-to-bottom, without padding.
Channel ordering will be RGB or RGBA for non-greyscale colourspaces.
Throws:
ErrorInvalid options
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object |
output options | |
| [options.depth] | string |
"'uchar'" |
bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex |
Example
// Extract raw, unsigned 8-bit RGB pixel data from JPEG input
const { data, info } = await sharp('input.jpg')
.raw()
.toBuffer({ resolveWithObject: true });Example
// Extract alpha channel as raw, unsigned 16-bit pixel data from PNG input
const data = await sharp('input.png')
.ensureAlpha()
.extractChannel(3)
.toColourspace('b-w')
.raw({ depth: 'ushort' })
.toBuffer();tile
tile([options]) ⇒
Sharp
Use tile-based deep zoom (image pyramid) output.
Set the format and options for tile images via the toFormat, jpeg, png or webp functions.
Use a .zip or .szi file extension with toFile to write to a compressed archive file format.
The container will be set to zip when the output is a Buffer or Stream, otherwise it will default to fs.
Throws:
ErrorInvalid parameters
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object |
||
| [options.size] | number |
256 |
tile size in pixels, a value between 1 and 8192. |
| [options.overlap] | number |
0 |
tile overlap in pixels, a value between 0 and 8192. |
| [options.angle] | number |
0 |
tile angle of rotation, must be a multiple of 90. |
| [options.background] | string | Object |
"{r: 255, g: 255, b: 255, alpha: 1}" |
background colour, parsed by the color module, defaults to white without transparency. |
| [options.depth] | string |
how deep to make the pyramid, possible values are onepixel, onetile or one, default based on layout. |
|
| [options.skipBlanks] | number |
-1 |
Threshold to skip tile generation. Range is 0-255 for 8-bit images, 0-65535 for 16-bit images. Default is 5 for google layout, -1 (no skip) otherwise. |
| [options.container] | string |
"'fs'" |
tile container, with value fs (filesystem) or zip (compressed file). |
| [options.layout] | string |
"'dz'" |
filesystem layout, possible values are dz, iiif, iiif3, zoomify or google. |
| [options.centre] | boolean |
false |
centre image in tile. |
| [options.center] | boolean |
false |
alternative spelling of centre. |
| [options.id] | string |
"'https://example.com/iiif'" |
when layout is iiif/iiif3, sets the @id/id attribute of info.json |
| [options.basename] | string |
the name of the directory within the zip file when container is zip. |
Example
sharp('input.tiff')
.png()
.tile({
size: 512
})
.toFile('output.dz', function(err, info) {
// output.dzi is the Deep Zoom XML definition
// output_files contains 512x512 tiles grouped by zoom level
});Example
const zipFileWithTiles = await sharp(input)
.tile({ basename: "tiles" })
.toBuffer();Example
const iiififier = sharp().tile({ layout: "iiif" });
readableStream
.pipe(iiififier)
.pipe(writeableStream);timeout
timeout(options) ⇒
Sharp
Set a timeout for processing, in seconds.
Use a value of zero to continue processing indefinitely, the default behaviour.
The clock starts when libvips opens an input image for processing.
Time spent waiting for a libuv thread to become available is not included.
Since: 0.29.2
| Param | Type | Description |
|---|---|---|
| options | Object |
|
| options.seconds | number |
Number of seconds after which processing will be stopped |
Example
// Ensure processing takes no longer than 3 seconds
try {
const data = await sharp(input)
.blur(1000)
.timeout({ seconds: 3 })
.toBuffer();
} catch (err) {
if (err.message.includes('timeout')) { ... }
}Src Content Docs Api Resize (`docs/src/content/docs/api-resize.md`)
This file was auto-generated from JSDoc in lib/resize.js
title: Resizing images
resize
resize([width], [height], [options]) ⇒
Sharp
Resize image to width, height or width x height.
When both a width and height are provided, the possible methods by which the image should fit these are:
cover: (default) Preserving aspect ratio, attempt to ensure the image covers both provided dimensions by cropping/clipping to fit.contain: Preserving aspect ratio, contain within both provided dimensions using "letterboxing" where necessary.fill: Ignore the aspect ratio of the input and stretch to both provided dimensions.inside: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified.outside: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified.
Some of these values are based on the object-fit CSS property.
When using a fit of cover or contain, the default position is centre. Other options are:
sharp.position:top,right top,right,right bottom,bottom,left bottom,left,left top.sharp.gravity:north,northeast,east,southeast,south,southwest,west,northwest,centerorcentre.sharp.strategy:coveronly, dynamically crop using either theentropyorattentionstrategy.
Some of these values are based on the object-position CSS property.
The strategy-based approach initially resizes so one dimension is at its target length
then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.
entropy: focus on the region with the highest Shannon entropy.attention: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
Possible downsizing kernels are:
nearest: Use nearest neighbour interpolation.linear: Use a triangle filter.cubic: Use a Catmull-Rom spline.mitchell: Use a Mitchell-Netravali spline.lanczos2: Use a Lanczos kernel witha=2.lanczos3: Use a Lanczos kernel witha=3(the default).mks2013: Use a Magic Kernel Sharp 2013 kernel, as adopted by Facebook.mks2021: Use a Magic Kernel Sharp 2021 kernel, with more accurate (reduced) sharpening than the 2013 version.
When upsampling, these kernels map to nearest, linear and cubic interpolators.
Downsampling kernels without a matching upsampling interpolator map to cubic.
Only one resize can occur per pipeline.
Previous calls to resize in the same pipeline will be ignored.
Throws:
ErrorInvalid parameters
| Param | Type | Default | Description |
|---|---|---|---|
| [width] | number |
How many pixels wide the resultant image should be. Use null or undefined to auto-scale the width to match the height. |
|
| [height] | number |
How many pixels high the resultant image should be. Use null or undefined to auto-scale the height to match the width. |
|
| [options] | Object |
||
| [options.width] | number |
An alternative means of specifying width. If both are present this takes priority. |
|
| [options.height] | number |
An alternative means of specifying height. If both are present this takes priority. |
|
| [options.fit] | String |
'cover' |
How the image should be resized/cropped to fit the target dimension(s), one of cover, contain, fill, inside or outside. |
| [options.position] | String |
'centre' |
A position, gravity or strategy to use when fit is cover or contain. |
| [options.background] | String | Object |
{r: 0, g: 0, b: 0, alpha: 1} |
background colour when fit is contain, parsed by the color module, defaults to black without transparency. |
| [options.kernel] | String |
'lanczos3' |
The kernel to use for image reduction and the inferred interpolator to use for upsampling. Use the fastShrinkOnLoad option to control kernel vs shrink-on-load. |
| [options.withoutEnlargement] | Boolean |
false |
Do not scale up if the width or height are already less than the target dimensions, equivalent to GraphicsMagick's > geometry option. This may result in output dimensions smaller than the target dimensions. |
| [options.withoutReduction] | Boolean |
false |
Do not scale down if the width or height are already greater than the target dimensions, equivalent to GraphicsMagick's < geometry option. This may still result in a crop to reach the target dimensions. |
| [options.fastShrinkOnLoad] | Boolean |
true |
Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern or round-down of an auto-scaled dimension. |
Example
sharp(input)
.resize({ width: 100 })
.toBuffer()
.then(data => {
// 100 pixels wide, auto-scaled height
});Example
sharp(input)
.resize({ height: 100 })
.toBuffer()
.then(data => {
// 100 pixels high, auto-scaled width
});Example
sharp(input)
.resize(200, 300, {
kernel: sharp.kernel.nearest,
fit: 'contain',
position: 'right top',
background: { r: 255, g: 255, b: 255, alpha: 0.5 }
})
.toFile('output.png')
.then(() => {
// output.png is a 200 pixels wide and 300 pixels high image
// containing a nearest-neighbour scaled version
// contained within the north-east corner of a semi-transparent white canvas
});Example
const transformer = sharp()
.resize({
width: 200,
height: 200,
fit: sharp.fit.cover,
position: sharp.strategy.entropy
});
// Read image data from readableStream
// Write 200px square auto-cropped image data to writableStream
readableStream
.pipe(transformer)
.pipe(writableStream);Example
sharp(input)
.resize(200, 200, {
fit: sharp.fit.inside,
withoutEnlargement: true
})
.toFormat('jpeg')
.toBuffer()
.then(function(outputBuffer) {
// outputBuffer contains JPEG image data
// no wider and no higher than 200 pixels
// and no larger than the input image
});Example
sharp(input)
.resize(200, 200, {
fit: sharp.fit.outside,
withoutReduction: true
})
.toFormat('jpeg')
.toBuffer()
.then(function(outputBuffer) {
// outputBuffer contains JPEG image data
// of at least 200 pixels wide and 200 pixels high while maintaining aspect ratio
// and no smaller than the input image
});Example
const scaleByHalf = await sharp(input)
.metadata()
.then(({ width }) => sharp(input)
.resize(Math.round(width * 0.5))
.toBuffer()
);extend
extend(extend) ⇒
Sharp
Extend / pad / extrude one or more edges of the image with either
the provided background colour or pixels derived from the image.
This operation will always occur after resizing and extraction, if any.
Throws:
ErrorInvalid parameters
| Param | Type | Default | Description |
|---|---|---|---|
| extend | number | Object |
single pixel count to add to all edges or an Object with per-edge counts | |
| [extend.top] | number |
0 |
number of pixels to add to the top edge, valid values are integers in the range 0-100000000 |
| [extend.left] | number |
0 |
number of pixels to add to the left edge, valid values are integers in the range 0-100000000 |
| [extend.bottom] | number |
0 |
number of pixels to add to the bottom edge, valid values are integers in the range 0-100000000 |
| [extend.right] | number |
0 |
number of pixels to add to the right edge, valid values are integers in the range 0-100000000 |
| [extend.extendWith] | String |
'background' |
populate new pixels using this method, one of: background, copy, repeat, mirror. |
| [extend.background] | String | Object |
{r: 0, g: 0, b: 0, alpha: 1} |
background colour, parsed by the color module, defaults to black without transparency. |
Example
// Resize to 140 pixels wide, then add 10 transparent pixels
// to the top, left and right edges and 20 to the bottom edge
sharp(input)
.resize(140)
.extend({
top: 10,
bottom: 20,
left: 10,
right: 10,
background: { r: 0, g: 0, b: 0, alpha: 0 }
})
...Example
// Add a row of 10 red pixels to the bottom
sharp(input)
.extend({
bottom: 10,
background: 'red'
})
...Example
// Extrude image by 8 pixels to the right, mirroring existing right hand edge
sharp(input)
.extend({
right: 8,
background: 'mirror'
})
...extract
extract(options) ⇒
Sharp
Extract/crop a region of the image.
- Use
extractbeforeresizefor pre-resize extraction. - Use
extractafterresizefor post-resize extraction. - Use
extracttwice andresizeonce for extract-then-resize-then-extract in a fixed operation order.
Throws:
ErrorInvalid parameters
| Param | Type | Description |
|---|---|---|
| options | Object |
describes the region to extract using integral pixel values |
| options.left | number |
zero-indexed offset from left edge, an integer between 0 and 100000000 |
| options.top | number |
zero-indexed offset from top edge, an integer between 0 and 100000000 |
| options.width | number |
width of region to extract, an integer between 0 and 100000000 |
| options.height | number |
height of region to extract, an integer between 0 and 100000000 |
Example
sharp(input)
.extract({ left: left, top: top, width: width, height: height })
.toFile(output, function(err) {
// Extract a region of the input image, saving in the same format.
});Example
sharp(input)
.extract({ left: leftOffsetPre, top: topOffsetPre, width: widthPre, height: heightPre })
.resize(width, height)
.extract({ left: leftOffsetPost, top: topOffsetPost, width: widthPost, height: heightPost })
.toFile(output, function(err) {
// Extract a region, resize, then extract from the resized image
});trim
trim([options]) ⇒
Sharp
Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.
Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels.
If the result of this operation would trim an image to nothing then no change is made.
Use the lineArt and threshold options for control over sensitivity.
The info response Object will contain trimOffsetLeft and trimOffsetTop properties.
Throws:
ErrorInvalid parameters
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object |
||
| [options.background] | string | Object |
"'top-left pixel'" |
Background colour, parsed by the color module, defaults to that of the top-left pixel. |
| [options.threshold] | number |
10 |
Allowed difference from the above colour, a positive number. |
| [options.lineArt] | boolean |
false |
Does the input more closely resemble line art (e.g. vector) rather than being photographic? |
| [options.margin] | number |
0 |
Leave a margin around trimmed content, integral number of pixels between 0 and 10000000. |
Example
// Trim pixels with a colour similar to that of the top-left pixel.
await sharp(input)
.trim()
.toFile(output);Example
// Trim pixels with the exact same colour as that of the top-left pixel.
await sharp(input)
.trim({
threshold: 0
})
.toFile(output);Example
// Assume input is line art and trim only pixels with a similar colour to red.
const output = await sharp(input)
.trim({
background: "#FF0000",
lineArt: true
})
.toBuffer();Example
// Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
const output = await sharp(input)
.trim({
background: "yellow",
threshold: 42,
})
.toBuffer();Example
// Trim image leaving (up to) a 10 pixel margin around the trimmed content.
const output = await sharp(input)
.trim({
margin: 10
})
.toBuffer();Src Content Docs Api Utility (`docs/src/content/docs/api-utility.md`)
This file was auto-generated from JSDoc in lib/utility.js
title: Global properties
versions
versions
An Object containing the version numbers of sharp, libvips
and (when using prebuilt binaries) its dependencies.
Example
console.log(sharp.versions);interpolators
interpolators :
enum
An Object containing the available interpolators and their proper values
Read only: true
Properties
| Name | Type | Default | Description |
|---|---|---|---|
| nearest | string |
"nearest" |
Nearest neighbour interpolation. Suitable for image enlargement only. |
| bilinear | string |
"bilinear" |
Bilinear interpolation. Faster than bicubic but with less smooth results. |
| bicubic | string |
"bicubic" |
Bicubic interpolation (the default). |
| locallyBoundedBicubic | string |
"lbb" |
LBB interpolation. Prevents some "acutance" but typically reduces performance by a factor of 2. |
| nohalo | string |
"nohalo" |
Nohalo interpolation. Prevents acutance but typically reduces performance by a factor of 3. |
| vertexSplitQuadraticBasisSpline | string |
"vsqbs" |
VSQBS interpolation. Prevents "staircasing" when enlarging. |
format
format ⇒
Object
An Object containing nested boolean values representing the available input and output formats/methods.
Example
console.log(sharp.format);queue
queue
An EventEmitter that emits a change event when a task is either:
- queued, waiting for libuv to provide a worker thread
- complete
Example
sharp.queue.on('change', function(queueLength) {
console.log('Queue contains ' + queueLength + ' task(s)');
});cache
cache([options]) ⇒
Object
Gets or, when options are provided, sets the limits of libvips' operation cache.
Existing entries in the cache will be trimmed after any change in limits.
This method always returns cache statistics,
useful for determining how much working memory is required for a particular task.
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | Object | boolean |
true |
Object with the following attributes, or boolean where true uses default cache settings and false removes all caching |
| [options.memory] | number |
50 |
is the maximum memory in MB to use for this cache |
| [options.files] | number |
20 |
is the maximum number of files to hold open |
| [options.items] | number |
100 |
is the maximum number of operations to cache |
Example
const stats = sharp.cache();Example
sharp.cache( { items: 200 } );
sharp.cache( { files: 0 } );
sharp.cache(false);concurrency
concurrency([concurrency]) ⇒
number
Gets or, when a concurrency is provided, sets
the maximum number of threads libvips should use to process each image.
These are from a thread pool managed by glib,
which helps avoid the overhead of creating new threads.
This method always returns the current concurrency.
The default value is the number of CPU cores,
except when using glibc-based Linux without jemalloc,
where the default is 1 to help reduce memory fragmentation.
A value of 0 will reset this to the number of CPU cores.
Some image format libraries spawn additional threads,
e.g. libaom manages its own 4 threads when encoding AVIF images,
and these are independent of the value set here.
:::note
Further control over performance is available.
:::
Returns: number - concurrency
| Param | Type |
|---|---|
| [concurrency] | number |
Example
const threads = sharp.concurrency(); // 4
sharp.concurrency(2); // 2
sharp.concurrency(0); // 4counters
counters() ⇒
Object
Provides access to internal task counters.
- queue is the number of tasks this module has queued waiting for libuv to provide a worker thread from its pool.
- process is the number of resize tasks currently being processed.
Example
const counters = sharp.counters(); // { queue: 2, process: 4 }simd
simd([simd]) ⇒
boolean
Get and set use of SIMD vector unit instructions.
Requires libvips to have been compiled with highway support.
Improves the performance of resize, blur and sharpen operations
by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.
| Param | Type | Default |
|---|---|---|
| [simd] | boolean |
true |
Example
const simd = sharp.simd();
// simd is `true` if the runtime use of highway is currently enabledExample
const simd = sharp.simd(false);
// prevent libvips from using highway at runtimeblock
block(options)
Block libvips operations at runtime.
This is in addition to the VIPS_BLOCK_UNTRUSTED environment variable,
which when set will block all "untrusted" operations.
Since: 0.32.4
| Param | Type | Description |
|---|---|---|
| options | Object |
|
| options.operation | Array.<string> |
List of libvips low-level operation names to block. |
Example (Block all TIFF input.)
sharp.block({
operation: ['VipsForeignLoadTiff']
});unblock
unblock(options)
Unblock libvips operations at runtime.
This is useful for defining a list of allowed operations.
Since: 0.32.4
| Param | Type | Description |
|---|---|---|
| options | Object |
|
| options.operation | Array.<string> |
List of libvips low-level operation names to unblock. |
Example (Block all input except WebP from the filesystem.)
sharp.block({
operation: ['VipsForeignLoad']
});
sharp.unblock({
operation: ['VipsForeignLoadWebpFile']
});Example (Block all input except JPEG and PNG from a Buffer or Stream.)
sharp.block({
operation: ['VipsForeignLoad']
});
sharp.unblock({
operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer']
});Src Content Docs Install (`docs/src/content/docs/install.md`)
title: Installation
Works with your choice of JavaScript package manager.
:::caution
Please ensure your package manager is configured to install optional dependencies
:::
If a package manager lockfile must support multiple platforms,
please see the cross-platform section
to help decide which package manager is appropriate.
npm install sharppnpm add sharpyarn add sharpbun add sharpdeno add --quiet npm:sharp
deno run --allow-env --allow-ffi --allow-read --allow-sys ...Prerequisites
- Node-API v9 compatible runtime e.g. Node.js >= 20.9.0.
Prebuilt binaries
Ready-compiled sharp and libvips binaries are provided for use on the most common platforms:
- macOS x64 (>= 10.15)
- macOS ARM64
- Linux ARM (glibc >= 2.36)
- Linux ARM64 (glibc >= 2.28, musl >= 1.2.5)
- Linux RISC-V 64-bit (glibc >= 2.41)
- Linux ppc64 (glibc >= 2.36)
- Linux s390x (glibc >= 2.36)
- Linux x64 (glibc >= 2.28, musl >= 1.2.5, CPU with SSE4.2)
- Windows x64
- Windows x86 (deprecated, Node.js 20 only)
- Windows ARM64
- FreeBSD (WebAssembly)
This provides support for the
JPEG, PNG, Ultra HDR, WebP, AVIF, TIFF, GIF and SVG (input) image formats.
Cross-platform
At install time, package managers will automatically select prebuilt binaries
for the current OS platform and CPU architecture, where available.
Some package managers support multiple platforms and architectures
within the same installation tree and/or using the same lockfile.
npm v10+
:::caution
npm package-lock.json files shared by multiple platforms can cause installation problems due to npm bug #4828
:::
Provides limited support via --os, --cpu and --libc flags.
To support macOS with Intel x64 and ARM64 CPUs:
npm install --cpu=x64 --os=darwin sharp
npm install --cpu=arm64 --os=darwin sharpWhen the cross-target is Linux, the C standard library must be specified.
To support glibc (e.g. Debian) and musl (e.g. Alpine) Linux with Intel x64 CPUs:
npm install --cpu=x64 --os=linux --libc=glibc sharp
npm install --cpu=x64 --os=linux --libc=musl sharpyarn v3+
Use the supportedArchitectures configuration.
pnpm v8+
Use the supportedArchitectures configuration.
Custom libvips
To use a custom, globally-installed version of libvips instead of the provided binaries,
make sure it is at least the version listed under config.libvips in the package.json file
and that it can be located using pkg-config --modversion vips-cpp.
For help compiling libvips and its dependencies, please see
building libvips from source.
The use of a globally-installed libvips is unsupported on Windows
and on macOS when running Node.js under Rosetta.
Building from source
npm install sharp
npm explore sharp -- npm run buildThe build process will search for a globally-installed libvips.
This detection logic can be skipped by setting theSHARP_IGNORE_GLOBAL_LIBVIPS (never try to use it) orSHARP_FORCE_GLOBAL_LIBVIPS (always try to use it, even when missing or outdated)
environment variables.
Building from source requires:
- C++17 compiler
- node-addon-api version 7+
- node-gyp version 9+ and its dependencies
If node-addon-api or node-gyp cannot be found, try adding them via:
npm install --save node-addon-api node-gypWebAssembly
Runtime environments that provide multi-threaded Wasm via Workers are supported
by the optional @img/sharp-wasm32 package.
npm install sharp @img/sharp-wasm32- Use in web browsers is unsupported.
- Use in single-threaded environments is unsupported.
- Native text rendering is unsupported.
- Tile-based output is unsupported.
Linux memory allocator
The default memory allocator on most glibc-based Linux systems
(e.g. Debian, Red Hat) is unsuitable for long-running, multi-threaded
processes that involve lots of small memory allocations.
For this reason, by default, sharp will limit the use of thread-based
concurrency when the glibc allocator is
detected at runtime.
To help avoid fragmentation and improve performance on these systems,
the use of an alternative memory allocator such as
jemalloc is recommended.
Those using musl-based Linux (e.g. Alpine) and non-Linux systems are
unaffected.
AWS Lambda
The node_modules directory of the
deployment package
must include binaries for either the linux-x64 or linux-arm64 platforms
depending on the chosen architecture.
When building your deployment package on a machine that differs from the target architecture,
see the cross-platform section to help decide which package manager is appropriate
and how to configure it.
Some package managers use symbolic links
but AWS Lambda does not support these within deployment packages.
An alternative approach is to use a well-maintained, third-party Lambda Layer:
To get the best performance select the largest memory available.
A 1536 MB function provides ~12x more CPU time than a 128 MB function.
When integrating with AWS API Gateway, ensure it is configured with the relevant
binary media types.
Bundlers
webpack
Ensure sharp is excluded from bundling via the
externals
configuration.
externals: {
'sharp': 'commonjs sharp'
}esbuild
Ensure sharp is excluded from bundling via the
external
configuration.
buildSync({
entryPoints: ['app.js'],
bundle: true,
platform: 'node',
external: ['sharp'],
})esbuild app.js --bundle --platform=node --external:sharpFor serverless-esbuild, ensure platform-specific binaries are installed
via the serverless.yml configuration.
custom:
esbuild:
external:
- sharp
packagerOptions:
scripts:
- npm install --os=linux --libc=glibc --cpu=x64 sharpelectron
electron-builder
Ensure sharp is unpacked from the ASAR archive file using the
asarUnpack
option.
{
"build": {
"asar": true,
"asarUnpack": [
"**/node_modules/sharp/**/*",
"**/node_modules/@img/**/*"
]
}
}electron-forge
Ensure sharp is unpacked from the ASAR archive file using the
unpack
option.
{
"packagerConfig": {
"asar": {
"unpack": "**/node_modules/{sharp,@img}/**/*"
}
}
}When using electron-forge with Webpack,
you may also need to add
forge-externals-plugin.
vite
Ensure sharp is excluded from bundling via the
build.rollupOptions
configuration.
import { defineConfig } from 'vite';
export default defineConfig({
build: {
rollupOptions: {
external: [
"sharp"
]
}
}
});TypeScript
TypeScript definitions are published as part of
the sharp package from v0.32.0.
Previously these were available via the @types/sharp package,
which is now deprecated.
When using Typescript, please ensure devDependencies includes
the @types/node package.
Fonts
When creating text images or rendering SVG images that contain text elements,fontconfig is used to find the relevant fonts.
On Windows and macOS systems, all system fonts are available for use.
On macOS systems using Homebrew, you may need to set thePANGOCAIRO_BACKEND environment variable to a value of fontconfig
to ensure it is used for font discovery instead of Core Text.
On Linux systems, fonts that include the relevantfontconfig configuration
when installed via package manager are available for use.
If fontconfig configuration is not found, the following error will occur:
Fontconfig error: Cannot load default config fileIn serverless environments where there is no control over font packages,
use the FONTCONFIG_PATH environment variable to point to a custom location.
Embedded SVG fonts are unsupported.
Known conflicts
Canvas and Windows
If both canvas and sharp modules are used in the same Windows process, the following error may occur:
The specified procedure could not be found.Electron and Linux
Binaries provided by Electron for use on Linux dynamically link against a globally-installed glib
and leak its symbols into the process space, which may cause the following error to occur:
GLib-GObject: g_object_ref: assertion 'G_IS_OBJECT (object)' failed
GLib-GObject: g_object_unref: assertion 'G_IS_OBJECT (object)' failedPlease subscribe to
electron#46323
for updates.
Src Content Docs Performance (`docs/src/content/docs/performance.md`)
title: Performance
Parallelism and concurrency
Node.js uses a libuv-managed thread pool when processing asynchronous calls to native modules such as sharp.
The maximum number of images that sharp can process in parallel is controlled by libuv'sUV_THREADPOOL_SIZE
environment variable, which defaults to 4.
When using more than 4 physical CPU cores, set this environment variable
before the Node.js process starts to increase the thread pool size.
export UV_THREADPOOL_SIZE="$(lscpu -p | egrep -v "^#" | sort -u -t, -k 2,4 | wc -l)"libvips uses a shared thread pool to avoid the overhead of spawning new threads.
The size of this thread pool will grow on demand and shrink when idle.
The default number of threads used to concurrently process each image is the same as the number of CPU cores,
except when using glibc-based Linux without jemalloc or without MALLOC_ARENA_MAX,
where the default is 1 to help reduce memory fragmentation.
Use sharp.concurrency() to manage the number of threads per image.
To reduce memory fragmentation when using the default Linux glibc memory allocator, set theMALLOC_ARENA_MAX
environment variable to either 2 or 4 before the Node.js process starts to reduce the number of memory pools.
export MALLOC_ARENA_MAX="2"Benchmark
A test to benchmark the performance of this module relative to alternatives.
Greater libvips performance can be expected with caching enabled (default)
and using 8+ core machines, especially those with larger L1/L2 CPU caches.
The I/O limits of the relevant (de)compression library will generally determine maximum throughput.
Contenders
- jimp v1.6.1 - Image processing in pure JavaScript.
- imagemagick v0.1.3 - Supports filesystem only and "has been unmaintained for a long time".
- gm v1.25.1 - Fully featured wrapper around GraphicsMagick's
gmcommand line utility, but "has been sunset". - sharp v0.35.0 / libvips v8.18.2 - Caching within libvips disabled to ensure a fair comparison.
Environment
AMD64
- AWS EC2 us-west-2 c8a.xlarge (4x AMD EPYC 9R45)
- Ubuntu 25.10
- Node.js 24.15.0
ARM64
- AWS EC2 us-west-2 c8g.xlarge (4x ARM Graviton4)
- Ubuntu 25.10
- Node.js 24.15.0
Task: JPEG
Decompress a 2725x2225 JPEG image,
resize to 720x588 using Lanczos 3 resampling (where available),
then compress to JPEG at a "quality" setting of 80.
Note: jimp does not support Lanczos 3, bicubic resampling used instead.
Results: JPEG (AMD64)
| Package | I/O | Ops/sec | Speed-up |
|---|---|---|---|
| jimp | buffer | 3.44 | 1.0 |
| jimp | file | 3.65 | 1.1 |
| imagemagick | file | 16.23 | 4.7 |
| gm | buffer | 20.92 | 6.1 |
| gm | file | 21.04 | 6.1 |
| sharp | stream | 82.87 | 24.1 |
| sharp | file | 88.21 | 25.6 |
| sharp | buffer | 89.63 | 26.1 |
Results: JPEG (ARM64)
| Package | I/O | Ops/sec | Speed-up |
|---|---|---|---|
| jimp | buffer | 2.20 | 1.0 |
| jimp | file | 2.45 | 1.1 |
| imagemagick | file | 5.85 | 2.7 |
| gm | file | 13.72 | 6.2 |
| gm | buffer | 13.82 | 6.3 |
| sharp | stream | 49.82 | 22.6 |
| sharp | file | 52.42 | 23.8 |
| sharp | buffer | 53.83 | 24.5 |
Task: PNG
Decompress a 2048x1536 RGBA PNG image,
premultiply the alpha channel,
resize to 720x540 using Lanczos 3 resampling (where available),
unpremultiply then compress as PNG with a "default" zlib compression level of 6
and without adaptive filtering.
Note: jimp does not support premultiply/unpremultiply.
Results: PNG (AMD64)
| Package | I/O | Ops/sec | Speed-up |
|---|---|---|---|
| imagemagick | file | 10.37 | 1.0 |
| gm | file | 13.35 | 1.3 |
| jimp | buffer | 17.04 | 1.6 |
| jimp | file | 17.15 | 1.7 |
| sharp | file | 47.17 | 4.5 |
| sharp | buffer | 47.74 | 4.6 |
Results: PNG (ARM64)
| Package | I/O | Ops/sec | Speed-up |
|---|---|---|---|
| imagemagick | file | 4.39 | 1.0 |
| gm | file | 9.45 | 2.2 |
| jimp | buffer | 10.36 | 2.4 |
| jimp | file | 10.52 | 2.4 |
| sharp | file | 28.04 | 6.4 |
| sharp | buffer | 28.57 | 6.5 |
Running the benchmark test
Requires Docker.
git clone https://github.com/lovell/sharp.git
cd sharp/test/bench
./run-with-docker.shSrc Content Docs Changelog V0.10.0 (`docs/src/content/docs/changelog/v0.10.0.md`)
title: v0.10.0 - 23rd April 2015 slug: changelog/v0.10.0
Add support for Windows (x86).
#19
@DullReferenceException
@itsanandersonAdd support for Openslide input and DeepZoom output.
#146
@mvictorasAllow arbitrary aspect ratios when resizing images via new
ignoreAspectRatiomethod.
#192
@skedastikEnhance output image contrast by stretching its luminance to cover the full dynamic range via new
normalizemethod.
#194
@bkw
@codingforce
Src Content Docs Changelog V0.10.1 (`docs/src/content/docs/changelog/v0.10.1.md`)
title: v0.10.1 - 1st June 2015 slug: changelog/v0.10.1
Allow embed of image with alpha transparency onto non-transparent background.
#204
@mikemliuInclude C standard library for
atoias Xcode 6.3 appears to no longer do this.
#228
@doggan
Src Content Docs Changelog V0.11.0 (`docs/src/content/docs/changelog/v0.11.0.md`)
title: v0.11.0 - 15th July 2015 slug: changelog/v0.11.0
Allow alpha transparency compositing via new
overlayWithmethod.
#97
@gasiExpose raw ICC profile data as a Buffer when using
metadata.
#129
@homerjamAllow image header updates via a parameter passed to existing
withMetadatamethod.
Provide initial support for EXIFOrientationtag,
which if present is now removed when usingrotate,fliporflop.
#189
@h2nonTighten constructor parameter checks.
#221
@mikemorrisAllow one input Stream to be shared with two or more output Streams via new
clonemethod.
#235
@jaubourgUse
roundinstead offloorwhen auto-scaling dimensions to avoid floating-point rounding errors.
#238
@richardadjogah
Src Content Docs Changelog V0.11.1 (`docs/src/content/docs/changelog/v0.11.1.md`)
title: v0.11.1 - 12th August 2015 slug: changelog/v0.11.1
Silence MSVC warning: "C4530: C++ exception handler used, but unwind semantics are not enabled".
#244
@TheThingSuppress gamma correction for input image with alpha transparency.
#249
@compeak
Src Content Docs Changelog V0.11.2 (`docs/src/content/docs/changelog/v0.11.2.md`)
title: v0.11.2 - 28th August 2015 slug: changelog/v0.11.2
- Allow crop gravity to be provided as a String.
#255
@papandreou - Add support for io.js v3 and Node v4.
#246
Src Content Docs Changelog V0.11.3 (`docs/src/content/docs/changelog/v0.11.3.md`)
title: v0.11.3 - 8th September 2015 slug: changelog/v0.11.3
- Interpret blurSigma, sharpenFlat, and sharpenJagged as double precision.
#263
@chrisriley
Src Content Docs Changelog V0.11.4 (`docs/src/content/docs/changelog/v0.11.4.md`)
title: v0.11.4 - 5th November 2015 slug: changelog/v0.11.4
Add corners, e.g.
northeast, to existinggravityoption.
#291
@brandonaaronEnsure correct auto-rotation for EXIF Orientation values 2 and 4.
#288
@brandonaaronMake static linking possible via
--runtime_linkinstall option.
#287
@vlapo
Src Content Docs Changelog V0.12.0 (`docs/src/content/docs/changelog/v0.12.0.md`)
title: v0.12.0 - 23rd November 2015 slug: changelog/v0.12.0
Bundle pre-compiled libvips and its dependencies for 64-bit Linux and Windows.
#42Take advantage of libvips v8.1.0+ features.
#152Add support for 64-bit Windows. Drop support for 32-bit Windows.
#224
@sabrehagenSwitch default interpolator to bicubic.
#289
@mahnunchikPre-extract rotation should not swap width/height.
#296
@asilvasEnsure 16-bit+alpha input images are (un)premultiplied correctly.
#301
@izaakschroederSupport
optionsObject with existingextractoperation.
#309
@papandreou
Src Content Docs Changelog V0.12.1 (`docs/src/content/docs/changelog/v0.12.1.md`)
title: v0.12.1 - 12th December 2015 slug: changelog/v0.12.1
Allow use of SIMD vector instructions (via liborc) to be toggled on/off.
#172
@bkw
@puzrinEnsure embedded ICC profiles output with perceptual intent.
#321
@vlapoUse the NPM-configured HTTPS proxy, if any, for binary downloads.
Src Content Docs Changelog V0.12.2 (`docs/src/content/docs/changelog/v0.12.2.md`)
title: v0.12.2 - 16th January 2016 slug: changelog/v0.12.2
Upgrade libvips to v8.2.0 for improved vips_shrink.
Add pre-compiled libvips for ARMv6+ CPUs.
Ensure 16-bit input images work with embed option.
#325
@janazAllow compilation with gmake to provide FreeBSD support.
#326
@c0decafeAttempt to remove temporary file after installation.
#331
@dtoubelis
Src Content Docs Changelog V0.13.0 (`docs/src/content/docs/changelog/v0.13.0.md`)
title: v0.13.0 - 15th February 2016 slug: changelog/v0.13.0
Improve vector image support by allowing control of density/DPI.
Switch pre-built libs from Imagemagick to Graphicsmagick.
#110
@bradisbellAdd support for raw, uncompressed pixel Buffer/Stream input.
#220
@mikemorrisSwitch from libvips' C to C++ bindings, requires upgrade to v8.2.2.
#299Control number of open files in libvips' cache; breaks existing
cachebehaviour.
#315
@impomeziaEnsure 16-bit input images can be normalised and embedded onto transparent backgrounds.
#339
#340
@janazEnsure selected format takes precedence over any unknown output filename extension.
#344
@ubaltaciAdd support for libvips' PBM, PGM, PPM and FITS image format loaders.
#347
@oaleynikEnsure default crop gravity is center/centre.
#351
@joelmukuthuImprove support for musl libc systems e.g. Alpine Linux.
#354
#359
@download13
@wjordanSmall optimisation when reducing by an integral factor to favour shrink over affine.
Add support for gamma correction of images with an alpha channel.
Src Content Docs Changelog V0.13.1 (`docs/src/content/docs/changelog/v0.13.1.md`)
title: v0.13.1 - 27th February 2016 slug: changelog/v0.13.1
- Fix embedding onto transparent backgrounds; regression introduced in v0.13.0.
#366
@diegocsandrim
Src Content Docs Changelog V0.14.0 (`docs/src/content/docs/changelog/v0.14.0.md`)
title: v0.14.0 - 2nd April 2016 slug: changelog/v0.14.0
Add ability to extend (pad) the edges of an image.
#128
@blowsieAdd support for Zoomify and Google tile layouts. Breaks existing tile API.
#223
@bdunnetteImprovements to overlayWith: differing sizes/formats, gravity, buffer input.
#239
@chrisrileyAdd entropy-based crop strategy to remove least interesting edges.
#295
@rightawayExpose density metadata; set density of images from vector input.
#338
@lookfirstEmit post-processing 'info' event for Stream output.
#367
@salzhraniEnsure output image EXIF Orientation values are within 1-8 range.
#385
@jtobinisaniceguyEnsure ratios are not swapped when rotating 90/270 and ignoring aspect.
#387
@kleisaukeRemove deprecated style of calling extract API. Breaks calls using positional arguments.
#276
Src Content Docs Changelog V0.14.1 (`docs/src/content/docs/changelog/v0.14.1.md`)
title: v0.14.1 - 16th April 2016 slug: changelog/v0.14.1
Allow removal of limitation on input pixel count via limitInputPixels. Use with care.
#250
#316
@anandthakker
@kentongrayUse final output image for metadata passed to callback.
#399
@salzhraniAdd support for writing tiled images to a zip container.
#402
@felixbuenemannImprove Electron compatibility by allowing node-gyp rebuilds without npm.
#412
@nouh
Src Content Docs Changelog V0.15.0 (`docs/src/content/docs/changelog/v0.15.0.md`)
title: v0.15.0 - 21st May 2016 slug: changelog/v0.15.0
Use libvips' new Lanczos 3 kernel as default for image reduction.
Deprecate interpolateWith method, now provided as a resize option.
#310
@jcupittTake advantage of libvips v8.3 features.
Add support for libvips' new GIF and SVG loaders.
Pre-built binaries now include giflib and librsvg, exclude *magick.
Use shrink-on-load for WebP input.
Break existing sharpen API to accept sigma and improve precision.
#369Remove unnecessary (un)premultiply operations when not resizing/compositing.
#413
@jardakotesovec
Src Content Docs Changelog V0.15.1 (`docs/src/content/docs/changelog/v0.15.1.md`)
title: v0.15.1 - 12th July 2016 slug: changelog/v0.15.1
Concat Stream-based input in single operation for ~+3% perf and less GC.
#429
@papandreouAdd alpha channel, if required, before extend operation.
#439
@fruloAllow overlay image to be repeated across entire image via tile option.
#443
@lemnisk8Add cutout option to overlayWith feature, applies only the alpha channel of the overlay image.
#448
@kleisaukeEnsure scaling factors are calculated independently to prevent rounding errors.
#452
@puzrinAdd --sharp-cxx11 flag to compile with gcc's new C++11 ABI.
#456
@kapouerAdd top/left offset support to overlayWith operation.
#473
@rnanwaniAdd convolve operation for kernel-based convolution.
#479
@mhirschAdd greyscale option to threshold operation for colourspace conversion control.
#480
@mhirschEnsure ICC profiles are licenced for distribution.
#486
@kapouerAllow images with an alpha channel to work with LAB-colourspace based sharpen.
#490
@jwagnerAdd trim operation to remove "boring" edges.
#492
@kleisaukeAdd bandbool feature for channel-wise boolean operations.
#496
@mhirschAdd extractChannel operation to extract a channel from an image.
#497
@mhirschAdd ability to read and write native libvips .v files.
#500
@mhirschAdd boolean feature for bitwise image operations.
#501
@mhirsch
Src Content Docs Changelog V0.16.0 (`docs/src/content/docs/changelog/v0.16.0.md`)
title: v0.16.0 - 18th August 2016 slug: changelog/v0.16.0
Add pre-compiled libvips for OS X, ARMv7 and ARMv8.
#312Ensure boolean, bandbool, extractChannel ops occur before sRGB conversion.
#504
@mhirschRecalculate factors after WebP shrink-on-load to avoid round-to-zero errors.
#508
@asilvasPrevent boolean errors during extract operation.
#511
@mhirschAdd joinChannel and toColourspace/toColorspace operations.
#513
@mhirschAdd support for raw pixel data with boolean and withOverlay operations.
#516
@mhirschPrevent bandbool creating a single channel sRGB image.
#519
@mhirschEnsure ICC profiles are removed from PNG output unless withMetadata used.
#521
@ChrisPinewoodAdd alpha channels, if missing, to overlayWith images.
#540
@cmttRemove deprecated interpolateWith method - use resize(w, h, { interpolator: ... })
#310
Src Content Docs Changelog V0.16.1 (`docs/src/content/docs/changelog/v0.16.1.md`)
title: v0.16.1 - 13th October 2016 slug: changelog/v0.16.1
C++11 ABI version is now auto-detected, remove sharp-cxx11 installation flag.
Add experimental 'attention' crop strategy.
#295Include .node extension for Meteor's require() implementation.
#537
@isjackwildEnsure convolution kernel scale is clamped to a minimum value of 1.
#561
@abagshawCorrect calculation of y-axis placement when overlaying image at a fixed point.
#566
@Nateowami
Src Content Docs Changelog V0.16.2 (`docs/src/content/docs/changelog/v0.16.2.md`)
title: v0.16.2 - 22nd October 2016 slug: changelog/v0.16.2
Src Content Docs Changelog V0.17.0 (`docs/src/content/docs/changelog/v0.17.0.md`)
title: v0.17.0 - 11th December 2016 slug: changelog/v0.17.0
Drop support for versions of Node prior to v4.
Deprecate the following output format "option" functions:
quality, progressive, compressionLevel, withoutAdaptiveFiltering,
withoutChromaSubsampling, trellisQuantisation, trellisQuantization,
overshootDeringing, optimiseScans and optimizeScans.
Access to these is now via output format functions, for examplequality(n)
is nowjpeg({quality: n})and/orwebp({quality: n}).Auto-convert GIF and SVG input to PNG output if no other format is specified.
Expose libvips' "centre" resize option to mimic *magick's +0.5px convention.
#568Ensure support for embedded base64 PNG and JPEG images within an SVG.
#601
@dynamite-readyEnsure premultiply operation occurs before box filter shrink.
#605
@CmdrShepardsPie
@teroparvinenAdd support for PNG and WebP tile-based output formats (in addition to JPEG).
#622
@ppaskarisAllow use of extend with greyscale input.
#623
@ppaskarisAllow non-RGB input to embed/extend onto background with an alpha channel.
#646
@DaGaMs
Src Content Docs Changelog V0.17.1 (`docs/src/content/docs/changelog/v0.17.1.md`)
title: v0.17.1 - 15th January 2017 slug: changelog/v0.17.1
Simplify expression for finding vips-cpp libdir.
#656Allow HTTPS-over-HTTP proxy when downloading pre-compiled dependencies.
@wangzhiwei1888
#679
Src Content Docs Changelog V0.17.2 (`docs/src/content/docs/changelog/v0.17.2.md`)
title: v0.17.2 - 11th February 2017 slug: changelog/v0.17.2
Ensure Readable side of Stream can start flowing after Writable side has finished.
#671
@danhallerExpose WebP alpha quality, lossless and near-lossless output options.
#685
@rnanwani
Src Content Docs Changelog V0.17.3 (`docs/src/content/docs/changelog/v0.17.3.md`)
title: v0.17.3 - 1st April 2017 slug: changelog/v0.17.3
Allow toBuffer to optionally resolve a Promise with both info and data.
#143
@salzhraniCreate blank image of given width, height, channels and background.
#470
@pjartsAdd support for the "nearest" kernel for image reductions.
#732
@alice0metaAdd support for TIFF compression and predictor options.
#738
@kristojorg
Src Content Docs Changelog V0.18.0 (`docs/src/content/docs/changelog/v0.18.0.md`)
title: v0.18.0 - 30th May 2017 slug: changelog/v0.18.0
Remove the previously-deprecated output format "option" functions:
quality, progressive, compressionLevel, withoutAdaptiveFiltering,
withoutChromaSubsampling, trellisQuantisation, trellisQuantization,
overshootDeringing, optimiseScans and optimizeScans.Ensure maximum output dimensions are based on the format to be used.
#176
@stephanebachelierAvoid costly (un)premultiply when using overlayWith without alpha channel.
#573
@strarsisInclude pixel depth (e.g. "uchar") when reading metadata.
#577
@moedusaAdd support for Buffer and Stream-based TIFF output.
#587
@strarsisExpose warnings from libvips via NODE_DEBUG=sharp environment variable.
#607
@puzrinSwitch to the libvips implementation of "attention" and "entropy" crop strategies.
#727Improve performance and accuracy of nearest neighbour integral upsampling.
#752
@MrIbbyConstructor single argument API: allow plain object, reject null/undefined.
#768
@kub1xEnsure ARM64 pre-built binaries use correct C++11 ABI version.
#772
@ajiratech2Prevent aliasing by using dynamic values for shrink(-on-load).
#781
@kleisaukeExpose libvips' "squash" parameter to enable 1-bit TIFF output.
#783
@YvesBosAdd support for rotation using any multiple of +/-90 degrees.
#791
@ncodenAdd "jpg" alias to toFormat as shortened form of "jpeg".
#814
@jingsam
Src Content Docs Changelog V0.18.1 (`docs/src/content/docs/changelog/v0.18.1.md`)
title: v0.18.1 - 30th May 2017 slug: changelog/v0.18.1
Src Content Docs Changelog V0.18.2 (`docs/src/content/docs/changelog/v0.18.2.md`)
title: v0.18.2 - 1st July 2017 slug: changelog/v0.18.2
Expose libvips' xres and yres properties for TIFF output.
#828
@YvesBosEnsure flip and flop operations work with auto-rotate.
#837
@rexxarsAllow binary download URL override via SHARP_DIST_BASE_URL env variable.
#841Add support for Solus Linux.
#857
@ekremkaraca
Src Content Docs Changelog V0.18.3 (`docs/src/content/docs/changelog/v0.18.3.md`)
title: v0.18.3 - 13th September 2017 slug: changelog/v0.18.3
Skip shrink-on-load when trimming.
#888
@kleisaukeMigrate from got to simple-get for basic auth support.
#945
@pbomb
Src Content Docs Changelog V0.18.4 (`docs/src/content/docs/changelog/v0.18.4.md`)
title: v0.18.4 - 18th September 2017 slug: changelog/v0.18.4
- Ensure input Buffer really is marked as Persistent, prevents mark-sweep GC.
#950
@lfdoherty
Src Content Docs Changelog V0.19.0 (`docs/src/content/docs/changelog/v0.19.0.md`)
title: v0.19.0 - 11th January 2018 slug: changelog/v0.19.0
Expose offset coordinates of strategy-based crop.
#868
@mirohristov-comPNG output now defaults to adaptiveFiltering=false, compressionLevel=9
#872
@wmertensAdd stats feature for pixel-derived image statistics.
#915
@rnanwaniAdd failOnError option to fail-fast on bad input image data.
#976
@mceachenResize: switch to libvips' implementation, make fastShrinkOnLoad optional, remove interpolator and centreSampling options.
#977
@jardakotesovecAttach finish event listener to a clone only for Stream-based input.
#995
@whmountainsAdd tilecache before smartcrop to avoid over-computation of previous operations.
#1028
@coffeebitePrevent toFile extension taking precedence over requested format.
#1037
@tomgallagherAdd support for gravity option to existing embed feature.
#1038
@AzureByteTIFF output: switch default predictor from 'none' to 'horizontal' to match libvips' behaviour.
Src Content Docs Changelog V0.19.1 (`docs/src/content/docs/changelog/v0.19.1.md`)
title: v0.19.1 - 24th February 2018 slug: changelog/v0.19.1
Src Content Docs Changelog V0.20.0 (`docs/src/content/docs/changelog/v0.20.0.md`)
title: v0.20.0 - 5th March 2018 slug: changelog/v0.20.0
- Add support for prebuilt sharp binaries on common platforms.
#186
Src Content Docs Changelog V0.20.1 (`docs/src/content/docs/changelog/v0.20.1.md`)
title: v0.20.1 - 17th March 2018 slug: changelog/v0.20.1
Improve installation experience when a globally-installed libvips below the minimum required version is found.
#1148Prevent smartcrop error when cumulative rounding is below target size.
#1154
@ralrom
Src Content Docs Changelog V0.20.2 (`docs/src/content/docs/changelog/v0.20.2.md`)
title: v0.20.2 - 28th April 2018 slug: changelog/v0.20.2
Add environment variable to ignore globally-installed libvips.
#1165
@oncletomAdd support for page selection with multi-page input (GIF/TIFF).
#1204
@woolite64Add support for Group4 (CCITTFAX4) compression with TIFF output.
#1208
@woolite64
Src Content Docs Changelog V0.20.3 (`docs/src/content/docs/changelog/v0.20.3.md`)
title: v0.20.3 - 29th May 2018 slug: changelog/v0.20.3
Src Content Docs Changelog V0.20.4 (`docs/src/content/docs/changelog/v0.20.4.md`)
title: v0.20.4 - 20th June 2018 slug: changelog/v0.20.4
Prevent possible rounding error when using shrink-on-load and 90/270 degree rotation.
#1241
@anahit42Ensure extractChannel sets correct single-channel colour space interpretation.
#1257
@jeremychone
Src Content Docs Changelog V0.20.5 (`docs/src/content/docs/changelog/v0.20.5.md`)
title: v0.20.5 - 27th June 2018 slug: changelog/v0.20.5
- Expose libjpeg optimize_coding flag.
#1265
@tomlokhorst
Src Content Docs Changelog V0.20.6 (`docs/src/content/docs/changelog/v0.20.6.md`)
title: v0.20.6 - 20th August 2018 slug: changelog/v0.20.6
Add removeAlpha operation to remove alpha channel, if any.
#1248Allow full WebP alphaQuality range of 0-100.
#1290
@sylvaindumontCache libvips binaries to reduce re-install time.
#1301Ensure vendor platform mismatch throws error at install time.
#1303Improve install time error messages for FreeBSD users.
#1310Ensure extractChannel works with 16-bit images.
#1330Expose depth option for tile-based output.
#1342
@alundaviesAdd experimental entropy field to stats response.
Src Content Docs Changelog V0.20.7 (`docs/src/content/docs/changelog/v0.20.7.md`)
title: v0.20.7 - 21st August 2018 slug: changelog/v0.20.7
- Use copy+unlink if rename operation fails during installation.
#1345
Src Content Docs Changelog V0.20.8 (`docs/src/content/docs/changelog/v0.20.8.md`)
title: v0.20.8 - 5th September 2018 slug: changelog/v0.20.8
Avoid race conditions when creating directories during installation.
#1358
@ajhoolAccept floating point values for input density parameter.
#1362
@aeirola
Src Content Docs Changelog V0.21.0 (`docs/src/content/docs/changelog/v0.21.0.md`)
title: v0.21.0 - 4th October 2018 slug: changelog/v0.21.0
Deprecate the following resize-related functions:
crop,embed,ignoreAspectRatio,max,minandwithoutEnlargement.
Access to these is now via options passed to theresizefunction.
For example:
embed('north')is nowresize(width, height, { fit: 'contain', position: 'north' }),
crop('attention')is nowresize(width, height, { fit: 'cover', position: 'attention' }),
max().withoutEnlargement()is nowresize(width, height, { fit: 'inside', withoutEnlargement: true }).
#1135Deprecate the
backgroundfunction.
Per-operationbackgroundoptions added toresize,extendandflattenoperations.
#1392Add
sizetometadataresponse (Stream and Buffer input only).
#695Switch from custom trim operation to
vips_find_trim.
#914Add
chromaSubsamplingandisProgressiveproperties tometadataresponse.
#1186Drop Node 4 support.
#1212Enable SIMD convolution by default.
#1213Add experimental prebuilt binaries for musl-based Linux.
#1379Add support for arbitrary rotation angle via vips_rotate.
#1385
@freezy
Src Content Docs Changelog V0.21.1 (`docs/src/content/docs/changelog/v0.21.1.md`)
title: v0.21.1 - 7th December 2018 slug: changelog/v0.21.1
Install: support
sharp_dist_base_urlnpm config, like existingSHARP_DIST_BASE_URL.
#1422
@SethWenEnsure
channelmetadata is correct for raw, greyscale output.
#1425Add support for the "mitchell" kernel for image reductions.
#1438
@DaizAllow separate parameters for gamma encoding and decoding.
#1439
@DaizBuild prototype with
Object.assignto allow minification.
#1475
@jaubourgExpose libvips' recombination matrix operation.
#1477
@fromkeithExpose libvips' pyramid/tile options for TIFF output.
#1483
@mbklein
Src Content Docs Changelog V0.21.2 (`docs/src/content/docs/changelog/v0.21.2.md`)
title: v0.21.2 - 13th January 2019 slug: changelog/v0.21.2
Ensure all metadata is removed from PNG output unless
withMetadataused.Ensure shortest edge is at least one pixel after resizing.
#1003Add
ensureAlphaoperation to add an alpha channel, if missing.
#1153Expose
pagesandpageHeightmetadata for multi-page input images.
#1205Expose PNG output options requiring libimagequant.
#1484Expose underlying error message for invalid input.
#1505Prevent mutation of options passed to
jpeg.
#1516Ensure forced output format applied correctly when output chaining.
#1528
Src Content Docs Changelog V0.21.3 (`docs/src/content/docs/changelog/v0.21.3.md`)
title: v0.21.3 - 19th January 2019 slug: changelog/v0.21.3
Input image decoding now fails fast, set
failOnErrorto change this behaviour.Failed filesystem-based input now separates missing file and invalid format errors.
#1542
Src Content Docs Changelog V0.22.0 (`docs/src/content/docs/changelog/v0.22.0.md`)
title: v0.22.0 - 18th March 2019 slug: changelog/v0.22.0
Remove functions previously deprecated in v0.21.0:
background,crop,embed,ignoreAspectRatio,max,minandwithoutEnlargement.Add
compositeoperation supporting multiple images and blend modes; deprecateoverlayWith.
#728Add support for
pagesinput option for multi-page input.
#1566Allow Stream-based input of raw pixel data.
#1579Add support for
pageinput option to GIF and PDF.
#1595
@ramiel
Src Content Docs Changelog V0.22.1 (`docs/src/content/docs/changelog/v0.22.1.md`)
title: v0.22.1 - 25th April 2019 slug: changelog/v0.22.1
Add
modulateoperation for brightness, saturation and hue.
#1601
@GouesImprove help messaging should
require("sharp")fail.
#1638
@sidharthachatterjeeAdd support for Node 12.
#1668
Src Content Docs Changelog V0.23.0 (`docs/src/content/docs/changelog/v0.23.0.md`)
title: v0.23.0 - 29th July 2019 slug: changelog/v0.23.0
Remove
overlayWithpreviously deprecated in v0.22.0.Add experimental support for HEIF images. Requires libvips compiled with libheif.
#1105Expose libwebp
smartSubsampleandreductionEffortoptions.
#1545Add experimental support for Worker Threads.
#1558Use libvips' built-in CMYK and sRGB profiles when required.
#1619Drop support for Node.js versions 6 and 11.
#1674Expose
skipBlanksoption for tile-based output.
#1687
@RaboliotTheGreyAllow use of
failOnErroroption with Stream-based input.
#1691
Src Content Docs Changelog V0.23.1 (`docs/src/content/docs/changelog/v0.23.1.md`)
title: v0.23.1 - 26th September 2019 slug: changelog/v0.23.1
Ensure
sharp.format.vipsis present and correct (filesystem only).
#1813Ensure invalid
widthandheightprovided as options toresizethrow.
#1817Allow use of 'heic' and 'heif' identifiers with
toFormat.
#1834
@jaubourgAdd
premultipliedoption tocompositeoperation.
#1835
@AndargorAllow instance reuse with differing
toBufferoptions.
#1860
@RaboliotTheGreyEnsure image is at least 3x3 pixels before attempting trim operation.
Src Content Docs Changelog V0.23.2 (`docs/src/content/docs/changelog/v0.23.2.md`)
title: v0.23.2 - 28th October 2019 slug: changelog/v0.23.2
Add support for Node.js 13.
#1932
@MayhemYDG
Src Content Docs Changelog V0.23.3 (`docs/src/content/docs/changelog/v0.23.3.md`)
title: v0.23.3 - 17th November 2019 slug: changelog/v0.23.3
Ensure
trimoperation supports images contained in the alpha channel.
#1597Ensure tile
overlapoption works as expected.
#1921
@rustygutsAllow compilation on FreeBSD and variants (broken since v0.23.0)
#1952
@pouya-eghbaliEnsure
modulateand other colour-based operations can co-exist.
#1958
Src Content Docs Changelog V0.23.4 (`docs/src/content/docs/changelog/v0.23.4.md`)
title: v0.23.4 - 5th December 2019 slug: changelog/v0.23.4
Handle zero-length Buffer objects when using Node.js v13.2.0+.
Expose raw TIFFTAG_PHOTOSHOP metadata.
#1600Improve thread safety by using copy-on-write when updating metadata.
#1986
Src Content Docs Changelog V0.24.0 (`docs/src/content/docs/changelog/v0.24.0.md`)
title: v0.24.0 - 16th January 2020 slug: changelog/v0.24.0
Drop support for Node.js 8.
#1910Drop support for undefined input where options also provided.
#1768Move
limitInputPixelsandsequentialReadto input options, deprecating functions of the same name.Expose
delayandloopmetadata for animated images.
#1905Ensure correct colour output for 16-bit, 2-channel PNG input with ICC profile.
#2013Prevent use of sequentialRead for rotate operations.
#2016Correctly bind max width and height values when using withoutEnlargement.
#2024
@BrychanOdlumAdd support for input with 16-bit RGB profile.
#2037
Src Content Docs Changelog V0.24.1 (`docs/src/content/docs/changelog/v0.24.1.md`)
title: v0.24.1 - 15th February 2020 slug: changelog/v0.24.1
Prevent use of sequentialRead for EXIF-based rotate operation.
#2042Ensure RGBA LZW TIFF returns correct channel count.
#2064
Src Content Docs Changelog V0.25.0 (`docs/src/content/docs/changelog/v0.25.0.md`)
title: v0.25.0 - 7th March 2020 slug: changelog/v0.25.0
Remove
limitInputPixelsandsequentialReadpreviously deprecated in v0.24.0.Migrate internals to N-API.
#1282Add support for 32-bit Windows.
#2088Ensure correct ordering of rotate-then-trim operations.
#2087Ensure composite accepts
limitInputPixelsandsequentialReadinput options.
#2099
Src Content Docs Changelog V0.25.1 (`docs/src/content/docs/changelog/v0.25.1.md`)
title: v0.25.1 - 7th March 2020 slug: changelog/v0.25.1
- Ensure prebuilt binaries are fetched based on N-API version.
#2117
Src Content Docs Changelog V0.25.2 (`docs/src/content/docs/changelog/v0.25.2.md`)
title: v0.25.2 - 20th March 2020 slug: changelog/v0.25.2
Provide prebuilt binaries for Linux ARM64v8.
Ensure input options are consistently and correctly detected.
#2118Ensure N-API prebuilt binaries work on RHEL7 and its derivatives.
#2119Ensure AsyncWorker options are persisted.
#2130
Src Content Docs Changelog V0.25.3 (`docs/src/content/docs/changelog/v0.25.3.md`)
title: v0.25.3 - 17th May 2020 slug: changelog/v0.25.3
Ensure libvips is initialised only once, improves worker thread safety.
#2143Ensure npm platform flag is respected when copying DLLs.
#2188
@dimadeveatiiAllow SVG input with large inline images to be parsed.
#2195
Src Content Docs Changelog V0.25.4 (`docs/src/content/docs/changelog/v0.25.4.md`)
title: v0.25.4 - 12th June 2020 slug: changelog/v0.25.4
Allow libvips binary location override where version is appended.
#2217
@malice00Enable PNG palette when setting quality, colours, colors or dither.
#2226
@romaleevAdd
levelconstructor option to use a specific level of a multi-level image.
Exposelevelsmetadata for multi-level images.
#2222Add support for named
alphachannel toextractChanneloperation.
#2138Add experimental
sharpnesscalculation tostats()response.
#2251Emit
warningevent for non-critical processing problems.
#2032
Src Content Docs Changelog V0.26.0 (`docs/src/content/docs/changelog/v0.26.0.md`)
title: v0.26.0 - 25th August 2020 slug: changelog/v0.26.0
Prebuilt libvips binaries are now statically-linked and Brotli-compressed, requiring Node.js 10.16.0+.
TIFF output
squashis replaced bybitdepthto reduce to 1, 2 or 4 bit.JPEG output
quality>= 90 no longer automatically setschromaSubsamplingto4:4:4.Add most
dominantcolour to imagestats.
#640Add support for animated GIF (requires *magick) and WebP output.
#2012
@deftomatAdd support for libvips ImageMagick v7 loaders.
#2258
@vouillonAdd support to
withMetadatafor custom ICC profile.
#2271
@roborourkeEnsure prebuilt binaries for ARM default to v7 when using Electron.
#2292
@diegodev3
Src Content Docs Changelog V0.26.1 (`docs/src/content/docs/changelog/v0.26.1.md`)
title: v0.26.1 - 20th September 2020 slug: changelog/v0.26.1
Ensure correct pageHeight when verifying multi-page image dimensions.
#2343
@deromAllow input density range up to 100000 DPI.
#2348
@stefanprobstEnsure animation-related properties can be set for Stream-based input.
#2369
@AcrylicShrimpEnsure
statscan be calculated for 1x1 input.
#2372Ensure animated GIF output is optimised.
#2376
Src Content Docs Changelog V0.26.2 (`docs/src/content/docs/changelog/v0.26.2.md`)
title: v0.26.2 - 14th October 2020 slug: changelog/v0.26.2
Add support for EXR input. Requires libvips compiled with OpenEXR.
#698
Src Content Docs Changelog V0.26.3 (`docs/src/content/docs/changelog/v0.26.3.md`)
title: v0.26.3 - 16th November 2020 slug: changelog/v0.26.3
Src Content Docs Changelog V0.27.0 (`docs/src/content/docs/changelog/v0.27.0.md`)
title: v0.27.0 - 22nd December 2020 slug: changelog/v0.27.0
Add support for AVIF to prebuilt binaries.
Remove experimental status from
heifoutput, defaults are now AVIF-centric.Allow negative top/left offsets for composite operation.
#2391
@CurosMJEnsure all platforms use fontconfig for font rendering.
#2399
Src Content Docs Changelog V0.27.1 (`docs/src/content/docs/changelog/v0.27.1.md`)
title: v0.27.1 - 27th January 2021 slug: changelog/v0.27.1
Ensure TIFF is cast when using float predictor.
#2502
@randyridgeAdd support for Uint8Array and Uint8ClampedArray input.
#2511
@leonRevert: ensure all platforms use fontconfig for font rendering.
#2515Expose libvips gaussnoise operation to allow creation of Gaussian noise.
#2527
@alza54
Src Content Docs Changelog V0.27.2 (`docs/src/content/docs/changelog/v0.27.2.md`)
title: v0.27.2 - 22nd February 2021 slug: changelog/v0.27.2
macOS: Prevent use of globally-installed ARM64 libvips with Rosetta x64 emulation.
#2460Linux (musl): Prevent use of prebuilt linuxmusl-x64 binaries with musl >= 1.2.0.
#2570Improve 16-bit grey+alpha support by using libvips'
has_alphadetection.
#2569Allow the use of non lower case extensions with
toFormat.
#2581
@florian-buschAllow use of
recomboperation with single channel input.
#2584
Src Content Docs Changelog V0.28.0 (`docs/src/content/docs/changelog/v0.28.0.md`)
title: v0.28.0 - 29th March 2021 slug: changelog/v0.28.0
Prebuilt binaries now include mozjpeg and libimagequant (BSD 2-Clause).
Prebuilt binaries limit AVIF support to the most common 8-bit depth.
Add
mozjpegoption tojpegmethod, sets mozjpeg defaults.Reduce the default PNG
compressionLevelto the more commonly used 6.Reduce concurrency on glibc-based Linux when using the default memory allocator to help prevent fragmentation.
Default missing edge properties of extend operation to zero.
#2578Ensure composite does not clip top and left offsets.
#2594
@SHG42Improve error handling of network failure at install time.
#2608
@abradleyEnsure
@idattribute can be set for IIIF tile-based output.
#2612
@edsilvEnsure composite replicates the correct number of tiles for centred gravities.
#2626
Src Content Docs Changelog V0.28.1 (`docs/src/content/docs/changelog/v0.28.1.md`)
title: v0.28.1 - 5th April 2021 slug: changelog/v0.28.1
Ensure all installation errors are logged with a more obvious prefix.
Allow
withMetadatato set and update EXIF metadata.
#650Add support for OME-TIFF Sub Image File Directories (subIFD).
#2557Allow
ensureAlphato set the alpha transparency level.
#2634
Src Content Docs Changelog V0.28.2 (`docs/src/content/docs/changelog/v0.28.2.md`)
title: v0.28.2 - 10th May 2021 slug: changelog/v0.28.2
Allow
withMetadatato setdensity.
#967Skip shrink-on-load where one dimension <4px.
#2653Allow escaped proxy credentials.
#2664
@msalettesDetect empty input and throw a helpful error.
#2687
@JakobJingleheimerAdd install-time flag to skip version compatibility checks.
#2692
@xemle
Src Content Docs Changelog V0.28.3 (`docs/src/content/docs/changelog/v0.28.3.md`)
title: v0.28.3 - 24th May 2021 slug: changelog/v0.28.3
Ensure presence of libvips, vendored or global, before invoking node-gyp.
Skip shrink-on-load for multi-page WebP.
#2714Add contrast limiting adaptive histogram equalization (CLAHE) operator.
#2726
@baparham
Src Content Docs Changelog V0.29.0 (`docs/src/content/docs/changelog/v0.29.0.md`)
title: v0.29.0 - 17th August 2021 slug: changelog/v0.29.0
Drop support for Node.js 10, now requires Node.js >= 12.13.0.
Add
backgroundproperty to PNG and GIF image metadata.Add
compressionproperty to HEIF image metadata.
#2504AVIF encoding now defaults to
4:4:4chroma subsampling.
#2562Allow multiple platform-arch binaries in same
node_modulesinstallation tree.
#2575Default to single-channel
b-wspace whenextractChannelis used.
#2658Allow installation directory to contain spaces (regression in v0.26.0).
#2777Add
pipelineColourspaceoperator to set the processing space.
#2704
@DaizAllow bit depth to be set when using raw input and output.
#2762
@mart-jansinkAllow
negateto act only on non-alpha channels.
#2808
@rexxars
Src Content Docs Changelog V0.29.1 (`docs/src/content/docs/changelog/v0.29.1.md`)
title: v0.29.1 - 7th September 2021 slug: changelog/v0.29.1
Add
lightnessoption tomodulateoperation.
#2846Ensure correct PNG bitdepth is set based on number of colours.
#2855Ensure background is always premultiplied when compositing.
#2858Ensure images with P3 profiles retain full gamut.
#2862Add support for libvips compiled with OpenJPEG.
#2868Remove unsupported animation properties from AVIF output.
#2870Resolve paths before comparing input/output filenames.
#2878
@rexxarsAllow use of speed 9 (fastest) for HEIF encoding.
#2879
@rexxars
Src Content Docs Changelog V0.29.2 (`docs/src/content/docs/changelog/v0.29.2.md`)
title: v0.29.2 - 21st October 2021 slug: changelog/v0.29.2
Add
timeoutfunction to limit processing time.Ensure
sharp.versionsis populated from vendored libvips.Remove animation properties from single page images.
#2890Improve error message on Windows for version conflict.
#2918
@dkrnlThrow error rather than exit when invalid binaries detected.
#2931
Src Content Docs Changelog V0.29.3 (`docs/src/content/docs/changelog/v0.29.3.md`)
title: v0.29.3 - 14th November 2021 slug: changelog/v0.29.3
Ensure correct dimensions when containing image resized to 1px.
#2951Impute TIFF
xres/yresfromdensityprovided towithMetadata.
#2952
@mbklein
Src Content Docs Changelog V0.30.0 (`docs/src/content/docs/changelog/v0.30.0.md`)
title: v0.30.0 - 1st February 2022 slug: changelog/v0.30.0
Add support for GIF output to prebuilt binaries.
Reduce minimum Linux ARM64v8 glibc requirement to 2.17.
Verify prebuilt binaries with a Subresource Integrity check.
Standardise WebP
effortoption name, deprecatereductionEffort.Standardise HEIF
effortoption name, deprecatespeed.Add support for IIIF v3 tile-based output.
Expose control over CPU effort for palette-based PNG output.
#2541Improve animated (multi-page) image resize and extract.
#2789
@kleisaukeExpose platform and architecture of vendored binaries as
sharp.vendor.
#2928Properly emit close events for duplex streams.
#2976
@driannaudeExpose
unlimitedoption for SVG and PNG input, switches off safety features.
#2984Add
withoutReductionoption to resize operation.
#3006
@christopherbradleybanksAdd
resolutionUnitastiffoption and expose in metadata.
#3023
@ompal-sisodiyaEnsure rotate-then-extract works with EXIF mirroring.
#3024
Src Content Docs Changelog V0.30.1 (`docs/src/content/docs/changelog/v0.30.1.md`)
title: v0.30.1 - 9th February 2022 slug: changelog/v0.30.1
Allow use of
toBufferandtoFileon the same instance.
#3044Skip shrink-on-load for known libjpeg rounding errors.
#3066
@kleisaukeEnsure withoutReduction does not interfere with contain/crop/embed.
#3081
@kleisaukeEnsure affine interpolator is correctly finalised.
#3083
@kleisauke
Src Content Docs Changelog V0.30.2 (`docs/src/content/docs/changelog/v0.30.2.md`)
title: v0.30.2 - 2nd March 2022 slug: changelog/v0.30.2
Improve performance and accuracy when compositing multiple images.
#2286Expand pkgconfig search path for wider BSD support.
#3106Ensure Windows C++ runtime is linked statically (regression in 0.30.0).
#3110
@kleisaukeTemporarily ignore greyscale ICC profiles to workaround lcms bug.
#3112
Src Content Docs Changelog V0.30.3 (`docs/src/content/docs/changelog/v0.30.3.md`)
title: v0.30.3 - 14th March 2022 slug: changelog/v0.30.3
Allow
sharpenoptions to be provided more consistently as an Object.
#2561Expose
x1,y2andy3parameters ofsharpenoperation.
#2935Prevent double unpremultiply with some composite blend modes (regression in 0.30.2).
#3118
Src Content Docs Changelog V0.30.4 (`docs/src/content/docs/changelog/v0.30.4.md`)
title: v0.30.4 - 18th April 2022 slug: changelog/v0.30.4
Increase control over sensitivity to invalid images via
failOn, deprecatefailOnError(equivalent tofailOn: 'warning').Ensure
createinput image has correct bit depth and colour space.
#3139Add support for
TypedArrayinput withbyteOffsetandlength.
#3146
@codepage949Improve error message when attempting to render SVG input greater than 32767x32767.
#3167Add missing file name to 'Input file is missing' error message.
#3178
@Brodan
Src Content Docs Changelog V0.30.5 (`docs/src/content/docs/changelog/v0.30.5.md`)
title: v0.30.5 - 23rd May 2022 slug: changelog/v0.30.5
Install: pass
PKG_CONFIG_PATHvia env rather than substitution.
@dwisiswant0Add support for
--libcflag to improve cross-platform installation.
#3160
@joonamoAllow installation of prebuilt libvips binaries from filesystem.
#3196
@ankurpariharFix rotate-then-extract for EXIF orientation 2.
#3218
@jakob0fischl
Src Content Docs Changelog V0.30.6 (`docs/src/content/docs/changelog/v0.30.6.md`)
title: v0.30.6 - 30th May 2022 slug: changelog/v0.30.6
Allow values for
limitInputPixelslarger than 32-bit.
#3238Ensure brew-installed
vipscan be detected (regression in 0.30.5).
#3239
Src Content Docs Changelog V0.30.7 (`docs/src/content/docs/changelog/v0.30.7.md`)
title: v0.30.7 - 22nd June 2022 slug: changelog/v0.30.7
Ensure tiled composition always works with outside resizing.
#3227Allow WebP encoding effort of 0.
#3261
@AlexanderTheGrey
Src Content Docs Changelog V0.31.0 (`docs/src/content/docs/changelog/v0.31.0.md`)
title: v0.31.0 - 5th September 2022 slug: changelog/v0.31.0
Drop support for Node.js 12, now requires Node.js >= 14.15.0.
GIF output now re-uses input palette if possible. Use
reoptimiseoption to generate a new palette.Add WebP
minSizeandmixedoptions for greater control over animation frames.Remove previously-deprecated WebP
reductionEffortand HEIFspeedoptions. Useeffortto control these.The
flipandflopoperations will now occur before therotateoperation.Improve
normaliseoperation with use of histogram.
#200Use combined bounding box of alpha and non-alpha channels for
trimoperation.
#2166Add Buffer and Stream support to tile-based output.
#2238Add input
fileSuffixand outputaliastoformatinformation.
#2642Re-introduce support for greyscale ICC profiles (temporarily removed in 0.30.2).
#3114Add support for WebP and PackBits
compressionoptions with TIFF output.
#3198Ensure OpenSlide and FITS input works with custom libvips.
#3226Ensure
trimoperation is a no-op when it would reduce an image to nothing.
#3223Expose
vips_textto create an image containing rendered text.
#3252
@brahimaEnsure only properties owned by the
withMetadataEXIF Object are parsed.
#3292Expand
linearoperation to allow use of per-channel arrays.
#3303
@antonmarsdenEnsure the order of
rotate,resizeandextendoperations is respected where possible.
Emit warnings when previous calls in the same pipeline will be ignored.
#3319Ensure PNG bitdepth can be set for non-palette output.
#3322Add trim option to provide a specific background colour.
#3332
@mart-jansinkEnsure resized image is unpremultiplied before composite.
#3334
Src Content Docs Changelog V0.31.1 (`docs/src/content/docs/changelog/v0.31.1.md`)
title: v0.31.1 - 29th September 2022 slug: changelog/v0.31.1
Upgrade to libvips v8.13.2 for upstream bug fixes.
Ensure
closeevent occurs afterendevent for Stream-based output.
#3313Ensure
limitInputPixelsconstructor option uses uint64.
#3349
@marcosc90Ensure auto-rotation works with shrink-on-load and extract (regression in 0.31.0).
#3352Ensure AVIF output is always 8-bit.
#3358Ensure greyscale images can be trimmed (regression in 0.31.0).
#3386
Src Content Docs Changelog V0.31.2 (`docs/src/content/docs/changelog/v0.31.2.md`)
title: v0.31.2 - 4th November 2022 slug: changelog/v0.31.2
Upgrade to libvips v8.13.3 for upstream bug fixes.
Ensure manual flip, rotate, resize operation ordering (regression in 0.31.1)
#3391Ensure auto-rotation works without resize (regression in 0.31.1)
#3422
Src Content Docs Changelog V0.31.3 (`docs/src/content/docs/changelog/v0.31.3.md`)
title: v0.31.3 - 21st December 2022 slug: changelog/v0.31.3
Add experimental support for JPEG-XL images. Requires libvips compiled with libjxl.
#2731Add runtime detection of V8 memory cage, ensures compatibility with Electron 21 onwards.
#3384Expose
interFrameMaxErrorandinterPaletteMaxErrorGIF optimisation properties.
#3401Allow installation on Linux with glibc patch versions e.g. Fedora 38.
#3423Expand range of existing
sharpenparameters to match libvips.
#3427Prevent possible race condition awaiting metadata of Stream-based input.
#3451Improve
extractChannelsupport for 16-bit output colourspaces.
#3453Ignore
sequentialReadoption when calculating image statistics.
#3462Small performance improvement for operations that introduce a non-opaque background.
#3465Ensure integral output of
linearoperation.
#3468
Src Content Docs Changelog V0.32.0 (`docs/src/content/docs/changelog/v0.32.0.md`)
title: v0.32.0 - 24th March 2023 slug: changelog/v0.32.0
Default to using sequential rather than random access read where possible.
Replace GIF output
optimise/optimizeoption withreuse.Add
progressiveoption to GIF output for interlacing.Add
wrapoption to text image creation.Add
formatMagickproperty to metadata of images loaded via *magick.Prefer integer (un)premultiply for faster resizing of RGBA images.
Add
ignoreIccinput option to ignore embedded ICC profile.Allow use of GPS (IFD3) EXIF metadata.
#2767TypeScript definitions are now maintained and published directly, deprecating the
@types/sharppackage.
#3369Prebuilt binaries: ensure macOS 10.13+ support, as documented.
#3438Prebuilt binaries: prevent use of glib slice allocator, improves QEMU support.
#3448Add focus point coordinates to output when using attention based crop.
#3470
@ejoebstlExpose sharp version as
sharp.versions.sharp.
#3471Respect
fastShrinkOnLoadresize option for WebP input.
#3516Reduce sharpen
sigmamaximum from 10000 to 10.
#3521Add support to
extendoperation forextendWithto allow copy/mirror/repeat.
#3556
@janazEnsure all async JS callbacks are wrapped to help avoid possible race condition.
#3569Prebuilt binaries: support for tile-based output temporarily removed due to licensing issue.
#3581Add support to
normaliseforlowerandupperpercentiles.
#3583
@LachlanNewman
Src Content Docs Changelog V0.32.1 (`docs/src/content/docs/changelog/v0.32.1.md`)
title: v0.32.1 - 27th April 2023 slug: changelog/v0.32.1
Add experimental
unflattenoperation.
#3461
@antonmarsdenEnsure use of
flipoperation forces random access read (regression in 0.32.0).
#3600Ensure
linearoperation works with 16-bit input (regression in 0.31.3).
#3605Install: ensure proxy URLs are logged correctly.
#3615
@TomWis97Ensure profile-less CMYK to CMYK roundtrip skips colourspace conversion.
#3620Add support for
modulateoperation when using non-sRGB pipeline colourspace.
#3620Ensure
trimoperation works with CMYK images (regression in 0.31.0).
#3636Install: coerce libc version to semver.
#3641
--- METRICS ---
- Files Extracted: 101
- Estimated Token Budget: ~54516 tokens
- Canonical Reference: https://codewiki.google/github.com/lovell/sharp