12 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, TIFF, DZI, and libvips' V format supported. Note that raw pixel data is only supported for buffer output.
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, TIFF and RAW output are supported. By default, the format will match the input image, except GIF and SVG input which become PNG output.
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 => { ... });
Returns Promise<Buffer> when no callback is provided
withMetadata
Include all metadata (EXIF, XMP, IPTC) from the input image in the output image.
The default behaviour, when withMetadata is not used, is to strip all metadata and convert to the device-independent sRGB colour space.
This will also convert to and add a web-friendly sRGB ICC profile.
Parameters
withMetadataObject?withMetadata.orientationNumber? value between 1 and 8, used to update the EXIFOrientationtag.
Examples
sharp('input.jpg')
.withMetadata()
.toFile('output-with-metadata.jpg')
.then(info => { ... });
- Throws Error Invalid parameters
Returns Sharp
jpeg
Use these JPEG options for output image.
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 when quality <= 90 (optional, default'4:2:0')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 (optional, defaultfalse)options.optimiseCodingBoolean optimise Huffman coding tables (optional, defaulttrue)options.optimizeCodingBoolean alternative spelling of optimiseCoding (optional, defaulttrue)options.quantisationTableNumber quantization table to use, integer 0-8, requires libvips compiled with support for mozjpeg (optional, default0)options.quantizationTableNumber alternative spelling of quantisationTable (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.
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, requires libvips compiled with support for libimagequant (optional, default100)options.coloursNumber maximum number of palette entries, requires libvips compiled with support for libimagequant (optional, default256)options.colorsNumber alternative spelling ofoptions.colours, requires libvips compiled with support for libimagequant (optional, default256)options.ditherNumber level of Floyd-Steinberg error diffusion, 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.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
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.squashBoolean squash 8-bit images down to 1 bit (optional, defaultfalse)
Examples
// Convert SVG input to LZW-compressed, 1 bit per pixel TIFF output
sharp('input.svg')
.tiff({
compression: 'lzw',
squash: true
})
.toFile('1-bpp-output.tiff')
.then(info => { ... });
- Throws Error Invalid options
Returns Sharp
raw
Force output to be raw, uncompressed uint8 pixel data.
Examples
// Extract raw RGB pixel data from JPEG input
const { data, info } = await sharp('input.jpg')
.raw()
.toBuffer({ resolveWithObject: true });
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
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
tileObject?tile.sizeNumber tile size in pixels, a value between 1 and 8192. (optional, default256)tile.overlapNumber tile overlap in pixels, a value between 0 and 8192. (optional, default0)tile.angleNumber tile angle of rotation, must be a multiple of 90. (optional, default0)tile.depthString? how deep to make the pyramid, possible values areonepixel,onetileorone, default based on layout.tile.containerString tile container, with valuefs(filesystem) orzip(compressed file). (optional, default'fs')tile.layoutString filesystem layout, possible values aredz,zoomifyorgoogle. (optional, default'dz')
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