22 KiB
toFile
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.
Parameters
fileOut
string the path to write the image data to.callback
Function? called on completion with two arguments(err, info)
.info
contains the output imageformat
,size
(bytes),width
,height
,channels
andpremultiplied
(indicating if premultiplication was used). When using a crop strategy also containscropOffsetLeft
andcropOffsetTop
.
Examples
sharp(input)
.toFile('output.png', (err, info) => { ... });
sharp(input)
.toFile('output.png')
.then(info => { ... })
.catch(err => { ... });
- Throws Error Invalid parameters
Returns Promise<Object> when no callback is provided
toBuffer
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:
err
is an error, if any.data
is the output image data.info
contains the output imageformat
,size
(bytes),width
,height
,
channels
and premultiplied
(indicating if premultiplication was used).
When using a crop strategy also contains cropOffsetLeft
and cropOffsetTop
.
A Promise
is returned when callback
is not provided.
Parameters
-
options
Object?options.resolveWithObject
boolean? Resolve the Promise with an Object containingdata
andinfo
properties instead of resolving only withdata
.
-
callback
Function?
Examples
sharp(input)
.toBuffer((err, data, info) => { ... });
sharp(input)
.toBuffer()
.then(data => { ... })
.catch(err => { ... });
sharp(input)
.png()
.toBuffer({ resolveWithObject: true })
.then(({ data, info }) => { ... })
.catch(err => { ... });
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');
Returns Promise<Buffer> when no callback is provided
withMetadata
Include all 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 unless a custom output profile is provided.
The default behaviour, when withMetadata
is not used, is to convert to the device-independent
sRGB colour space and strip all metadata, including the removal of any ICC profile.
EXIF metadata is unsupported for TIFF output.
Parameters
-
options
Object?options.orientation
number? value between 1 and 8, used to update the EXIFOrientation
tag.options.icc
string? filesystem path to output ICC profile, defaults to sRGB.options.exif
Object<Object> Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. (optional, default{}
)options.density
number? Number of pixels per inch (DPI).
Examples
sharp('input.jpg')
.withMetadata()
.toFile('output-with-metadata.jpg')
.then(info => { ... });
// Set "IFD0-Copyright" in output EXIF metadata
const data = await sharp(input)
.withMetadata({
exif: {
IFD0: {
Copyright: 'Wernham Hogg'
}
}
})
.toBuffer();
// Set output metadata to 96 DPI
const data = await sharp(input)
.withMetadata({ density: 96 })
.toBuffer();
- Throws Error Invalid parameters
Returns Sharp
toFormat
Force output to a given format.
Parameters
format
(string | Object) as a string or an Object with an 'id' attributeoptions
Object output options
Examples
// Convert any input to PNG output
const data = await sharp(input)
.toFormat('png')
.toBuffer();
- Throws Error unsupported format or options
Returns Sharp
jpeg
Use these JPEG options for output image.
Parameters
-
options
Object? output optionsoptions.quality
number quality, integer 1-100 (optional, default80
)options.progressive
boolean use progressive (interlace) scan (optional, defaultfalse
)options.chromaSubsampling
string set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling (optional, default'4:2:0'
)options.optimiseCoding
boolean optimise Huffman coding tables (optional, defaulttrue
)options.optimizeCoding
boolean alternative spelling of optimiseCoding (optional, defaulttrue
)options.mozjpeg
boolean use mozjpeg defaults, equivalent to{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }
(optional, defaultfalse
)options.trellisQuantisation
boolean apply trellis quantisation (optional, defaultfalse
)options.overshootDeringing
boolean apply overshoot deringing (optional, defaultfalse
)options.optimiseScans
boolean optimise progressive scans, forces progressive (optional, defaultfalse
)options.optimizeScans
boolean alternative spelling of optimiseScans (optional, defaultfalse
)options.quantisationTable
number quantization table to use, integer 0-8 (optional, default0
)options.quantizationTable
number alternative spelling of quantisationTable (optional, default0
)options.force
boolean force JPEG output, otherwise attempt to use input format (optional, defaulttrue
)
Examples
// Convert any input to very high quality JPEG output
const data = await sharp(input)
.jpeg({
quality: 100,
chromaSubsampling: '4:4:4'
})
.toBuffer();
// Use mozjpeg to reduce output JPEG file size (slower)
const data = await sharp(input)
.jpeg({ mozjpeg: true })
.toBuffer();
- Throws Error Invalid options
Returns Sharp
png
Use these PNG options for output image.
By default, PNG output is full colour at 8 or 16 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.
Parameters
-
options
Object?options.progressive
boolean use progressive (interlace) scan (optional, defaultfalse
)options.compressionLevel
number zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest) (optional, default6
)options.adaptiveFiltering
boolean use adaptive row filtering (optional, defaultfalse
)options.palette
boolean quantise to a palette-based image with alpha transparency support (optional, defaultfalse
)options.quality
number use the lowest number of colours needed to achieve given quality, setspalette
totrue
(optional, default100
)options.effort
number CPU effort, between 1 (fastest) and 10 (slowest), setspalette
totrue
(optional, default7
)options.colours
number maximum number of palette entries, setspalette
totrue
(optional, default256
)options.colors
number alternative spelling ofoptions.colours
, setspalette
totrue
(optional, default256
)options.dither
number level of Floyd-Steinberg error diffusion, setspalette
totrue
(optional, default1.0
)options.force
boolean force PNG output, otherwise attempt to use input format (optional, defaulttrue
)
Examples
// Convert any input to full colour PNG output
const data = await sharp(input)
.png()
.toBuffer();
// Convert any input to indexed PNG output (slower)
const data = await sharp(input)
.png({ palette: true })
.toBuffer();
- Throws Error Invalid options
Returns Sharp
webp
Use these WebP options for output image.
Parameters
-
options
Object? output optionsoptions.quality
number quality, integer 1-100 (optional, default80
)options.alphaQuality
number quality of alpha layer, integer 0-100 (optional, default100
)options.lossless
boolean use lossless compression mode (optional, defaultfalse
)options.nearLossless
boolean use near_lossless compression mode (optional, defaultfalse
)options.smartSubsample
boolean use high quality chroma subsampling (optional, defaultfalse
)options.effort
number CPU effort, between 0 (fastest) and 6 (slowest) (optional, default4
)options.loop
number number of animation iterations, use 0 for infinite animation (optional, default0
)options.delay
(number | Array<number>)? delay(s) between animation frames (in milliseconds)options.force
boolean force WebP output, otherwise attempt to use input format (optional, defaulttrue
)
Examples
// Convert any input to lossless WebP output
const data = await sharp(input)
.webp({ lossless: true })
.toBuffer();
// Optimise the file size of an animated WebP
const outputWebp = await sharp(inputWebp, { animated: true })
.webp({ effort: 6 })
.toBuffer();
- Throws Error Invalid options
Returns Sharp
gif
Use these GIF options for the output image.
The first entry in the palette is reserved for transparency.
Parameters
-
options
Object? output optionsoptions.colours
number maximum number of palette entries, including transparency, between 2 and 256 (optional, default256
)options.colors
number alternative spelling ofoptions.colours
(optional, default256
)options.effort
number CPU effort, between 1 (fastest) and 10 (slowest) (optional, default7
)options.dither
number level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) (optional, default1.0
)options.loop
number number of animation iterations, use 0 for infinite animation (optional, default0
)options.delay
(number | Array<number>)? delay(s) between animation frames (in milliseconds)options.force
boolean force GIF output, otherwise attempt to use input format (optional, defaulttrue
)
Examples
// Convert PNG to GIF
await sharp(pngBuffer)
.gif()
.toBuffer();
// Convert animated WebP to animated GIF
await sharp('animated.webp', { animated: true })
.toFile('animated.gif');
// 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();
- Throws Error Invalid options
Returns Sharp
Meta
- since: 0.30.0
jp2
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.
Parameters
-
options
Object? output optionsoptions.quality
number quality, integer 1-100 (optional, default80
)options.lossless
boolean use lossless compression mode (optional, defaultfalse
)options.tileWidth
number horizontal tile size (optional, default512
)options.tileHeight
number vertical tile size (optional, default512
)options.chromaSubsampling
string set to '4:2:0' to use chroma subsampling (optional, default'4:4:4'
)
Examples
// Convert any input to lossless JP2 output
const data = await sharp(input)
.jp2({ lossless: true })
.toBuffer();
// Convert any input to very high quality JP2 output
const data = await sharp(input)
.jp2({
quality: 100,
chromaSubsampling: '4:4:4'
})
.toBuffer();
- Throws Error Invalid options
Returns Sharp
Meta
- since: 0.29.1
tiff
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.
Parameters
-
options
Object? output optionsoptions.quality
number quality, integer 1-100 (optional, default80
)options.force
boolean force TIFF output, otherwise attempt to use input format (optional, defaulttrue
)options.compression
string compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k (optional, default'jpeg'
)options.predictor
string compression predictor options: none, horizontal, float (optional, default'horizontal'
)options.pyramid
boolean write an image pyramid (optional, defaultfalse
)options.tile
boolean write a tiled tiff (optional, defaultfalse
)options.tileWidth
number horizontal tile size (optional, default256
)options.tileHeight
number vertical tile size (optional, default256
)options.xres
number horizontal resolution in pixels/mm (optional, default1.0
)options.yres
number vertical resolution in pixels/mm (optional, default1.0
)options.resolutionUnit
string resolution unit options: inch, cm (optional, default'inch'
)options.bitdepth
number reduce bitdepth to 1, 2 or 4 bit (optional, default8
)
Examples
// 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 => { ... });
- Throws Error Invalid options
Returns Sharp
avif
Use these AVIF options for output image.
Whilst it is possible to create AVIF images smaller than 16x16 pixels, most web browsers do not display these properly.
AVIF image sequences are not supported.
Parameters
-
options
Object? output optionsoptions.quality
number quality, integer 1-100 (optional, default50
)options.lossless
boolean use lossless compression (optional, defaultfalse
)options.effort
number CPU effort, between 0 (fastest) and 9 (slowest) (optional, default4
)options.chromaSubsampling
string set to '4:2:0' to use chroma subsampling (optional, default'4:4:4'
)
- Throws Error Invalid options
Returns Sharp
Meta
- since: 0.27.0
heif
Use these HEIF options for output image.
Support for patent-encumbered HEIC images requires the use of a globally-installed libvips compiled with support for libheif, libde265 and x265.
Parameters
-
options
Object? output optionsoptions.quality
number quality, integer 1-100 (optional, default50
)options.compression
string compression format: av1, hevc (optional, default'av1'
)options.lossless
boolean use lossless compression (optional, defaultfalse
)options.effort
number CPU effort, between 0 (fastest) and 9 (slowest) (optional, default4
)options.chromaSubsampling
string set to '4:2:0' to use chroma subsampling (optional, default'4:4:4'
)
- Throws Error Invalid options
Returns Sharp
Meta
- since: 0.23.0
raw
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.
Parameters
-
options
Object? output optionsoptions.depth
string bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex (optional, default'uchar'
)
Examples
// Extract raw, unsigned 8-bit RGB pixel data from JPEG input
const { data, info } = await sharp('input.jpg')
.raw()
.toBuffer({ resolveWithObject: true });
// 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();
- Throws Error Invalid options
tile
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.
Parameters
-
options
Object?options.size
number tile size in pixels, a value between 1 and 8192. (optional, default256
)options.overlap
number tile overlap in pixels, a value between 0 and 8192. (optional, default0
)options.angle
number tile angle of rotation, must be a multiple of 90. (optional, default0
)options.background
(string | Object) background colour, parsed by the color module, defaults to white without transparency. (optional, default{r:255,g:255,b:255,alpha:1}
)options.depth
string? how deep to make the pyramid, possible values areonepixel
,onetile
orone
, default based on layout.options.skipBlanks
number threshold to skip tile generation, a value 0 - 255 for 8-bit images or 0 - 65535 for 16-bit images (optional, default-1
)options.container
string tile container, with valuefs
(filesystem) orzip
(compressed file). (optional, default'fs'
)options.layout
string filesystem layout, possible values aredz
,iiif
,iiif3
,zoomify
orgoogle
. (optional, default'dz'
)options.centre
boolean centre image in tile. (optional, defaultfalse
)options.center
boolean alternative spelling of centre. (optional, defaultfalse
)options.id
string whenlayout
isiiif
/iiif3
, sets the@id
/id
attribute ofinfo.json
(optional, default'https://example.com/iiif'
)
Examples
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
});
- Throws Error Invalid parameters
Returns Sharp
timeout
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.
Parameters
Examples
// 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')) { ... }
}
Returns Sharp
Meta
- since: 0.29.2