Skip to content

Latest commit

 

History

History
841 lines (628 loc) · 28.4 KB

api-output.md

File metadata and controls

841 lines (628 loc) · 28.4 KB

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

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

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

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:

  • Error Invalid 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.

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

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

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
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).

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
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:

  • Error Invalid 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:

  • Error Invalid 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:

  • Error Invalid 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.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.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:

  • Error Invalid 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.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:

  • Error Invalid 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:

  • Error Invalid 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.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
[options.tileHeight] number 256 vertical tile size
[options.xres] number 1.0 horizontal resolution in pixels/mm
[options.yres] number 1.0 vertical resolution in pixels/mm
[options.resolutionUnit] string "'inch'" resolution unit options: inch, cm
[options.bitdepth] number 8 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:

  • Error Invalid 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

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

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

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.

Image metadata (EXIF, XMP) is unsupported.

Throws:

  • Error Invalid 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 3 (fastest) and 9 (slowest)

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

Requires libvips compiled with support for libgsf. The prebuilt binaries do not include this - see installing a custom libvips.

Throws:

  • Error Invalid 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&#x27;" 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')) { ... }
}