17 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, 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.
A Promise is returned when callback is not provided.
Parameters
fileOutstring the path to write the image data to.callbackFunction? called on completion with two arguments(err, info).infocontains the output imageformat,size(bytes),width,height,channelsandpremultiplied(indicating if premultiplication was used). When using a crop strategy also containscropOffsetLeftandcropOffsetTop.
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 and raw pixel data output are supported.
If no explicit format is set, the output format will match the input image, except GIF and SVG input which become 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.
A Promise is returned when callback is not provided.
Parameters
optionsObject?options.resolveWithObjectboolean? Resolve the Promise with an Object containingdataandinfoproperties instead of resolving only withdata.
callbackFunction?
Examples
sharp(input)
.toBuffer((err, data, info) => { ... });
sharp(input)
.toBuffer()
.then(data => { ... })
.catch(err => { ... });
sharp(input)
.toBuffer({ resolveWithObject: true })
.then(({ data, info }) => { ... })
.catch(err => { ... });
const data = await sharp('my-image.jpg')
// output the raw pixels
.raw()
.toBuffer();
// 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
await sharp(pixelArray).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.
Parameters
optionsObject?
Examples
sharp('input.jpg')
.withMetadata()
.toFile('output-with-metadata.jpg')
.then(info => { ... });
- 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' attributeoptionsObject 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.
Some of these options require the use of a globally-installed libvips compiled with support for mozjpeg.
Parameters
optionsObject? output optionsoptions.qualitynumber quality, integer 1-100 (optional, default80)options.progressiveboolean use progressive (interlace) scan (optional, defaultfalse)options.chromaSubsamplingstring set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling (optional, default'4:2:0')options.optimiseCodingboolean optimise Huffman coding tables (optional, defaulttrue)options.optimizeCodingboolean alternative spelling of optimiseCoding (optional, defaulttrue)options.trellisQuantisationboolean apply trellis quantisation, requires libvips compiled with support for mozjpeg (optional, defaultfalse)options.overshootDeringingboolean apply overshoot deringing, requires libvips compiled with support for mozjpeg (optional, defaultfalse)options.optimiseScansboolean optimise progressive scans, forces progressive, requires libvips compiled with support for mozjpeg (optional, defaultfalse)options.optimizeScansboolean alternative spelling of optimiseScans, requires libvips compiled with support for mozjpeg (optional, defaultfalse)options.quantisationTablenumber quantization table to use, integer 0-8, requires libvips compiled with support for mozjpeg (optional, default0)options.quantizationTablenumber alternative spelling of quantisationTable, requires libvips compiled with support for mozjpeg (optional, default0)options.forceboolean 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();
- Throws Error Invalid options
Returns Sharp
png
Use these PNG options for output image.
PNG output is always 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.
Some of these options require the use of a globally-installed libvips compiled with support for libimagequant (GPL).
Parameters
optionsObject?options.progressiveboolean use progressive (interlace) scan (optional, defaultfalse)options.compressionLevelnumber zlib compression level, 0-9 (optional, default9)options.adaptiveFilteringboolean use adaptive row filtering (optional, defaultfalse)options.paletteboolean quantise to a palette-based image with alpha transparency support, requires libvips compiled with support for libimagequant (optional, defaultfalse)options.qualitynumber use the lowest number of colours needed to achieve given quality, setspalettetotrue, requires libvips compiled with support for libimagequant (optional, default100)options.coloursnumber maximum number of palette entries, setspalettetotrue, requires libvips compiled with support for libimagequant (optional, default256)options.colorsnumber alternative spelling ofoptions.colours, setspalettetotrue, requires libvips compiled with support for libimagequant (optional, default256)options.dithernumber level of Floyd-Steinberg error diffusion, setspalettetotrue, requires libvips compiled with support for libimagequant (optional, default1.0)options.forceboolean force PNG output, otherwise attempt to use input format (optional, defaulttrue)
Examples
// Convert any input to PNG output
const data = await sharp(input)
.png()
.toBuffer();
- Throws Error Invalid options
Returns Sharp
webp
Use these WebP options for output image.
Parameters
optionsObject? output optionsoptions.qualitynumber quality, integer 1-100 (optional, default80)options.alphaQualitynumber quality of alpha layer, integer 0-100 (optional, default100)options.losslessboolean use lossless compression mode (optional, defaultfalse)options.nearLosslessboolean use near_lossless compression mode (optional, defaultfalse)options.smartSubsampleboolean use high quality chroma subsampling (optional, defaultfalse)options.reductionEffortnumber level of CPU effort to reduce file size, integer 0-6 (optional, default4)options.pageHeightnumber? page height for animated outputoptions.loopnumber number of animation iterations, use 0 for infinite animation (optional, default0)options.delayArray<number>? list of delays between animation frames (in milliseconds)options.forceboolean 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();
- Throws Error Invalid options
Returns Sharp
gif
Use these GIF options for output image.
Requires libvips compiled with support for ImageMagick or GraphicsMagick. The prebuilt binaries do not include this - see installing a custom libvips.
Parameters
-
optionsObject? output optionsoptions.pageHeightnumber? page height for animated outputoptions.loopnumber number of animation iterations, use 0 for infinite animation (optional, default0)options.delayArray<number>? list of delays between animation frames (in milliseconds)options.forceboolean force GIF output, otherwise attempt to use input format (optional, defaulttrue)
-
Throws Error Invalid options
Returns Sharp
tiff
Use these TIFF options for output image.
Parameters
optionsObject? output optionsoptions.qualitynumber quality, integer 1-100 (optional, default80)options.forceboolean force TIFF output, otherwise attempt to use input format (optional, defaulttrue)options.compressionboolean compression options: lzw, deflate, jpeg, ccittfax4 (optional, default'jpeg')options.predictorboolean compression predictor options: none, horizontal, float (optional, default'horizontal')options.pyramidboolean write an image pyramid (optional, defaultfalse)options.tileboolean write a tiled tiff (optional, defaultfalse)options.tileWidthboolean horizontal tile size (optional, default256)options.tileHeightboolean vertical tile size (optional, default256)options.xresnumber horizontal resolution in pixels/mm (optional, default1.0)options.yresnumber vertical resolution in pixels/mm (optional, default1.0)options.bitdepthboolean 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.
Parameters
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
-
optionsObject? output optionsoptions.qualitynumber quality, integer 1-100 (optional, default50)options.compressionboolean compression format: av1, hevc (optional, default'av1')options.losslessboolean use lossless compression (optional, defaultfalse)options.speedboolean CPU effort vs file size, 0 (slowest/smallest) to 8 (fastest/largest) (optional, default5)
-
Throws Error Invalid options
Returns Sharp
Meta
- since: 0.23.0
raw
Force output to be raw, uncompressed, 8-bit unsigned integer (unit8) pixel data. Pixel ordering is left-to-right, top-to-bottom, without padding. Channel ordering will be RGB or RGBA for non-greyscale colourspaces.
Examples
// Extract raw RGB pixel data from JPEG input
const { data, info } = await sharp('input.jpg')
.raw()
.toBuffer({ resolveWithObject: true });
// Extract alpha channel as raw pixel data from PNG input
const data = await sharp('input.png')
.ensureAlpha()
.extractChannel(3)
.toColourspace('b-w')
.raw()
.toBuffer();
Returns Sharp
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.
Warning: multiple sharp instances concurrently producing tile output can expose a possible race condition in some versions of libgsf.
Parameters
optionsObject?options.sizenumber tile size in pixels, a value between 1 and 8192. (optional, default256)options.overlapnumber tile overlap in pixels, a value between 0 and 8192. (optional, default0)options.anglenumber 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.depthstring? how deep to make the pyramid, possible values areonepixel,onetileorone, default based on layout.options.skipBlanksnumber threshold to skip tile generation, a value 0 - 255 for 8-bit images or 0 - 65535 for 16-bit images (optional, default-1)options.containerstring tile container, with valuefs(filesystem) orzip(compressed file). (optional, default'fs')options.layoutstring filesystem layout, possible values aredz,iiif,zoomifyorgoogle. (optional, default'dz')options.centreboolean centre image in tile. (optional, defaultfalse)options.centerboolean alternative spelling of centre. (optional, defaultfalse)
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