Skip to content

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:

  • Error Invalid parameters
ParamTypeDescription
fileOutstringthe path to write the image data to.
[callback]functioncalled 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:

  • err is an error, if any.
  • data is the output image data.
  • 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. Animated output will also contain pageHeight and pages. May also contain textAutofitDpi (dpi the font was rendered at) if image was created from text.

A Promise is returned when callback is not provided.

Returns: Promise.<Buffer> - - when no callback is provided

ParamTypeDescription
[options]Object
[options.resolveWithObject]booleanResolve the Promise with an Object containing data and info properties instead of resolving only with data.
[callback]function

Example

sharp(input)
.toBuffer((err, data, info) => { ... });

Example

sharp(input)
.toBuffer()
.then(data => { ... })
.catch(err => { ... });

Example

sharp(input)
.png()
.toBuffer({ resolveWithObject: true })
.then(({ data, info }) => { ... })
.catch(err => { ... });

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');

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:

  • Error Invalid parameters

Since: 0.33.0

ParamTypeDescription
exifObject.<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:

  • Error Invalid parameters

Since: 0.33.0

ParamTypeDescription
exifObject.<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.

Where necessary, will attempt to convert the output colour space to match the profile.

Since: 0.33.0
Example

const outputWithIccProfile = await sharp(inputWithIccProfile)
.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:

  • Error Invalid parameters

Since: 0.33.0

ParamTypeDefaultDescription
iccstringAbsolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk).
[options]Object
[options.attach]numbertrueShould the ICC profile be included in the output image metadata?

Example

const outputWithP3 = await sharp(input)
.withIccProfile('p3')
.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:

  • Error Invalid parameters
ParamTypeDescription
[options]Object
[options.orientation]numberUsed to update the EXIF Orientation tag, integer between 1 and 8.
[options.density]numberNumber of pixels per inch (DPI).

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:

  • Error unsupported format or options
ParamTypeDescription
formatstring | Objectas a string or an Object with an ‘id’ attribute
optionsObjectoutput 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:

  • Error Invalid options
ParamTypeDefaultDescription
[options]Objectoutput options
[options.quality]number80quality, integer 1-100
[options.progressive]booleanfalseuse 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]booleantrueoptimise Huffman coding tables
[options.optimizeCoding]booleantruealternative spelling of optimiseCoding
[options.mozjpeg]booleanfalseuse mozjpeg defaults, equivalent to { trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }
[options.trellisQuantisation]booleanfalseapply trellis quantisation
[options.overshootDeringing]booleanfalseapply overshoot deringing
[options.optimiseScans]booleanfalseoptimise progressive scans, forces progressive
[options.optimizeScans]booleanfalsealternative spelling of optimiseScans
[options.quantisationTable]number0quantization table to use, integer 0-8
[options.quantizationTable]number0alternative spelling of quantisationTable
[options.force]booleantrueforce 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:

  • Error Invalid options
ParamTypeDefaultDescription
[options]Object
[options.progressive]booleanfalseuse progressive (interlace) scan
[options.compressionLevel]number6zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest)
[options.adaptiveFiltering]booleanfalseuse adaptive row filtering
[options.palette]booleanfalsequantise to a palette-based image with alpha transparency support
[options.quality]number100use the lowest number of colours needed to achieve given quality, sets palette to true
[options.effort]number7CPU effort, between 1 (fastest) and 10 (slowest), sets palette to true
[options.colours]number256maximum number of palette entries, sets palette to true
[options.colors]number256alternative spelling of options.colours, sets palette to true
[options.dither]number1.0level of Floyd-Steinberg error diffusion, sets palette to true
[options.force]booleantrueforce 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:

  • Error Invalid options
ParamTypeDefaultDescription
[options]Objectoutput options
[options.quality]number80quality, integer 1-100
[options.alphaQuality]number100quality of alpha layer, integer 0-100
[options.lossless]booleanfalseuse lossless compression mode
[options.nearLossless]booleanfalseuse near_lossless compression mode
[options.smartSubsample]booleanfalseuse high quality chroma subsampling
[options.smartDeblock]booleanfalseauto-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]number4CPU effort, between 0 (fastest) and 6 (slowest)
[options.loop]number0number of animation iterations, use 0 for infinite animation
[options.delay]number | Array.<number>delay(s) between animation frames (in milliseconds)
[options.minSize]booleanfalseprevent use of animation key frames to minimise file size (slow)
[options.mixed]booleanfalseallow mixture of lossy and lossless animation frames (slow)
[options.force]booleantrueforce 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:

  • Error Invalid options

Since: 0.30.0

ParamTypeDefaultDescription
[options]Objectoutput options
[options.reuse]booleantruere-use existing palette, otherwise generate new (slow)
[options.progressive]booleanfalseuse progressive (interlace) scan
[options.colours]number256maximum number of palette entries, including transparency, between 2 and 256
[options.colors]number256alternative spelling of options.colours
[options.effort]number7CPU effort, between 1 (fastest) and 10 (slowest)
[options.dither]number1.0level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most)
[options.interFrameMaxError]number0maximum inter-frame error for transparency, between 0 (lossless) and 32
[options.interPaletteMaxError]number3maximum inter-palette error for palette reuse, between 0 and 256
[options.loop]number0number of animation iterations, use 0 for infinite animation
[options.delay]number | Array.<number>delay(s) between animation frames (in milliseconds)
[options.force]booleantrueforce 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:

  • Error Invalid options

Since: 0.29.1

ParamTypeDefaultDescription
[options]Objectoutput options
[options.quality]number80quality, integer 1-100
[options.lossless]booleanfalseuse lossless compression mode
[options.tileWidth]number512horizontal tile size
[options.tileHeight]number512vertical 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:

  • Error Invalid options
ParamTypeDefaultDescription
[options]Objectoutput options
[options.quality]number80quality, integer 1-100
[options.force]booleantrueforce TIFF output, otherwise attempt to use input format
[options.compression]string“‘jpeg‘“compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k
[options.predictor]string“‘horizontal‘“compression predictor options: none, horizontal, float
[options.pyramid]booleanfalsewrite an image pyramid
[options.tile]booleanfalsewrite a tiled tiff
[options.tileWidth]number256horizontal tile size
[options.tileHeight]number256vertical tile size
[options.xres]number1.0horizontal resolution in pixels/mm
[options.yres]number1.0vertical resolution in pixels/mm
[options.resolutionUnit]string“‘inch‘“resolution unit options: inch, cm
[options.bitdepth]number8reduce bitdepth to 1, 2 or 4 bit
[options.miniswhite]booleanfalsewrite 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. Prebuilt binaries support a bitdepth of 8 only.

Throws:

  • Error Invalid options

Since: 0.27.0

ParamTypeDefaultDescription
[options]Objectoutput options
[options.quality]number50quality, integer 1-100
[options.lossless]booleanfalseuse lossless compression
[options.effort]number4CPU effort, between 0 (fastest) and 9 (slowest)
[options.chromaSubsampling]string“‘4:4:4‘“set to ‘4:2:0’ to use chroma subsampling
[options.bitdepth]number8set bitdepth to 8, 10 or 12 bit

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:

  • Error Invalid options

Since: 0.23.0

ParamTypeDefaultDescription
optionsObjectoutput options
options.compressionstringcompression format: av1, hevc
[options.quality]number50quality, integer 1-100
[options.lossless]booleanfalseuse lossless compression
[options.effort]number4CPU effort, between 0 (fastest) and 9 (slowest)
[options.chromaSubsampling]string“‘4:4:4‘“set to ‘4:2:0’ to use chroma subsampling
[options.bitdepth]number8set bitdepth to 8, 10 or 12 bit

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:

  • Error Invalid options

Since: 0.31.3

ParamTypeDefaultDescription
[options]Objectoutput options
[options.distance]number1.0maximum encoding error, between 0 (highest quality) and 15 (lowest quality)
[options.quality]numbercalculate distance based on JPEG-like quality, between 1 and 100, overrides distance if specified
[options.decodingTier]number0target decode speed tier, between 0 (highest quality) and 4 (lowest quality)
[options.lossless]booleanfalseuse lossless compression
[options.effort]number7CPU effort, between 1 (fastest) and 9 (slowest)
[options.loop]number0number 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:

  • Error Invalid options
ParamTypeDefaultDescription
[options]Objectoutput 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:

  • Error Invalid parameters
ParamTypeDefaultDescription
[options]Object
[options.size]number256tile size in pixels, a value between 1 and 8192.
[options.overlap]number0tile overlap in pixels, a value between 0 and 8192.
[options.angle]number0tile 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]stringhow deep to make the pyramid, possible values are onepixel, onetile or one, default based on layout.
[options.skipBlanks]number-1Threshold 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]booleanfalsecentre image in tile.
[options.center]booleanfalsealternative spelling of centre.
[options.id]string“‘https://example.com/iiif&#x27;“when layout is iiif/iiif3, sets the @id/id attribute of info.json
[options.basename]stringthe 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

ParamTypeDescription
optionsObject
options.secondsnumberNumber 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')) { ... }
}