diff --git a/docs/api-channel.md b/docs/api-channel.md index 3f6d859f..7e50b817 100644 --- a/docs/api-channel.md +++ b/docs/api-channel.md @@ -1,14 +1,11 @@ - - ## removeAlpha - Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel. -See also [flatten][1]. +See also [flatten](/api-operation#flatten). -### Examples -```javascript +**Example** +```js sharp('rgba.png') .removeAlpha() .toFile('rgb.png', function(err, info) { @@ -16,61 +13,62 @@ sharp('rgba.png') }); ``` -Returns **Sharp** ## ensureAlpha - Ensure the output image has an alpha transparency channel. If missing, the added alpha channel will have the specified transparency level, defaulting to fully-opaque (1). This is a no-op if the image already has an alpha channel. -### Parameters -* `alpha` **[number][2]** alpha transparency level (0=fully-transparent, 1=fully-opaque) (optional, default `1`) +**Throws**: -### Examples +- Error Invalid alpha transparency level -```javascript +**Since**: 0.21.2 + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [alpha] | number | 1 | alpha transparency level (0=fully-transparent, 1=fully-opaque) | + +**Example** +```js // rgba.png will be a 4 channel image with a fully-opaque alpha channel await sharp('rgb.jpg') .ensureAlpha() .toFile('rgba.png') ``` - -```javascript +**Example** +```js // rgba is a 4 channel image with a fully-transparent alpha channel const rgba = await sharp(rgb) .ensureAlpha(0) .toBuffer(); ``` -* Throws **[Error][3]** Invalid alpha transparency level - -Returns **Sharp** - -**Meta** - -* **since**: 0.21.2 ## extractChannel - Extract a single channel from a multi-channel image. -### Parameters -* `channel` **([number][2] | [string][4])** zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`. +**Throws**: -### Examples +- Error Invalid channel -```javascript + +| Param | Type | Description | +| --- | --- | --- | +| channel | number \| string | zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`. | + +**Example** +```js // green.jpg is a greyscale image containing the green channel of the input await sharp(input) .extractChannel('green') .toFile('green.jpg'); ``` - -```javascript +**Example** +```js // red1 is the red value of the first pixel, red2 the second pixel etc. const [red1, red2, ...] = await sharp(input) .extractChannel(0) @@ -78,45 +76,46 @@ const [red1, red2, ...] = await sharp(input) .toBuffer(); ``` -* Throws **[Error][3]** Invalid channel - -Returns **Sharp** ## joinChannel - Join one or more channels to the image. The meaning of the added channels depends on the output colourspace, set with `toColourspace()`. By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. Channel ordering follows vips convention: - -* sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha. -* CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha. +- sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha. +- CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha. Buffers may be any of the image formats supported by sharp. For raw pixel input, the `options` object should contain a `raw` attribute, which follows the format of the attribute of the same name in the `sharp()` constructor. -### Parameters -* `images` **([Array][5]<([string][4] | [Buffer][6])> | [string][4] | [Buffer][6])** one or more images (file paths, Buffers). -* `options` **[Object][7]** image options, see `sharp()` constructor. +**Throws**: - +- Error Invalid parameters + + +| Param | Type | Description | +| --- | --- | --- | +| images | Array.<(string\|Buffer)> \| string \| Buffer | one or more images (file paths, Buffers). | +| options | Object | image options, see `sharp()` constructor. | -* Throws **[Error][3]** Invalid parameters -Returns **Sharp** ## bandbool - Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image. -### Parameters -* `boolOp` **[string][4]** one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. +**Throws**: -### Examples +- Error Invalid parameters -```javascript + +| Param | Type | Description | +| --- | --- | --- | +| boolOp | string | one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. | + +**Example** +```js sharp('3-channel-rgb-input.png') .bandbool(sharp.bool.and) .toFile('1-channel-output.png', function (err, info) { @@ -124,22 +123,4 @@ sharp('3-channel-rgb-input.png') // If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]` // then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`. }); -``` - -* Throws **[Error][3]** Invalid parameters - -Returns **Sharp** - -[1]: /api-operation#flatten - -[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number - -[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error - -[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String - -[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array - -[6]: https://nodejs.org/api/buffer.html - -[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object +``` \ No newline at end of file diff --git a/docs/api-colour.md b/docs/api-colour.md index 7b7a41d1..4594a6e3 100644 --- a/docs/api-colour.md +++ b/docs/api-colour.md @@ -1,28 +1,26 @@ - - ## tint - Tint the image using the provided chroma while preserving the image luminance. An alpha channel may be present and will be unchanged by the operation. -### Parameters -* `rgb` **([string][1] | [Object][2])** parsed by the [color][3] module to extract chroma values. +**Throws**: -### Examples +- Error Invalid parameter -```javascript + +| Param | Type | Description | +| --- | --- | --- | +| rgb | string \| Object | parsed by the [color](https://www.npmjs.org/package/color) module to extract chroma values. | + +**Example** +```js const output = await sharp(input) .tint({ r: 255, g: 240, b: 16 }) .toBuffer(); ``` -* Throws **[Error][4]** Invalid parameter - -Returns **Sharp** ## greyscale - Convert to 8-bit greyscale; 256 shades of grey. This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results. By default the output image will be web-friendly sRGB and contain three (identical) color channels. @@ -30,44 +28,50 @@ This may be overridden by other sharp operations such as `toColourspace('b-w')`, which will produce an output image containing one color channel. An alpha channel may be present, and will be unchanged by the operation. -### Parameters -* `greyscale` **[Boolean][5]** (optional, default `true`) -### Examples +| Param | Type | Default | +| --- | --- | --- | +| [greyscale] | Boolean | true | -```javascript +**Example** +```js const output = await sharp(input).greyscale().toBuffer(); ``` -Returns **Sharp** ## grayscale - Alternative spelling of `greyscale`. -### Parameters -* `grayscale` **[Boolean][5]** (optional, default `true`) -Returns **Sharp** +| Param | Type | Default | +| --- | --- | --- | +| [grayscale] | Boolean | true | + + ## pipelineColourspace - Set the pipeline colourspace. The input image will be converted to the provided colourspace at the start of the pipeline. -All operations will use this colourspace before converting to the output colourspace, as defined by [toColourspace][6]. +All operations will use this colourspace before converting to the output colourspace, as defined by [toColourspace](#toColourspace). This feature is experimental and has not yet been fully-tested with all operations. -### Parameters -* `colourspace` **[string][1]?** pipeline colourspace e.g. `rgb16`, `scrgb`, `lab`, `grey16` [...][7] +**Throws**: -### Examples +- Error Invalid parameters -```javascript +**Since**: 0.29.0 + +| Param | Type | Description | +| --- | --- | --- | +| [colourspace] | string | pipeline colourspace e.g. `rgb16`, `scrgb`, `lab`, `grey16` [...](https://github.com/libvips/libvips/blob/41cff4e9d0838498487a00623462204eb10ee5b8/libvips/iofuncs/enumtypes.c#L774) | + +**Example** +```js // Run pipeline in 16 bits per channel RGB while converting final result to 8 bits per channel sRGB. await sharp(input) .pipelineColourspace('rgb16') @@ -75,76 +79,54 @@ await sharp(input) .toFile('16bpc-pipeline-to-8bpc-output.png') ``` -* Throws **[Error][4]** Invalid parameters - -Returns **Sharp** - -**Meta** - -* **since**: 0.29.0 ## pipelineColorspace - Alternative spelling of `pipelineColourspace`. -### Parameters -* `colorspace` **[string][1]?** pipeline colorspace. +**Throws**: - +- Error Invalid parameters + + +| Param | Type | Description | +| --- | --- | --- | +| [colorspace] | string | pipeline colorspace. | -* Throws **[Error][4]** Invalid parameters -Returns **Sharp** ## toColourspace - Set the output colourspace. By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. -### Parameters -* `colourspace` **[string][1]?** output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...][8] +**Throws**: -### Examples +- Error Invalid parameters -```javascript + +| Param | Type | Description | +| --- | --- | --- | +| [colourspace] | string | output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/libvips/libvips/blob/3c0bfdf74ce1dc37a6429bed47fa76f16e2cd70a/libvips/iofuncs/enumtypes.c#L777-L794) | + +**Example** +```js // Output 16 bits per pixel RGB await sharp(input) .toColourspace('rgb16') .toFile('16-bpp.png') ``` -* Throws **[Error][4]** Invalid parameters - -Returns **Sharp** ## toColorspace - Alternative spelling of `toColourspace`. -### Parameters -* `colorspace` **[string][1]?** output colorspace. +**Throws**: - +- Error Invalid parameters -* Throws **[Error][4]** Invalid parameters -Returns **Sharp** - -[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String - -[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object - -[3]: https://www.npmjs.org/package/color - -[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error - -[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean - -[6]: #tocolourspace - -[7]: https://github.com/libvips/libvips/blob/41cff4e9d0838498487a00623462204eb10ee5b8/libvips/iofuncs/enumtypes.c#L774 - -[8]: https://github.com/libvips/libvips/blob/3c0bfdf74ce1dc37a6429bed47fa76f16e2cd70a/libvips/iofuncs/enumtypes.c#L777-L794 +| Param | Type | Description | +| --- | --- | --- | +| [colorspace] | string | output colorspace. | \ No newline at end of file diff --git a/docs/api-composite.md b/docs/api-composite.md index f63e5864..521bdb76 100644 --- a/docs/api-composite.md +++ b/docs/api-composite.md @@ -1,7 +1,4 @@ - - ## composite - Composite image(s) over the processed (resized, extracted etc.) image. The images to composite must be the same size or smaller than the processed image. @@ -17,52 +14,53 @@ The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`, `hard-light`, `soft-light`, `difference`, `exclusion`. More information about blend modes can be found at -[https://www.libvips.org/API/current/libvips-conversion.html#VipsBlendMode][1] -and [https://www.cairographics.org/operators/][2] +https://www.libvips.org/API/current/libvips-conversion.html#VipsBlendMode +and https://www.cairographics.org/operators/ -### Parameters -* `images` **[Array][3]<[Object][4]>** Ordered list of images to composite +**Throws**: - * `images[].input` **([Buffer][5] | [String][6])?** Buffer containing image data, String containing the path to an image file, or Create object (see below) +- Error Invalid parameters - * `images[].input.create` **[Object][4]?** describes a blank overlay to be created. +**Since**: 0.22.0 - * `images[].input.create.width` **[Number][7]?** - * `images[].input.create.height` **[Number][7]?** - * `images[].input.create.channels` **[Number][7]?** 3-4 - * `images[].input.create.background` **([String][6] | [Object][4])?** parsed by the [color][8] module to extract values for red, green, blue and alpha. - * `images[].input.text` **[Object][4]?** describes a new text image to be created. +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| images | Array.<Object> | | Ordered list of images to composite | +| [images[].input] | Buffer \| String | | Buffer containing image data, String containing the path to an image file, or Create object (see below) | +| [images[].input.create] | Object | | describes a blank overlay to be created. | +| [images[].input.create.width] | Number | | | +| [images[].input.create.height] | Number | | | +| [images[].input.create.channels] | Number | | 3-4 | +| [images[].input.create.background] | String \| Object | | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. | +| [images[].input.text] | Object | | describes a new text image to be created. | +| [images[].input.text.text] | string | | text to render as a UTF-8 string. It can contain Pango markup, for example `LeMonde`. | +| [images[].input.text.font] | string | | font name to render with. | +| [images[].input.text.fontfile] | string | | absolute filesystem path to a font file that can be used by `font`. | +| [images[].input.text.width] | number | 0 | integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. | +| [images[].input.text.height] | number | 0 | integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. | +| [images[].input.text.align] | string | "'left'" | text alignment (`'left'`, `'centre'`, `'center'`, `'right'`). | +| [images[].input.text.justify] | boolean | false | set this to true to apply justification to the text. | +| [images[].input.text.dpi] | number | 72 | the resolution (size) at which to render the text. Does not take effect if `height` is specified. | +| [images[].input.text.rgba] | boolean | false | set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `Red!`. | +| [images[].input.text.spacing] | number | 0 | text line height in points. Will use the font line height if none is specified. | +| [images[].blend] | String | 'over' | how to blend this image with the image below. | +| [images[].gravity] | String | 'centre' | gravity at which to place the overlay. | +| [images[].top] | Number | | the pixel offset from the top edge. | +| [images[].left] | Number | | the pixel offset from the left edge. | +| [images[].tile] | Boolean | false | set to true to repeat the overlay image across the entire image with the given `gravity`. | +| [images[].premultiplied] | Boolean | false | set to true to avoid premultipling the image below. Equivalent to the `--premultiplied` vips option. | +| [images[].density] | Number | 72 | number representing the DPI for vector overlay image. | +| [images[].raw] | Object | | describes overlay when using raw pixel data. | +| [images[].raw.width] | Number | | | +| [images[].raw.height] | Number | | | +| [images[].raw.channels] | Number | | | +| [images[].animated] | boolean | false | Set to `true` to read all frames/pages of an animated image. | +| [images[].failOn] | string | "'warning'" | @see [constructor parameters](/api-constructor#parameters) | +| [images[].limitInputPixels] | number \| boolean | 268402689 | @see [constructor parameters](/api-constructor#parameters) | - * `images[].input.text.text` **[string][6]?** text to render as a UTF-8 string. It can contain Pango markup, for example `LeMonde`. - * `images[].input.text.font` **[string][6]?** font name to render with. - * `images[].input.text.fontfile` **[string][6]?** absolute filesystem path to a font file that can be used by `font`. - * `images[].input.text.width` **[number][7]** integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. (optional, default `0`) - * `images[].input.text.height` **[number][7]** integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. (optional, default `0`) - * `images[].input.text.align` **[string][6]** text alignment (`'left'`, `'centre'`, `'center'`, `'right'`). (optional, default `'left'`) - * `images[].input.text.justify` **[boolean][9]** set this to true to apply justification to the text. (optional, default `false`) - * `images[].input.text.dpi` **[number][7]** the resolution (size) at which to render the text. Does not take effect if `height` is specified. (optional, default `72`) - * `images[].input.text.rgba` **[boolean][9]** set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `Red!`. (optional, default `false`) - * `images[].input.text.spacing` **[number][7]** text line height in points. Will use the font line height if none is specified. (optional, default `0`) - * `images[].blend` **[String][6]** how to blend this image with the image below. (optional, default `'over'`) - * `images[].gravity` **[String][6]** gravity at which to place the overlay. (optional, default `'centre'`) - * `images[].top` **[Number][7]?** the pixel offset from the top edge. - * `images[].left` **[Number][7]?** the pixel offset from the left edge. - * `images[].tile` **[Boolean][9]** set to true to repeat the overlay image across the entire image with the given `gravity`. (optional, default `false`) - * `images[].premultiplied` **[Boolean][9]** set to true to avoid premultipling the image below. Equivalent to the `--premultiplied` vips option. (optional, default `false`) - * `images[].density` **[Number][7]** number representing the DPI for vector overlay image. (optional, default `72`) - * `images[].raw` **[Object][4]?** describes overlay when using raw pixel data. - - * `images[].raw.width` **[Number][7]?** - * `images[].raw.height` **[Number][7]?** - * `images[].raw.channels` **[Number][7]?** - * `images[].animated` **[boolean][9]** Set to `true` to read all frames/pages of an animated image. (optional, default `false`) - * `images[].failOn` **[string][6]** @see [constructor parameters][10] (optional, default `'warning'`) - * `images[].limitInputPixels` **([number][7] | [boolean][9])** @see [constructor parameters][10] (optional, default `268402689`) - -### Examples - -```javascript +**Example** +```js await sharp(background) .composite([ { input: layer1, gravity: 'northwest' }, @@ -70,16 +68,16 @@ await sharp(background) ]) .toFile('combined.png'); ``` - -```javascript +**Example** +```js const output = await sharp('input.gif', { animated: true }) .composite([ { input: 'overlay.png', tile: true, blend: 'saturate' } ]) .toBuffer(); ``` - -```javascript +**Example** +```js sharp('input.png') .rotate(180) .resize(300) @@ -94,34 +92,4 @@ sharp('input.png') // onto orange background, composited with overlay.png with SE gravity, // sharpened, with metadata, 90% quality WebP image data. Phew! }); -``` - -* Throws **[Error][11]** Invalid parameters - -Returns **Sharp** - -**Meta** - -* **since**: 0.22.0 - -[1]: https://www.libvips.org/API/current/libvips-conversion.html#VipsBlendMode - -[2]: https://www.cairographics.org/operators/ - -[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array - -[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object - -[5]: https://nodejs.org/api/buffer.html - -[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String - -[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number - -[8]: https://www.npmjs.org/package/color - -[9]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean - -[10]: /api-constructor#parameters - -[11]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error +``` \ No newline at end of file diff --git a/docs/api-constructor.md b/docs/api-constructor.md index 55a442ba..24ea9366 100644 --- a/docs/api-constructor.md +++ b/docs/api-constructor.md @@ -1,7 +1,9 @@ - - ## Sharp +**Emits**: Sharp#event:info, Sharp#event:warning + + +### new Constructor factory to create an instance of `sharp`, to which further methods are chained. JPEG, PNG, WebP, GIF, AVIF or TIFF format image data can be streamed out from this object. @@ -9,65 +11,56 @@ When using Stream based output, derived attributes are available from the `info` Non-critical problems encountered during processing are emitted as `warning` events. -Implements the [stream.Duplex][1] class. +Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class. -### Parameters +**Throws**: -* `input` **([Buffer][2] | [Uint8Array][3] | [Uint8ClampedArray][4] | [Int8Array][5] | [Uint16Array][6] | [Int16Array][7] | [Uint32Array][8] | [Int32Array][9] | [Float32Array][10] | [Float64Array][11] | [string][12])?** if present, can be - a Buffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or - a TypedArray containing raw pixel image data, or - a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. - JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. -* `options` **[Object][13]?** if present, is an Object with optional attributes. +- Error Invalid parameters - * `options.failOn` **[string][12]** when to abort processing of invalid pixel data, one of (in order of sensitivity): 'none' (least), 'truncated', 'error' or 'warning' (most), highers level imply lower levels, invalid metadata will always abort. (optional, default `'warning'`) - * `options.limitInputPixels` **([number][14] | [boolean][15])** Do not process input images where the number of pixels - (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted. - An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). (optional, default `268402689`) - * `options.unlimited` **[boolean][15]** Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). (optional, default `false`) - * `options.sequentialRead` **[boolean][15]** Set this to `true` to use sequential rather than random access where possible. - This can reduce memory usage and might improve performance on some systems. (optional, default `false`) - * `options.density` **[number][14]** number representing the DPI for vector images in the range 1 to 100000. (optional, default `72`) - * `options.pages` **[number][14]** number of pages to extract for multi-page input (GIF, WebP, AVIF, TIFF, PDF), use -1 for all pages. (optional, default `1`) - * `options.page` **[number][14]** page number to start extracting from for multi-page input (GIF, WebP, AVIF, TIFF, PDF), zero based. (optional, default `0`) - * `options.subifd` **[number][14]** subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. (optional, default `-1`) - * `options.level` **[number][14]** level to extract from a multi-level input (OpenSlide), zero based. (optional, default `0`) - * `options.animated` **[boolean][15]** Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). (optional, default `false`) - * `options.raw` **[Object][13]?** describes raw pixel input image data. See `raw()` for pixel ordering. - * `options.raw.width` **[number][14]?** integral number of pixels wide. - * `options.raw.height` **[number][14]?** integral number of pixels high. - * `options.raw.channels` **[number][14]?** integral number of channels, between 1 and 4. - * `options.raw.premultiplied` **[boolean][15]?** specifies that the raw input has already been premultiplied, set to `true` - to avoid sharp premultiplying the image. (optional, default `false`) - * `options.create` **[Object][13]?** describes a new image to be created. +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [input] | Buffer \| Uint8Array \| Uint8ClampedArray \| Int8Array \| Uint16Array \| Int16Array \| Uint32Array \| Int32Array \| Float32Array \| Float64Array \| string | | if present, can be a Buffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or a TypedArray containing raw pixel image data, or a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. | +| [options] | Object | | if present, is an Object with optional attributes. | +| [options.failOn] | string | "'warning'" | when to abort processing of invalid pixel data, one of (in order of sensitivity): 'none' (least), 'truncated', 'error' or 'warning' (most), highers level imply lower levels, invalid metadata will always abort. | +| [options.limitInputPixels] | number \| boolean | 268402689 | Do not process input images where the number of pixels (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted. An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). | +| [options.unlimited] | boolean | false | Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). | +| [options.sequentialRead] | boolean | false | Set this to `true` to use sequential rather than random access where possible. This can reduce memory usage and might improve performance on some systems. | +| [options.density] | number | 72 | number representing the DPI for vector images in the range 1 to 100000. | +| [options.pages] | number | 1 | number of pages to extract for multi-page input (GIF, WebP, AVIF, TIFF, PDF), use -1 for all pages. | +| [options.page] | number | 0 | page number to start extracting from for multi-page input (GIF, WebP, AVIF, TIFF, PDF), zero based. | +| [options.subifd] | number | -1 | subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. | +| [options.level] | number | 0 | level to extract from a multi-level input (OpenSlide), zero based. | +| [options.animated] | boolean | false | Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). | +| [options.raw] | Object | | describes raw pixel input image data. See `raw()` for pixel ordering. | +| [options.raw.width] | number | | integral number of pixels wide. | +| [options.raw.height] | number | | integral number of pixels high. | +| [options.raw.channels] | number | | integral number of channels, between 1 and 4. | +| [options.raw.premultiplied] | boolean | | specifies that the raw input has already been premultiplied, set to `true` to avoid sharp premultiplying the image. (optional, default `false`) | +| [options.create] | Object | | describes a new image to be created. | +| [options.create.width] | number | | integral number of pixels wide. | +| [options.create.height] | number | | integral number of pixels high. | +| [options.create.channels] | number | | integral number of channels, either 3 (RGB) or 4 (RGBA). | +| [options.create.background] | string \| Object | | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. | +| [options.create.noise] | Object | | describes a noise to be created. | +| [options.create.noise.type] | string | | type of generated noise, currently only `gaussian` is supported. | +| [options.create.noise.mean] | number | | mean of pixels in generated noise. | +| [options.create.noise.sigma] | number | | standard deviation of pixels in generated noise. | +| [options.text] | Object | | describes a new text image to be created. | +| [options.text.text] | string | | text to render as a UTF-8 string. It can contain Pango markup, for example `LeMonde`. | +| [options.text.font] | string | | font name to render with. | +| [options.text.fontfile] | string | | absolute filesystem path to a font file that can be used by `font`. | +| [options.text.width] | number | 0 | integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. | +| [options.text.height] | number | 0 | integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. | +| [options.text.align] | string | "'left'" | text alignment (`'left'`, `'centre'`, `'center'`, `'right'`). | +| [options.text.justify] | boolean | false | set this to true to apply justification to the text. | +| [options.text.dpi] | number | 72 | the resolution (size) at which to render the text. Does not take effect if `height` is specified. | +| [options.text.rgba] | boolean | false | set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `Red!`. | +| [options.text.spacing] | number | 0 | text line height in points. Will use the font line height if none is specified. | +| [options.text.wrap] | number | 'word' | word wrapping style when width is provided, one of: 'word', 'char', 'charWord' (prefer char, fallback to word) or 'none'. | - * `options.create.width` **[number][14]?** integral number of pixels wide. - * `options.create.height` **[number][14]?** integral number of pixels high. - * `options.create.channels` **[number][14]?** integral number of channels, either 3 (RGB) or 4 (RGBA). - * `options.create.background` **([string][12] | [Object][13])?** parsed by the [color][16] module to extract values for red, green, blue and alpha. - * `options.create.noise` **[Object][13]?** describes a noise to be created. - - * `options.create.noise.type` **[string][12]?** type of generated noise, currently only `gaussian` is supported. - * `options.create.noise.mean` **[number][14]?** mean of pixels in generated noise. - * `options.create.noise.sigma` **[number][14]?** standard deviation of pixels in generated noise. - * `options.text` **[Object][13]?** describes a new text image to be created. - - * `options.text.text` **[string][12]?** text to render as a UTF-8 string. It can contain Pango markup, for example `LeMonde`. - * `options.text.font` **[string][12]?** font name to render with. - * `options.text.fontfile` **[string][12]?** absolute filesystem path to a font file that can be used by `font`. - * `options.text.width` **[number][14]** integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. (optional, default `0`) - * `options.text.height` **[number][14]** integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. (optional, default `0`) - * `options.text.align` **[string][12]** text alignment (`'left'`, `'centre'`, `'center'`, `'right'`). (optional, default `'left'`) - * `options.text.justify` **[boolean][15]** set this to true to apply justification to the text. (optional, default `false`) - * `options.text.dpi` **[number][14]** the resolution (size) at which to render the text. Does not take effect if `height` is specified. (optional, default `72`) - * `options.text.rgba` **[boolean][15]** set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `Red!`. (optional, default `false`) - * `options.text.spacing` **[number][14]** text line height in points. Will use the font line height if none is specified. (optional, default `0`) - * `options.text.wrap` **[number][14]** word wrapping style when width is provided, one of: 'word', 'char', 'charWord' (prefer char, fallback to word) or 'none'. (optional, default `'word'`) - -### Examples - -```javascript +**Example** +```js sharp('input.jpg') .resize(300, 200) .toFile('output.jpg', function(err) { @@ -75,8 +68,8 @@ sharp('input.jpg') // containing a scaled and cropped version of input.jpg }); ``` - -```javascript +**Example** +```js // Read image data from readableStream, // resize to 300 pixels wide, // emit an 'info' event with calculated dimensions @@ -88,8 +81,8 @@ var transformer = sharp() }); readableStream.pipe(transformer).pipe(writableStream); ``` - -```javascript +**Example** +```js // Create a blank 300x200 PNG image of semi-transluent red pixels sharp({ create: { @@ -103,13 +96,13 @@ sharp({ .toBuffer() .then( ... ); ``` - -```javascript +**Example** +```js // Convert an animated GIF to an animated WebP await sharp('in.gif', { animated: true }).toFile('out.webp'); ``` - -```javascript +**Example** +```js // Read a raw array of pixels and save it to a png const input = Uint8Array.from([255, 255, 255, 0, 0, 0]); // or Uint8ClampedArray const image = sharp(input, { @@ -123,8 +116,8 @@ const image = sharp(input, { }); await image.toFile('my-two-pixels.png'); ``` - -```javascript +**Example** +```js // Generate RGB Gaussian noise await sharp({ create: { @@ -139,8 +132,8 @@ await sharp({ } }).toFile('noise.png'); ``` - -```javascript +**Example** +```js // Generate an image from text await sharp({ text: { @@ -150,8 +143,8 @@ await sharp({ } }).toFile('text_bw.png'); ``` - -```javascript +**Example** +```js // Generate an rgba image from text using pango markup and font await sharp({ text: { @@ -163,19 +156,15 @@ await sharp({ }).toFile('text_rgba.png'); ``` -* Throws **[Error][17]** Invalid parameters - -Returns **[Sharp][18]** ## clone - Take a "snapshot" of the Sharp instance, returning a new instance. Cloned instances inherit the input of their parent instance. This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream. -### Examples -```javascript +**Example** +```js const pipeline = sharp().rotate(); pipeline.clone().resize(800, 600).pipe(firstWritableStream); pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 }).pipe(secondWritableStream); @@ -183,8 +172,8 @@ readableStream.pipe(pipeline); // firstWritableStream receives auto-rotated, resized readableStream // secondWritableStream receives auto-rotated, extracted region of readableStream ``` - -```javascript +**Example** +```js // Create a pipeline that will download an image, resize it and format it to different files // Using Promises to know when the pipeline is complete const fs = require("fs"); @@ -229,42 +218,4 @@ Promise.all(promises) fs.unlinkSync("optimized-500.webp"); } catch (e) {} }); -``` - -Returns **[Sharp][18]** - -[1]: http://nodejs.org/api/stream.html#stream_class_stream_duplex - -[2]: https://nodejs.org/api/buffer.html - -[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array - -[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray - -[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Int8Array - -[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array - -[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Int16Array - -[8]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array - -[9]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Int32Array - -[10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Float32Array - -[11]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Float64Array - -[12]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String - -[13]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object - -[14]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number - -[15]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean - -[16]: https://www.npmjs.org/package/color - -[17]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error - -[18]: #sharp +``` \ No newline at end of file diff --git a/docs/api-input.md b/docs/api-input.md index 2aa9bd37..3d78e78d 100644 --- a/docs/api-input.md +++ b/docs/api-input.md @@ -1,57 +1,55 @@ - - ## metadata - Fast access to (uncached) image metadata without decoding any compressed pixel data. This is taken from the header of the input image. It does not include operations, such as resize, to be applied to the output image. Dimensions in the response will respect the `page` and `pages` properties of the -[constructor parameters][1]. +[constructor parameters](/api-constructor#parameters). A `Promise` is returned when `callback` is not provided. -* `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg` -* `size`: Total size of image in bytes, for Stream and Buffer input only -* `width`: Number of pixels wide (EXIF orientation is not taken into consideration, see example below) -* `height`: Number of pixels high (EXIF orientation is not taken into consideration, see example below) -* `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...][2] -* `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK -* `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...][3] -* `density`: Number of pixels per inch (DPI), if present -* `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK -* `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan -* `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP -* `pageHeight`: Number of pixels high each page in a multi-page image will be. -* `loop`: Number of times to loop an animated image, zero refers to a continuous loop. -* `delay`: Delay in ms between each page in an animated image, provided as an array of integers. -* `pagePrimary`: Number of the primary page in a HEIF image -* `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide -* `subifds`: Number of Sub Image File Directories in an OME-TIFF image -* `background`: Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value -* `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC) -* `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present -* `hasProfile`: Boolean indicating the presence of an embedded ICC profile -* `hasAlpha`: Boolean indicating the presence of an alpha transparency channel -* `orientation`: Number value of the EXIF Orientation header, if present -* `exif`: Buffer containing raw EXIF data, if present -* `icc`: Buffer containing raw [ICC][4] profile data, if present -* `iptc`: Buffer containing raw IPTC data, if present -* `xmp`: Buffer containing raw XMP data, if present -* `tifftagPhotoshop`: Buffer containing raw TIFFTAG\_PHOTOSHOP data, if present +- `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg` +- `size`: Total size of image in bytes, for Stream and Buffer input only +- `width`: Number of pixels wide (EXIF orientation is not taken into consideration, see example below) +- `height`: Number of pixels high (EXIF orientation is not taken into consideration, see example below) +- `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://www.libvips.org/API/current/VipsImage.html#VipsInterpretation) +- `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK +- `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...](https://www.libvips.org/API/current/VipsImage.html#VipsBandFormat) +- `density`: Number of pixels per inch (DPI), if present +- `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK +- `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan +- `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP +- `pageHeight`: Number of pixels high each page in a multi-page image will be. +- `loop`: Number of times to loop an animated image, zero refers to a continuous loop. +- `delay`: Delay in ms between each page in an animated image, provided as an array of integers. +- `pagePrimary`: Number of the primary page in a HEIF image +- `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide +- `subifds`: Number of Sub Image File Directories in an OME-TIFF image +- `background`: Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value +- `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC) +- `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present +- `hasProfile`: Boolean indicating the presence of an embedded ICC profile +- `hasAlpha`: Boolean indicating the presence of an alpha transparency channel +- `orientation`: Number value of the EXIF Orientation header, if present +- `exif`: Buffer containing raw EXIF data, if present +- `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present +- `iptc`: Buffer containing raw IPTC data, if present +- `xmp`: Buffer containing raw XMP data, if present +- `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present -### Parameters -* `callback` **[Function][5]?** called with the arguments `(err, metadata)` -### Examples +| Param | Type | Description | +| --- | --- | --- | +| [callback] | function | called with the arguments `(err, metadata)` | -```javascript +**Example** +```js const metadata = await sharp(input).metadata(); ``` - -```javascript +**Example** +```js const image = sharp(inputJpg); image .metadata() @@ -65,8 +63,8 @@ image // data contains a WebP image half the width and height of the original JPEG }); ``` - -```javascript +**Example** +```js // Based on EXIF rotation metadata, get the right-side-up width and height: const size = getNormalSize(await sharp(input).metadata()); @@ -78,39 +76,38 @@ function getNormalSize({ width, height, orientation }) { } ``` -Returns **([Promise][6]<[Object][7]> | Sharp)** ## stats - Access to pixel-derived image statistics for every channel in the image. A `Promise` is returned when `callback` is not provided. -* `channels`: Array of channel statistics for each channel in the image. Each channel statistic contains - * `min` (minimum value in the channel) - * `max` (maximum value in the channel) - * `sum` (sum of all values in a channel) - * `squaresSum` (sum of squared values in a channel) - * `mean` (mean of the values in a channel) - * `stdev` (standard deviation for the values in a channel) - * `minX` (x-coordinate of one of the pixel where the minimum lies) - * `minY` (y-coordinate of one of the pixel where the minimum lies) - * `maxX` (x-coordinate of one of the pixel where the maximum lies) - * `maxY` (y-coordinate of one of the pixel where the maximum lies) -* `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque. -* `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any. -* `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any. -* `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram. +- `channels`: Array of channel statistics for each channel in the image. Each channel statistic contains + - `min` (minimum value in the channel) + - `max` (maximum value in the channel) + - `sum` (sum of all values in a channel) + - `squaresSum` (sum of squared values in a channel) + - `mean` (mean of the values in a channel) + - `stdev` (standard deviation for the values in a channel) + - `minX` (x-coordinate of one of the pixel where the minimum lies) + - `minY` (y-coordinate of one of the pixel where the minimum lies) + - `maxX` (x-coordinate of one of the pixel where the maximum lies) + - `maxY` (y-coordinate of one of the pixel where the maximum lies) +- `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque. +- `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any. +- `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any. +- `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram. **Note**: Statistics are derived from the original input image. Any operations performed on the image must first be written to a buffer in order to run `stats` on the result (see third example). -### Parameters -* `callback` **[Function][5]?** called with the arguments `(err, stats)` -### Examples +| Param | Type | Description | +| --- | --- | --- | +| [callback] | function | called with the arguments `(err, stats)` | -```javascript +**Example** +```js const image = sharp(inputJpg); image .stats() @@ -118,32 +115,16 @@ image // stats contains the channel-wise statistics array and the isOpaque value }); ``` - -```javascript +**Example** +```js const { entropy, sharpness, dominant } = await sharp(input).stats(); const { r, g, b } = dominant; ``` - -```javascript +**Example** +```js const image = sharp(input); // store intermediate result const part = await image.extract(region).toBuffer(); // create new instance to obtain statistics of extracted region const stats = await sharp(part).stats(); -``` - -Returns **[Promise][6]<[Object][7]>** - -[1]: /api-constructor#parameters - -[2]: https://www.libvips.org/API/current/VipsImage.html#VipsInterpretation - -[3]: https://www.libvips.org/API/current/VipsImage.html#VipsBandFormat - -[4]: https://www.npmjs.com/package/icc - -[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function - -[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise - -[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object +``` \ No newline at end of file diff --git a/docs/api-operation.md b/docs/api-operation.md index 80519049..35f212fe 100644 --- a/docs/api-operation.md +++ b/docs/api-operation.md @@ -1,7 +1,4 @@ - - ## rotate - Rotate the output image by either an explicit angle or auto-orient based on the EXIF `Orientation` tag. @@ -22,16 +19,20 @@ Previous calls to `rotate` in the same pipeline will be ignored. Method order is important when rotating, resizing and/or extracting regions, for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`. -### Parameters -* `angle` **[number][1]** angle of rotation. (optional, default `auto`) -* `options` **[Object][2]?** if present, is an Object with optional attributes. +**Throws**: - * `options.background` **([string][3] | [Object][2])** parsed by the [color][4] module to extract values for red, green, blue and alpha. (optional, default `"#000000"`) +- Error Invalid parameters -### Examples -```javascript +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [angle] | number | auto | angle of rotation. | +| [options] | Object | | if present, is an Object with optional attributes. | +| [options.background] | string \| Object | "\"#000000\"" | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. | + +**Example** +```js const pipeline = sharp() .rotate() .resize(null, 200) @@ -42,8 +43,8 @@ const pipeline = sharp() }); readableStream.pipe(pipeline); ``` - -```javascript +**Example** +```js const rotateThenResize = await sharp(input) .rotate(90) .resize({ width: 16, height: 8, fit: 'fill' }) @@ -54,46 +55,40 @@ const resizeThenRotate = await sharp(input) .toBuffer(); ``` -* Throws **[Error][5]** Invalid parameters - -Returns **Sharp** ## flip - Flip the image about the vertical Y axis. This always occurs before rotation, if any. The use of `flip` implies the removal of the EXIF `Orientation` tag, if any. -### Parameters -* `flip` **[Boolean][6]** (optional, default `true`) -### Examples +| Param | Type | Default | +| --- | --- | --- | +| [flip] | Boolean | true | -```javascript +**Example** +```js const output = await sharp(input).flip().toBuffer(); ``` -Returns **Sharp** ## flop - Flop the image about the horizontal X axis. This always occurs before rotation, if any. The use of `flop` implies the removal of the EXIF `Orientation` tag, if any. -### Parameters -* `flop` **[Boolean][6]** (optional, default `true`) -### Examples +| Param | Type | Default | +| --- | --- | --- | +| [flop] | Boolean | true | -```javascript +**Example** +```js const output = await sharp(input).flop().toBuffer(); ``` -Returns **Sharp** ## affine - Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any. You must provide an array of length 4 or a 2x2 affine transformation matrix. @@ -101,31 +96,34 @@ By default, new pixels are filled with a black background. You can provide a bac A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolator` Object e.g. `sharp.interpolator.nohalo`. In the case of a 2x2 matrix, the transform is: - -* X = `matrix[0, 0]` \* (x + `idx`) + `matrix[0, 1]` \* (y + `idy`) + `odx` -* Y = `matrix[1, 0]` \* (x + `idx`) + `matrix[1, 1]` \* (y + `idy`) + `ody` +- X = `matrix[0, 0]` \* (x + `idx`) + `matrix[0, 1]` \* (y + `idy`) + `odx` +- Y = `matrix[1, 0]` \* (x + `idx`) + `matrix[1, 1]` \* (y + `idy`) + `ody` where: +- x and y are the coordinates in input image. +- X and Y are the coordinates in output image. +- (0,0) is the upper left corner. -* x and y are the coordinates in input image. -* X and Y are the coordinates in output image. -* (0,0) is the upper left corner. -### Parameters +**Throws**: -* `matrix` **([Array][7]<[Array][7]<[number][1]>> | [Array][7]<[number][1]>)** affine transformation matrix -* `options` **[Object][2]?** if present, is an Object with optional attributes. +- Error Invalid parameters - * `options.background` **([String][3] | [Object][2])** parsed by the [color][4] module to extract values for red, green, blue and alpha. (optional, default `"#000000"`) - * `options.idx` **[Number][1]** input horizontal offset (optional, default `0`) - * `options.idy` **[Number][1]** input vertical offset (optional, default `0`) - * `options.odx` **[Number][1]** output horizontal offset (optional, default `0`) - * `options.ody` **[Number][1]** output vertical offset (optional, default `0`) - * `options.interpolator` **[String][3]** interpolator (optional, default `sharp.interpolators.bicubic`) +**Since**: 0.27.0 -### Examples +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| matrix | Array.<Array.<number>> \| Array.<number> | | affine transformation matrix | +| [options] | Object | | if present, is an Object with optional attributes. | +| [options.background] | String \| Object | "#000000" | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. | +| [options.idx] | Number | 0 | input horizontal offset | +| [options.idy] | Number | 0 | input vertical offset | +| [options.odx] | Number | 0 | output horizontal offset | +| [options.ody] | Number | 0 | output vertical offset | +| [options.interpolator] | String | sharp.interpolators.bicubic | interpolator | -```javascript +**Example** +```js const pipeline = sharp() .affine([[1, 0.3], [0.1, 0.7]], { background: 'white', @@ -140,16 +138,8 @@ inputStream .pipe(pipeline); ``` -* Throws **[Error][5]** Invalid parameters - -Returns **Sharp** - -**Meta** - -* **since**: 0.27.0 ## sharpen - Sharpen the image. When used without parameters, performs a fast, mild sharpen of the output image. @@ -157,32 +147,36 @@ When used without parameters, performs a fast, mild sharpen of the output image. When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space. Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available. -See [libvips sharpen][8] operation. +See [libvips sharpen](https://www.libvips.org/API/current/libvips-convolution.html#vips-sharpen) operation. -### Parameters -* `options` **([Object][2] | [number][1])?** if present, is an Object with attributes +**Throws**: - * `options.sigma` **[number][1]?** the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`, between 0.000001 and 10000 - * `options.m1` **[number][1]** the level of sharpening to apply to "flat" areas, between 0 and 1000000 (optional, default `1.0`) - * `options.m2` **[number][1]** the level of sharpening to apply to "jagged" areas, between 0 and 1000000 (optional, default `2.0`) - * `options.x1` **[number][1]** threshold between "flat" and "jagged", between 0 and 1000000 (optional, default `2.0`) - * `options.y2` **[number][1]** maximum amount of brightening, between 0 and 1000000 (optional, default `10.0`) - * `options.y3` **[number][1]** maximum amount of darkening, between 0 and 1000000 (optional, default `20.0`) -* `flat` **[number][1]?** (deprecated) see `options.m1`. -* `jagged` **[number][1]?** (deprecated) see `options.m2`. +- Error Invalid parameters -### Examples -```javascript +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [options] | Object \| number | | if present, is an Object with attributes | +| [options.sigma] | number | | the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`, between 0.000001 and 10000 | +| [options.m1] | number | 1.0 | the level of sharpening to apply to "flat" areas, between 0 and 1000000 | +| [options.m2] | number | 2.0 | the level of sharpening to apply to "jagged" areas, between 0 and 1000000 | +| [options.x1] | number | 2.0 | threshold between "flat" and "jagged", between 0 and 1000000 | +| [options.y2] | number | 10.0 | maximum amount of brightening, between 0 and 1000000 | +| [options.y3] | number | 20.0 | maximum amount of darkening, between 0 and 1000000 | +| [flat] | number | | (deprecated) see `options.m1`. | +| [jagged] | number | | (deprecated) see `options.m2`. | + +**Example** +```js const data = await sharp(input).sharpen().toBuffer(); ``` - -```javascript +**Example** +```js const data = await sharp(input).sharpen({ sigma: 2 }).toBuffer(); ``` - -```javascript +**Example** +```js const data = await sharp(input) .sharpen({ sigma: 2, @@ -195,87 +189,83 @@ const data = await sharp(input) .toBuffer(); ``` -* Throws **[Error][5]** Invalid parameters - -Returns **Sharp** ## median - Apply median filter. When used without parameters the default window is 3x3. -### Parameters -* `size` **[number][1]** square mask size: size x size (optional, default `3`) +**Throws**: -### Examples +- Error Invalid parameters -```javascript + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [size] | number | 3 | square mask size: size x size | + +**Example** +```js const output = await sharp(input).median().toBuffer(); ``` - -```javascript +**Example** +```js const output = await sharp(input).median(5).toBuffer(); ``` -* Throws **[Error][5]** Invalid parameters - -Returns **Sharp** ## blur - Blur the image. When used without parameters, performs a fast 3x3 box blur (equivalent to a box linear filter). When a `sigma` is provided, performs a slower, more accurate Gaussian blur. -### Parameters -* `sigma` **[number][1]?** a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. +**Throws**: -### Examples +- Error Invalid parameters -```javascript + +| Param | Type | Description | +| --- | --- | --- | +| [sigma] | number | a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. | + +**Example** +```js const boxBlurred = await sharp(input) .blur() .toBuffer(); ``` - -```javascript +**Example** +```js const gaussianBlurred = await sharp(input) .blur(5) .toBuffer(); ``` -* Throws **[Error][5]** Invalid parameters - -Returns **Sharp** ## flatten - Merge alpha transparency channel, if any, with a background, then remove the alpha channel. -See also [removeAlpha][9]. +See also [removeAlpha](/api-channel#removealpha). -### Parameters -* `options` **[Object][2]?** - * `options.background` **([string][3] | [Object][2])** background colour, parsed by the [color][4] module, defaults to black. (optional, default `{r:0,g:0,b:0}`) +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [options] | Object | | | +| [options.background] | string \| Object | "{r: 0, g: 0, b: 0}" | background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black. | -### Examples - -```javascript +**Example** +```js await sharp(rgbaInput) .flatten({ background: '#F0A703' }) .toBuffer(); ``` -Returns **Sharp** ## gamma - Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of `1/gamma` then increasing the encoding (brighten) post-resize at a factor of `gamma`. This can improve the perceived brightness of a resized image in non-linear colour spaces. @@ -284,95 +274,95 @@ when applying a gamma correction. Supply a second argument to use a different output gamma value, otherwise the first value is used in both cases. -### Parameters -* `gamma` **[number][1]** value between 1.0 and 3.0. (optional, default `2.2`) -* `gammaOut` **[number][1]?** value between 1.0 and 3.0. (optional, defaults to same as `gamma`) +**Throws**: - +- Error Invalid parameters + + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [gamma] | number | 2.2 | value between 1.0 and 3.0. | +| [gammaOut] | number | | value between 1.0 and 3.0. (optional, defaults to same as `gamma`) | -* Throws **[Error][5]** Invalid parameters -Returns **Sharp** ## negate - Produce the "negative" of the image. -### Parameters -* `options` **[Object][2]?** - * `options.alpha` **[Boolean][6]** Whether or not to negate any alpha channel (optional, default `true`) +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [options] | Object | | | +| [options.alpha] | Boolean | true | Whether or not to negate any alpha channel | -### Examples - -```javascript +**Example** +```js const output = await sharp(input) .negate() .toBuffer(); ``` - -```javascript +**Example** +```js const output = await sharp(input) .negate({ alpha: false }) .toBuffer(); ``` -Returns **Sharp** ## normalise - Enhance output image contrast by stretching its luminance to cover the full dynamic range. -### Parameters -* `normalise` **[Boolean][6]** (optional, default `true`) -### Examples +| Param | Type | Default | +| --- | --- | --- | +| [normalise] | Boolean | true | -```javascript +**Example** +```js const output = await sharp(input).normalise().toBuffer(); ``` -Returns **Sharp** ## normalize - Alternative spelling of normalise. -### Parameters -* `normalize` **[Boolean][6]** (optional, default `true`) -### Examples +| Param | Type | Default | +| --- | --- | --- | +| [normalize] | Boolean | true | -```javascript +**Example** +```js const output = await sharp(input).normalize().toBuffer(); ``` -Returns **Sharp** ## clahe - Perform contrast limiting adaptive histogram equalization -[CLAHE][10]. +[CLAHE](https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE). This will, in general, enhance the clarity of the image by bringing out darker details. -### Parameters -* `options` **[Object][2]** +**Throws**: - * `options.width` **[number][1]** integer width of the region in pixels. - * `options.height` **[number][1]** integer height of the region in pixels. - * `options.maxSlope` **[number][1]** maximum value for the slope of the - cumulative histogram. A value of 0 disables contrast limiting. Valid values - are integers in the range 0-100 (inclusive) (optional, default `3`) +- Error Invalid parameters -### Examples +**Since**: 0.28.3 -```javascript +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| options | Object | | | +| options.width | number | | integer width of the region in pixels. | +| options.height | number | | integer height of the region in pixels. | +| [options.maxSlope] | number | 3 | maximum value for the slope of the cumulative histogram. A value of 0 disables contrast limiting. Valid values are integers in the range 0-100 (inclusive) | + +**Example** +```js const output = await sharp(input) .clahe({ width: 3, @@ -381,31 +371,27 @@ const output = await sharp(input) .toBuffer(); ``` -* Throws **[Error][5]** Invalid parameters - -Returns **Sharp** - -**Meta** - -* **since**: 0.28.3 ## convolve - Convolve the image with the specified kernel. -### Parameters -* `kernel` **[Object][2]** +**Throws**: - * `kernel.width` **[number][1]** width of the kernel in pixels. - * `kernel.height` **[number][1]** height of the kernel in pixels. - * `kernel.kernel` **[Array][7]<[number][1]>** Array of length `width*height` containing the kernel values. - * `kernel.scale` **[number][1]** the scale of the kernel in pixels. (optional, default `sum`) - * `kernel.offset` **[number][1]** the offset of the kernel in pixels. (optional, default `0`) +- Error Invalid parameters -### Examples -```javascript +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| kernel | Object | | | +| kernel.width | number | | width of the kernel in pixels. | +| kernel.height | number | | height of the kernel in pixels. | +| kernel.kernel | Array.<number> | | Array of length `width*height` containing the kernel values. | +| [kernel.scale] | number | sum | the scale of the kernel in pixels. | +| [kernel.offset] | number | 0 | the offset of the kernel in pixels. | + +**Example** +```js sharp(input) .convolve({ width: 3, @@ -419,74 +405,74 @@ sharp(input) }); ``` -* Throws **[Error][5]** Invalid parameters - -Returns **Sharp** ## threshold - Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0. -### Parameters -* `threshold` **[number][1]** a value in the range 0-255 representing the level at which the threshold will be applied. (optional, default `128`) -* `options` **[Object][2]?** +**Throws**: - * `options.greyscale` **[Boolean][6]** convert to single channel greyscale. (optional, default `true`) - * `options.grayscale` **[Boolean][6]** alternative spelling for greyscale. (optional, default `true`) +- Error Invalid parameters - -* Throws **[Error][5]** Invalid parameters +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [threshold] | number | 128 | a value in the range 0-255 representing the level at which the threshold will be applied. | +| [options] | Object | | | +| [options.greyscale] | Boolean | true | convert to single channel greyscale. | +| [options.grayscale] | Boolean | true | alternative spelling for greyscale. | + -Returns **Sharp** ## boolean - Perform a bitwise boolean operation with operand image. This operation creates an output image where each pixel is the result of the selected bitwise boolean `operation` between the corresponding pixels of the input images. -### Parameters -* `operand` **([Buffer][11] | [string][3])** Buffer containing image data or string containing the path to an image file. -* `operator` **[string][3]** one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. -* `options` **[Object][2]?** +**Throws**: - * `options.raw` **[Object][2]?** describes operand when using raw pixel data. +- Error Invalid parameters - * `options.raw.width` **[number][1]?** - * `options.raw.height` **[number][1]?** - * `options.raw.channels` **[number][1]?** - +| Param | Type | Description | +| --- | --- | --- | +| operand | Buffer \| string | Buffer containing image data or string containing the path to an image file. | +| operator | string | one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. | +| [options] | Object | | +| [options.raw] | Object | describes operand when using raw pixel data. | +| [options.raw.width] | number | | +| [options.raw.height] | number | | +| [options.raw.channels] | number | | -* Throws **[Error][5]** Invalid parameters -Returns **Sharp** ## linear - -Apply the linear formula `a` \* input + `b` to the image to adjust image levels. +Apply the linear formula `a` * input + `b` to the image to adjust image levels. When a single number is provided, it will be used for all image channels. When an array of numbers is provided, the array length must match the number of channels. -### Parameters -* `a` **([number][1] | [Array][7]<[number][1]>)** multiplier (optional, default `[]`) -* `b` **([number][1] | [Array][7]<[number][1]>)** offset (optional, default `[]`) +**Throws**: -### Examples +- Error Invalid parameters -```javascript + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [a] | number \| Array.<number> | [] | multiplier | +| [b] | number \| Array.<number> | [] | offset | + +**Example** +```js await sharp(input) .linear(0.5, 2) .toBuffer(); ``` - -```javascript +**Example** +```js await sharp(rgbInput) .linear( [0.25, 0.5, 0.75], @@ -495,21 +481,23 @@ await sharp(rgbInput) .toBuffer(); ``` -* Throws **[Error][5]** Invalid parameters - -Returns **Sharp** ## recomb - Recomb the image with the specified matrix. -### Parameters -* `inputMatrix` **[Array][7]<[Array][7]<[number][1]>>** 3x3 Recombination matrix +**Throws**: -### Examples +- Error Invalid parameters -```javascript +**Since**: 0.21.1 + +| Param | Type | Description | +| --- | --- | --- | +| inputMatrix | Array.<Array.<number>> | 3x3 Recombination matrix | + +**Example** +```js sharp(input) .recomb([ [0.3588, 0.7044, 0.1368], @@ -523,32 +511,25 @@ sharp(input) }); ``` -* Throws **[Error][5]** Invalid parameters - -Returns **Sharp** - -**Meta** - -* **since**: 0.21.1 ## modulate - Transforms the image using brightness, saturation, hue rotation, and lightness. Brightness and lightness both operate on luminance, with the difference being that brightness is multiplicative whereas lightness is additive. -### Parameters -* `options` **[Object][2]?** +**Since**: 0.22.1 - * `options.brightness` **[number][1]?** Brightness multiplier - * `options.saturation` **[number][1]?** Saturation multiplier - * `options.hue` **[number][1]?** Degrees for hue rotation - * `options.lightness` **[number][1]?** Lightness addend +| Param | Type | Description | +| --- | --- | --- | +| [options] | Object | | +| [options.brightness] | number | Brightness multiplier | +| [options.saturation] | number | Saturation multiplier | +| [options.hue] | number | Degrees for hue rotation | +| [options.lightness] | number | Lightness addend | -### Examples - -```javascript +**Example** +```js // increase brightness by a factor of 2 const output = await sharp(input) .modulate({ @@ -556,8 +537,8 @@ const output = await sharp(input) }) .toBuffer(); ``` - -```javascript +**Example** +```js // hue-rotate by 180 degrees const output = await sharp(input) .modulate({ @@ -565,8 +546,8 @@ const output = await sharp(input) }) .toBuffer(); ``` - -```javascript +**Example** +```js // increase lightness by +50 const output = await sharp(input) .modulate({ @@ -574,8 +555,8 @@ const output = await sharp(input) }) .toBuffer(); ``` - -```javascript +**Example** +```js // decreate brightness and saturation while also hue-rotating by 90 degrees const output = await sharp(input) .modulate({ @@ -584,32 +565,4 @@ const output = await sharp(input) hue: 90, }) .toBuffer(); -``` - -Returns **Sharp** - -**Meta** - -* **since**: 0.22.1 - -[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number - -[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object - -[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String - -[4]: https://www.npmjs.org/package/color - -[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error - -[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean - -[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array - -[8]: https://www.libvips.org/API/current/libvips-convolution.html#vips-sharpen - -[9]: /api-channel#removealpha - -[10]: https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE - -[11]: https://nodejs.org/api/buffer.html +``` \ No newline at end of file diff --git a/docs/api-output.md b/docs/api-output.md index 6e10ff81..9dbd7669 100644 --- a/docs/api-output.md +++ b/docs/api-output.md @@ -1,7 +1,4 @@ - - ## toFile - Write output image data to a file. If an explicit output format is not selected, it will be inferred from the extension, @@ -9,92 +6,90 @@ 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][1] for control over this. +See [withMetadata](#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][2]** the path to write the image data to. -* `callback` **[Function][3]?** 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`. - May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. +**Returns**: Promise.<Object> - - when no callback is provided +**Throws**: -### Examples +- Error Invalid parameters -```javascript + +| 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`. May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. | + +**Example** +```js sharp(input) .toFile('output.png', (err, info) => { ... }); ``` - -```javascript +**Example** +```js sharp(input) .toFile('output.png') .then(info => { ... }) .catch(err => { ... }); ``` -* Throws **[Error][4]** Invalid parameters - -Returns **[Promise][5]<[Object][6]>** 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][7] or one of the format-specific functions such as [jpeg][8], [png][9] etc. to set the output format. +Use [toFormat](#toFormat) or one of the format-specific functions such as [jpeg](#jpeg), [png](#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][1] for control over this. +See [withMetadata](#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. +- `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. -### Parameters -* `options` **[Object][6]?** +**Returns**: Promise.<Buffer> - - when no callback is provided - * `options.resolveWithObject` **[boolean][10]?** Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`. -* `callback` **[Function][3]?** +| 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 | | -### Examples - -```javascript +**Example** +```js sharp(input) .toBuffer((err, data, info) => { ... }); ``` - -```javascript +**Example** +```js sharp(input) .toBuffer() .then(data => { ... }) .catch(err => { ... }); ``` - -```javascript +**Example** +```js sharp(input) .png() .toBuffer({ resolveWithObject: true }) .then(({ data, info }) => { ... }) .catch(err => { ... }); ``` - -```javascript +**Example** +```js const { data, info } = await sharp('my-image.jpg') // output the raw pixels .raw() @@ -111,10 +106,8 @@ await sharp(pixelArray, { raw: { width, height, channels } }) .toFile('my-changed-image.jpg'); ``` -Returns **[Promise][5]<[Buffer][11]>** 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. @@ -124,25 +117,29 @@ sRGB colour space and strip all metadata, including the removal of any ICC profi EXIF metadata is unsupported for TIFF output. -### Parameters -* `options` **[Object][6]?** +**Throws**: - * `options.orientation` **[number][12]?** value between 1 and 8, used to update the EXIF `Orientation` tag. - * `options.icc` **[string][2]?** filesystem path to output ICC profile, defaults to sRGB. - * `options.exif` **[Object][6]<[Object][6]>** Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. (optional, default `{}`) - * `options.density` **[number][12]?** Number of pixels per inch (DPI). +- Error Invalid parameters -### Examples -```javascript +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [options] | Object | | | +| [options.orientation] | number | | value between 1 and 8, used to update the EXIF `Orientation` 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. | +| [options.density] | number | | Number of pixels per inch (DPI). | + +**Example** +```js sharp('input.jpg') .withMetadata() .toFile('output-with-metadata.jpg') .then(info => { ... }); ``` - -```javascript +**Example** +```js // Set "IFD0-Copyright" in output EXIF metadata const data = await sharp(input) .withMetadata({ @@ -154,65 +151,66 @@ const data = await sharp(input) }) .toBuffer(); ``` - -```javascript +**Example** +```js // Set output metadata to 96 DPI const data = await sharp(input) .withMetadata({ density: 96 }) .toBuffer(); ``` -* Throws **[Error][4]** Invalid parameters - -Returns **Sharp** ## toFormat - Force output to a given format. -### Parameters -* `format` **([string][2] | [Object][6])** as a string or an Object with an 'id' attribute -* `options` **[Object][6]** output options +**Throws**: -### Examples +- Error unsupported format or options -```javascript + +| Param | Type | Description | +| --- | --- | --- | +| format | string \| Object | as a string or an Object with an 'id' attribute | +| options | Object | output options | + +**Example** +```js // Convert any input to PNG output const data = await sharp(input) .toFormat('png') .toBuffer(); ``` -* Throws **[Error][4]** unsupported format or options - -Returns **Sharp** ## jpeg - Use these JPEG options for output image. -### Parameters -* `options` **[Object][6]?** output options +**Throws**: - * `options.quality` **[number][12]** quality, integer 1-100 (optional, default `80`) - * `options.progressive` **[boolean][10]** use progressive (interlace) scan (optional, default `false`) - * `options.chromaSubsampling` **[string][2]** 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][10]** optimise Huffman coding tables (optional, default `true`) - * `options.optimizeCoding` **[boolean][10]** alternative spelling of optimiseCoding (optional, default `true`) - * `options.mozjpeg` **[boolean][10]** use mozjpeg defaults, equivalent to `{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }` (optional, default `false`) - * `options.trellisQuantisation` **[boolean][10]** apply trellis quantisation (optional, default `false`) - * `options.overshootDeringing` **[boolean][10]** apply overshoot deringing (optional, default `false`) - * `options.optimiseScans` **[boolean][10]** optimise progressive scans, forces progressive (optional, default `false`) - * `options.optimizeScans` **[boolean][10]** alternative spelling of optimiseScans (optional, default `false`) - * `options.quantisationTable` **[number][12]** quantization table to use, integer 0-8 (optional, default `0`) - * `options.quantizationTable` **[number][12]** alternative spelling of quantisationTable (optional, default `0`) - * `options.force` **[boolean][10]** force JPEG output, otherwise attempt to use input format (optional, default `true`) +- Error Invalid options -### Examples -```javascript +| 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** +```js // Convert any input to very high quality JPEG output const data = await sharp(input) .jpeg({ @@ -221,234 +219,186 @@ const data = await sharp(input) }) .toBuffer(); ``` - -```javascript +**Example** +```js // Use mozjpeg to reduce output JPEG file size (slower) const data = await sharp(input) .jpeg({ mozjpeg: true }) .toBuffer(); ``` -* Throws **[Error][4]** 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][6]?** +**Throws**: - * `options.progressive` **[boolean][10]** use progressive (interlace) scan (optional, default `false`) - * `options.compressionLevel` **[number][12]** zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest) (optional, default `6`) - * `options.adaptiveFiltering` **[boolean][10]** use adaptive row filtering (optional, default `false`) - * `options.palette` **[boolean][10]** quantise to a palette-based image with alpha transparency support (optional, default `false`) - * `options.quality` **[number][12]** use the lowest number of colours needed to achieve given quality, sets `palette` to `true` (optional, default `100`) - * `options.effort` **[number][12]** CPU effort, between 1 (fastest) and 10 (slowest), sets `palette` to `true` (optional, default `7`) - * `options.colours` **[number][12]** maximum number of palette entries, sets `palette` to `true` (optional, default `256`) - * `options.colors` **[number][12]** alternative spelling of `options.colours`, sets `palette` to `true` (optional, default `256`) - * `options.dither` **[number][12]** level of Floyd-Steinberg error diffusion, sets `palette` to `true` (optional, default `1.0`) - * `options.force` **[boolean][10]** force PNG output, otherwise attempt to use input format (optional, default `true`) +- Error Invalid options -### Examples -```javascript +| 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** +```js // Convert any input to full colour PNG output const data = await sharp(input) .png() .toBuffer(); ``` - -```javascript +**Example** +```js // Convert any input to indexed PNG output (slower) const data = await sharp(input) .png({ palette: true }) .toBuffer(); ``` -* Throws **[Error][4]** Invalid options - -Returns **Sharp** ## webp - Use these WebP options for output image. -### Parameters -* `options` **[Object][6]?** output options +**Throws**: - * `options.quality` **[number][12]** quality, integer 1-100 (optional, default `80`) - * `options.alphaQuality` **[number][12]** quality of alpha layer, integer 0-100 (optional, default `100`) - * `options.lossless` **[boolean][10]** use lossless compression mode (optional, default `false`) - * `options.nearLossless` **[boolean][10]** use near\_lossless compression mode (optional, default `false`) - * `options.smartSubsample` **[boolean][10]** use high quality chroma subsampling (optional, default `false`) - * `options.effort` **[number][12]** CPU effort, between 0 (fastest) and 6 (slowest) (optional, default `4`) - * `options.loop` **[number][12]** number of animation iterations, use 0 for infinite animation (optional, default `0`) - * `options.delay` **([number][12] | [Array][13]<[number][12]>)?** delay(s) between animation frames (in milliseconds) - * `options.minSize` **[boolean][10]** prevent use of animation key frames to minimise file size (slow) (optional, default `false`) - * `options.mixed` **[boolean][10]** allow mixture of lossy and lossless animation frames (slow) (optional, default `false`) - * `options.force` **[boolean][10]** force WebP output, otherwise attempt to use input format (optional, default `true`) +- Error Invalid options -### Examples -```javascript +| 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.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** +```js // Convert any input to lossless WebP output const data = await sharp(input) .webp({ lossless: true }) .toBuffer(); ``` - -```javascript +**Example** +```js // Optimise the file size of an animated WebP const outputWebp = await sharp(inputWebp, { animated: true }) .webp({ effort: 6 }) .toBuffer(); ``` -* Throws **[Error][4]** Invalid options - -Returns **Sharp** ## gif - 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. -### Parameters -* `options` **[Object][6]?** output options +**Throws**: - * `options.reuse` **[boolean][10]** re-use existing palette, otherwise generate new (slow) (optional, default `true`) - * `options.progressive` **[boolean][10]** use progressive (interlace) scan (optional, default `false`) - * `options.colours` **[number][12]** maximum number of palette entries, including transparency, between 2 and 256 (optional, default `256`) - * `options.colors` **[number][12]** alternative spelling of `options.colours` (optional, default `256`) - * `options.effort` **[number][12]** CPU effort, between 1 (fastest) and 10 (slowest) (optional, default `7`) - * `options.dither` **[number][12]** level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) (optional, default `1.0`) - * `options.interFrameMaxError` **[number][12]** maximum inter-frame error for transparency, between 0 (lossless) and 32 (optional, default `0`) - * `options.interPaletteMaxError` **[number][12]** maximum inter-palette error for palette reuse, between 0 and 256 (optional, default `3`) - * `options.loop` **[number][12]** number of animation iterations, use 0 for infinite animation (optional, default `0`) - * `options.delay` **([number][12] | [Array][13]<[number][12]>)?** delay(s) between animation frames (in milliseconds) - * `options.force` **[boolean][10]** force GIF output, otherwise attempt to use input format (optional, default `true`) +- Error Invalid options -### Examples +**Since**: 0.30.0 -```javascript +| 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** +```js // Convert PNG to GIF await sharp(pngBuffer) .gif() .toBuffer(); ``` - -```javascript +**Example** +```js // Convert animated WebP to animated GIF await sharp('animated.webp', { animated: true }) .toFile('animated.gif'); ``` - -```javascript +**Example** +```js // 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(); ``` - -```javascript +**Example** +```js // Lossy file size reduction of animated GIF await sharp('in.gif', { animated: true }) .gif({ interFrameMaxError: 8 }) .toFile('optim.gif'); ``` -* Throws **[Error][4]** 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][14]. - -### Parameters - -* `options` **[Object][6]?** output options - - * `options.quality` **[number][12]** quality, integer 1-100 (optional, default `80`) - * `options.lossless` **[boolean][10]** use lossless compression mode (optional, default `false`) - * `options.tileWidth` **[number][12]** horizontal tile size (optional, default `512`) - * `options.tileHeight` **[number][12]** vertical tile size (optional, default `512`) - * `options.chromaSubsampling` **[string][2]** set to '4:2:0' to use chroma subsampling (optional, default `'4:4:4'`) - -### Examples - -```javascript -// Convert any input to lossless JP2 output -const data = await sharp(input) - .jp2({ lossless: true }) - .toBuffer(); -``` - -```javascript -// Convert any input to very high quality JP2 output -const data = await sharp(input) - .jp2({ - quality: 100, - chromaSubsampling: '4:4:4' - }) - .toBuffer(); -``` - -* Throws **[Error][4]** 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][1] instead of providing `xres` and `yres` in pixels/mm. +The `density` can be set in pixels/inch via [withMetadata](#withMetadata) instead of providing `xres` and `yres` in pixels/mm. -### Parameters -* `options` **[Object][6]?** output options +**Throws**: - * `options.quality` **[number][12]** quality, integer 1-100 (optional, default `80`) - * `options.force` **[boolean][10]** force TIFF output, otherwise attempt to use input format (optional, default `true`) - * `options.compression` **[string][2]** compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k (optional, default `'jpeg'`) - * `options.predictor` **[string][2]** compression predictor options: none, horizontal, float (optional, default `'horizontal'`) - * `options.pyramid` **[boolean][10]** write an image pyramid (optional, default `false`) - * `options.tile` **[boolean][10]** write a tiled tiff (optional, default `false`) - * `options.tileWidth` **[number][12]** horizontal tile size (optional, default `256`) - * `options.tileHeight` **[number][12]** vertical tile size (optional, default `256`) - * `options.xres` **[number][12]** horizontal resolution in pixels/mm (optional, default `1.0`) - * `options.yres` **[number][12]** vertical resolution in pixels/mm (optional, default `1.0`) - * `options.resolutionUnit` **[string][2]** resolution unit options: inch, cm (optional, default `'inch'`) - * `options.bitdepth` **[number][12]** reduce bitdepth to 1, 2 or 4 bit (optional, default `8`) +- Error Invalid options -### Examples -```javascript +| 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 | + +**Example** +```js // Convert SVG input to LZW-compressed, 1 bit per pixel TIFF output sharp('input.svg') .tiff({ @@ -459,12 +409,8 @@ sharp('input.svg') .then(info => { ... }); ``` -* Throws **[Error][4]** Invalid options - -Returns **Sharp** ## avif - Use these AVIF options for output image. Whilst it is possible to create AVIF images smaller than 16x16 pixels, @@ -472,124 +418,119 @@ most web browsers do not display these properly. AVIF image sequences are not supported. -### Parameters -* `options` **[Object][6]?** output options +**Throws**: - * `options.quality` **[number][12]** quality, integer 1-100 (optional, default `50`) - * `options.lossless` **[boolean][10]** use lossless compression (optional, default `false`) - * `options.effort` **[number][12]** CPU effort, between 0 (fastest) and 9 (slowest) (optional, default `4`) - * `options.chromaSubsampling` **[string][2]** set to '4:2:0' to use chroma subsampling (optional, default `'4:4:4'`) +- Error Invalid options -### Examples +**Since**: 0.27.0 -```javascript +| 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** +```js const data = await sharp(input) .avif({ effort: 2 }) .toBuffer(); ``` - -```javascript +**Example** +```js const data = await sharp(input) .avif({ lossless: true }) .toBuffer(); ``` -* Throws **[Error][4]** Invalid options - -Returns **Sharp** - -**Meta** - -* **since**: 0.27.0 ## heif - 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. -### Parameters -* `options` **[Object][6]?** output options +**Throws**: - * `options.quality` **[number][12]** quality, integer 1-100 (optional, default `50`) - * `options.compression` **[string][2]** compression format: av1, hevc (optional, default `'av1'`) - * `options.lossless` **[boolean][10]** use lossless compression (optional, default `false`) - * `options.effort` **[number][12]** CPU effort, between 0 (fastest) and 9 (slowest) (optional, default `4`) - * `options.chromaSubsampling` **[string][2]** set to '4:2:0' to use chroma subsampling (optional, default `'4:4:4'`) +- Error Invalid options -### Examples +**Since**: 0.23.0 -```javascript +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [options] | Object | | output options | +| [options.quality] | number | 50 | quality, integer 1-100 | +| [options.compression] | string | "'av1'" | compression format: av1, hevc | +| [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** +```js const data = await sharp(input) .heif({ compression: 'hevc' }) .toBuffer(); ``` -* Throws **[Error][4]** Invalid options - -Returns **Sharp** - -**Meta** - -* **since**: 0.23.0 ## jxl - 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][14]. +[installing a custom libvips](https://sharp.pixelplumbing.com/install#custom-libvips). Image metadata (EXIF, XMP) is unsupported. -### Parameters -* `options` **[Object][6]?** output options +**Throws**: - * `options.distance` **[number][12]** maximum encoding error, between 0 (highest quality) and 15 (lowest quality) (optional, default `1.0`) - * `options.quality` **[number][12]?** calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified - * `options.decodingTier` **[number][12]** target decode speed tier, between 0 (highest quality) and 4 (lowest quality) (optional, default `0`) - * `options.lossless` **[boolean][10]** use lossless compression (optional, default `false`) - * `options.effort` **[number][12]** CPU effort, between 3 (fastest) and 9 (slowest) (optional, default `7`) +- Error Invalid options - +**Since**: 0.31.3 -* Throws **[Error][4]** Invalid options +| 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) | -Returns **Sharp** -**Meta** - -* **since**: 0.31.3 ## 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][6]?** output options +**Throws**: - * `options.depth` **[string][2]** bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex (optional, default `'uchar'`) +- Error Invalid options -### Examples -```javascript +| 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** +```js // Extract raw, unsigned 8-bit RGB pixel data from JPEG input const { data, info } = await sharp('input.jpg') .raw() .toBuffer({ resolveWithObject: true }); ``` - -```javascript +**Example** +```js // Extract alpha channel as raw, unsigned 16-bit pixel data from PNG input const data = await sharp('input.png') .ensureAlpha() @@ -599,10 +540,8 @@ const data = await sharp('input.png') .toBuffer(); ``` -* Throws **[Error][4]** 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. @@ -610,26 +549,30 @@ Use a `.zip` or `.szi` file extension with `toFile` to write to a compressed arc The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`. -### Parameters -* `options` **[Object][6]?** +**Throws**: - * `options.size` **[number][12]** tile size in pixels, a value between 1 and 8192. (optional, default `256`) - * `options.overlap` **[number][12]** tile overlap in pixels, a value between 0 and 8192. (optional, default `0`) - * `options.angle` **[number][12]** tile angle of rotation, must be a multiple of 90. (optional, default `0`) - * `options.background` **([string][2] | [Object][6])** background colour, parsed by the [color][15] module, defaults to white without transparency. (optional, default `{r:255,g:255,b:255,alpha:1}`) - * `options.depth` **[string][2]?** how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout. - * `options.skipBlanks` **[number][12]** 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][2]** tile container, with value `fs` (filesystem) or `zip` (compressed file). (optional, default `'fs'`) - * `options.layout` **[string][2]** filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`. (optional, default `'dz'`) - * `options.centre` **[boolean][10]** centre image in tile. (optional, default `false`) - * `options.center` **[boolean][10]** alternative spelling of centre. (optional, default `false`) - * `options.id` **[string][2]** when `layout` is `iiif`/`iiif3`, sets the `@id`/`id` attribute of `info.json` (optional, default `'https://example.com/iiif'`) - * `options.basename` **[string][2]?** the name of the directory within the zip file when container is `zip`. +- Error Invalid parameters -### Examples -```javascript +| 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](https://www.npmjs.org/package/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, a value 0 - 255 for 8-bit images or 0 - 65535 for 16-bit images | +| [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'" | 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** +```js sharp('input.tiff') .png() .tile({ @@ -640,41 +583,38 @@ sharp('input.tiff') // output_files contains 512x512 tiles grouped by zoom level }); ``` - -```javascript +**Example** +```js const zipFileWithTiles = await sharp(input) .tile({ basename: "tiles" }) .toBuffer(); ``` - -```javascript +**Example** +```js const iiififier = sharp().tile({ layout: "iiif" }); readableStream .pipe(iiififier) .pipe(writeableStream); ``` -* Throws **[Error][4]** 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 -* `options` **[Object][6]** +**Since**: 0.29.2 - * `options.seconds` **[number][12]** Number of seconds after which processing will be stopped +| Param | Type | Description | +| --- | --- | --- | +| options | Object | | +| options.seconds | number | Number of seconds after which processing will be stopped | -### Examples - -```javascript +**Example** +```js // Ensure processing takes no longer than 3 seconds try { const data = await sharp(input) @@ -684,40 +624,4 @@ try { } catch (err) { if (err.message.includes('timeout')) { ... } } -``` - -Returns **Sharp** - -**Meta** - -* **since**: 0.29.2 - -[1]: #withmetadata - -[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String - -[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function - -[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error - -[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise - -[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object - -[7]: #toformat - -[8]: #jpeg - -[9]: #png - -[10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean - -[11]: https://nodejs.org/api/buffer.html - -[12]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number - -[13]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array - -[14]: https://sharp.pixelplumbing.com/install#custom-libvips - -[15]: https://www.npmjs.org/package/color +``` \ No newline at end of file diff --git a/docs/api-resize.md b/docs/api-resize.md index 799c5aa5..af8c2c6b 100644 --- a/docs/api-resize.md +++ b/docs/api-resize.md @@ -1,65 +1,62 @@ - - ## resize - Resize image to `width`, `height` or `width x height`. When both a `width` and `height` are provided, the possible methods by which the image should **fit** these are: +- `cover`: (default) Preserving aspect ratio, ensure the image covers both provided dimensions by cropping/clipping to fit. +- `contain`: Preserving aspect ratio, contain within both provided dimensions using "letterboxing" where necessary. +- `fill`: Ignore the aspect ratio of the input and stretch to both provided dimensions. +- `inside`: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified. +- `outside`: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified. -* `cover`: (default) Preserving aspect ratio, ensure the image covers both provided dimensions by cropping/clipping to fit. -* `contain`: Preserving aspect ratio, contain within both provided dimensions using "letterboxing" where necessary. -* `fill`: Ignore the aspect ratio of the input and stretch to both provided dimensions. -* `inside`: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified. -* `outside`: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified. - -Some of these values are based on the [object-fit][1] CSS property. +Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property. Examples of various values for the fit property when resizing When using a **fit** of `cover` or `contain`, the default **position** is `centre`. Other options are: +- `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`. +- `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`. +- `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy. -* `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`. -* `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`. -* `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy. - -Some of these values are based on the [object-position][2] CSS property. +Some of these values are based on the [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS property. The experimental strategy-based approach resizes so one dimension is at its target length then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy. - -* `entropy`: focus on the region with the highest [Shannon entropy][3]. -* `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones. +- `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29). +- `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones. Possible interpolation kernels are: - -* `nearest`: Use [nearest neighbour interpolation][4]. -* `cubic`: Use a [Catmull-Rom spline][5]. -* `mitchell`: Use a [Mitchell-Netravali spline][6]. -* `lanczos2`: Use a [Lanczos kernel][7] with `a=2`. -* `lanczos3`: Use a Lanczos kernel with `a=3` (the default). +- `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). +- `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline). +- `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf). +- `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`. +- `lanczos3`: Use a Lanczos kernel with `a=3` (the default). Only one resize can occur per pipeline. Previous calls to `resize` in the same pipeline will be ignored. -### Parameters -* `width` **[number][8]?** pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height. -* `height` **[number][8]?** pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width. -* `options` **[Object][9]?** +**Throws**: - * `options.width` **[String][10]?** alternative means of specifying `width`. If both are present this takes priority. - * `options.height` **[String][10]?** alternative means of specifying `height`. If both are present this takes priority. - * `options.fit` **[String][10]** how the image should be resized to fit both provided dimensions, one of `cover`, `contain`, `fill`, `inside` or `outside`. (optional, default `'cover'`) - * `options.position` **[String][10]** position, gravity or strategy to use when `fit` is `cover` or `contain`. (optional, default `'centre'`) - * `options.background` **([String][10] | [Object][9])** background colour when `fit` is `contain`, parsed by the [color][11] module, defaults to black without transparency. (optional, default `{r:0,g:0,b:0,alpha:1}`) - * `options.kernel` **[String][10]** the kernel to use for image reduction. (optional, default `'lanczos3'`) - * `options.withoutEnlargement` **[Boolean][12]** do not enlarge if the width *or* height are already less than the specified dimensions, equivalent to GraphicsMagick's `>` geometry option. (optional, default `false`) - * `options.withoutReduction` **[Boolean][12]** do not reduce if the width *or* height are already greater than the specified dimensions, equivalent to GraphicsMagick's `<` geometry option. (optional, default `false`) - * `options.fastShrinkOnLoad` **[Boolean][12]** take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern on some images. (optional, default `true`) +- Error Invalid parameters -### Examples -```javascript +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [width] | number | | pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height. | +| [height] | number | | pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width. | +| [options] | Object | | | +| [options.width] | String | | alternative means of specifying `width`. If both are present this takes priority. | +| [options.height] | String | | alternative means of specifying `height`. If both are present this takes priority. | +| [options.fit] | String | 'cover' | how the image should be resized to fit both provided dimensions, one of `cover`, `contain`, `fill`, `inside` or `outside`. | +| [options.position] | String | 'centre' | position, gravity or strategy to use when `fit` is `cover` or `contain`. | +| [options.background] | String \| Object | {r: 0, g: 0, b: 0, alpha: 1} | background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency. | +| [options.kernel] | String | 'lanczos3' | the kernel to use for image reduction. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load. | +| [options.withoutEnlargement] | Boolean | false | do not enlarge if the width *or* height are already less than the specified dimensions, equivalent to GraphicsMagick's `>` geometry option. | +| [options.withoutReduction] | Boolean | false | do not reduce if the width *or* height are already greater than the specified dimensions, equivalent to GraphicsMagick's `<` geometry option. | +| [options.fastShrinkOnLoad] | Boolean | true | take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern on some images. | + +**Example** +```js sharp(input) .resize({ width: 100 }) .toBuffer() @@ -67,8 +64,8 @@ sharp(input) // 100 pixels wide, auto-scaled height }); ``` - -```javascript +**Example** +```js sharp(input) .resize({ height: 100 }) .toBuffer() @@ -76,8 +73,8 @@ sharp(input) // 100 pixels high, auto-scaled width }); ``` - -```javascript +**Example** +```js sharp(input) .resize(200, 300, { kernel: sharp.kernel.nearest, @@ -92,8 +89,8 @@ sharp(input) // contained within the north-east corner of a semi-transparent white canvas }); ``` - -```javascript +**Example** +```js const transformer = sharp() .resize({ width: 200, @@ -107,8 +104,8 @@ readableStream .pipe(transformer) .pipe(writableStream); ``` - -```javascript +**Example** +```js sharp(input) .resize(200, 200, { fit: sharp.fit.inside, @@ -122,8 +119,8 @@ sharp(input) // and no larger than the input image }); ``` - -```javascript +**Example** +```js sharp(input) .resize(200, 200, { fit: sharp.fit.outside, @@ -137,8 +134,8 @@ sharp(input) // and no smaller than the input image }); ``` - -```javascript +**Example** +```js const scaleByHalf = await sharp(input) .metadata() .then(({ width }) => sharp(input) @@ -147,28 +144,28 @@ const scaleByHalf = await sharp(input) ); ``` -* Throws **[Error][13]** Invalid parameters - -Returns **Sharp** ## extend - Extends/pads the edges of the image with the provided background colour. This operation will always occur after resizing and extraction, if any. -### Parameters -* `extend` **([number][8] | [Object][9])** single pixel count to add to all edges or an Object with per-edge counts +**Throws**: - * `extend.top` **[number][8]** (optional, default `0`) - * `extend.left` **[number][8]** (optional, default `0`) - * `extend.bottom` **[number][8]** (optional, default `0`) - * `extend.right` **[number][8]** (optional, default `0`) - * `extend.background` **([String][10] | [Object][9])** background colour, parsed by the [color][11] module, defaults to black without transparency. (optional, default `{r:0,g:0,b:0,alpha:1}`) +- Error Invalid parameters -### Examples -```javascript +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| extend | number \| Object | | single pixel count to add to all edges or an Object with per-edge counts | +| [extend.top] | number | 0 | | +| [extend.left] | number | 0 | | +| [extend.bottom] | number | 0 | | +| [extend.right] | number | 0 | | +| [extend.background] | String \| Object | {r: 0, g: 0, b: 0, alpha: 1} | background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency. | + +**Example** +```js // Resize to 140 pixels wide, then add 10 transparent pixels // to the top, left and right edges and 20 to the bottom edge sharp(input) @@ -182,8 +179,8 @@ sharp(input) }) ... ``` - -```javascript +**Example** +```js // Add a row of 10 red pixels to the bottom sharp(input) .extend({ @@ -193,38 +190,38 @@ sharp(input) ... ``` -* Throws **[Error][13]** Invalid parameters - -Returns **Sharp** ## extract - Extract/crop a region of the image. -* Use `extract` before `resize` for pre-resize extraction. -* Use `extract` after `resize` for post-resize extraction. -* Use `extract` before and after for both. +- Use `extract` before `resize` for pre-resize extraction. +- Use `extract` after `resize` for post-resize extraction. +- Use `extract` before and after for both. -### Parameters -* `options` **[Object][9]** describes the region to extract using integral pixel values +**Throws**: - * `options.left` **[number][8]** zero-indexed offset from left edge - * `options.top` **[number][8]** zero-indexed offset from top edge - * `options.width` **[number][8]** width of region to extract - * `options.height` **[number][8]** height of region to extract +- Error Invalid parameters -### Examples -```javascript +| Param | Type | Description | +| --- | --- | --- | +| options | Object | describes the region to extract using integral pixel values | +| options.left | number | zero-indexed offset from left edge | +| options.top | number | zero-indexed offset from top edge | +| options.width | number | width of region to extract | +| options.height | number | height of region to extract | + +**Example** +```js sharp(input) .extract({ left: left, top: top, width: width, height: height }) .toFile(output, function(err) { // Extract a region of the input image, saving in the same format. }); ``` - -```javascript +**Example** +```js sharp(input) .extract({ left: leftOffsetPre, top: topOffsetPre, width: widthPre, height: heightPre }) .resize(width, height) @@ -234,12 +231,8 @@ sharp(input) }); ``` -* Throws **[Error][13]** Invalid parameters - -Returns **Sharp** ## trim - Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel. Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels. @@ -249,16 +242,20 @@ If the result of this operation would trim an image to nothing then no change is The `info` response Object, obtained from callback of `.toFile()` or `.toBuffer()`, will contain `trimOffsetLeft` and `trimOffsetTop` properties. -### Parameters -* `trim` **([string][10] | [number][8] | [Object][9])** the specific background colour to trim, the threshold for doing so or an Object with both. +**Throws**: - * `trim.background` **([string][10] | [Object][9])** background colour, parsed by the [color][11] module, defaults to that of the top-left pixel. (optional, default `'top-left pixel'`) - * `trim.threshold` **[number][8]** the allowed difference from the above colour, a positive number. (optional, default `10`) +- Error Invalid parameters -### Examples -```javascript +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| trim | string \| number \| Object | | the specific background colour to trim, the threshold for doing so or an Object with both. | +| [trim.background] | string \| Object | "'top-left pixel'" | background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel. | +| [trim.threshold] | number | 10 | the allowed difference from the above colour, a positive number. | + +**Example** +```js // Trim pixels with a colour similar to that of the top-left pixel. sharp(input) .trim() @@ -266,8 +263,8 @@ sharp(input) ... }); ``` - -```javascript +**Example** +```js // Trim pixels with the exact same colour as that of the top-left pixel. sharp(input) .trim(0) @@ -275,8 +272,8 @@ sharp(input) ... }); ``` - -```javascript +**Example** +```js // Trim only pixels with a similar colour to red. sharp(input) .trim("#FF0000") @@ -284,8 +281,8 @@ sharp(input) ... }); ``` - -```javascript +**Example** +```js // Trim all "yellow-ish" pixels, being more lenient with the higher threshold. sharp(input) .trim({ @@ -295,34 +292,4 @@ sharp(input) .toFile(output, function(err, info) { ... }); -``` - -* Throws **[Error][13]** Invalid parameters - -Returns **Sharp** - -[1]: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit - -[2]: https://developer.mozilla.org/en-US/docs/Web/CSS/object-position - -[3]: https://en.wikipedia.org/wiki/Entropy_%28information_theory%29 - -[4]: http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation - -[5]: https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline - -[6]: https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf - -[7]: https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel - -[8]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number - -[9]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object - -[10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String - -[11]: https://www.npmjs.org/package/color - -[12]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean - -[13]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error +``` \ No newline at end of file diff --git a/docs/api-utility.md b/docs/api-utility.md index 37954428..365a3057 100644 --- a/docs/api-utility.md +++ b/docs/api-utility.md @@ -1,101 +1,96 @@ - - -## format - -An Object containing nested boolean values representing the available input and output formats/methods. - -### Examples - -```javascript -console.log(sharp.format); -``` - -Returns **[Object][1]** - -## interpolators - -An Object containing the available interpolators and their proper values - -Type: [string][2] - -### nearest - -[Nearest neighbour interpolation][3]. Suitable for image enlargement only. - -### bilinear - -[Bilinear interpolation][4]. Faster than bicubic but with less smooth results. - -### bicubic - -[Bicubic interpolation][5] (the default). - -### locallyBoundedBicubic - -[LBB interpolation][6]. Prevents some "[acutance][7]" but typically reduces performance by a factor of 2. - -### nohalo - -[Nohalo interpolation][8]. Prevents acutance but typically reduces performance by a factor of 3. - -### vertexSplitQuadraticBasisSpline - -[VSQBS interpolation][9]. Prevents "staircasing" when enlarging. - ## versions - An Object containing the version numbers of libvips and its dependencies. -### Examples -```javascript +**Example** +```js console.log(sharp.versions); ``` -## vendor +## interpolators +An Object containing the available interpolators and their proper values + + +**Read only**: true +**Properties** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| nearest | string | "nearest" | [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. | +| bilinear | string | "bilinear" | [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. | +| bicubic | string | "bicubic" | [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). | +| locallyBoundedBicubic | string | "lbb" | [LBB interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100). Prevents some "[acutance](http://en.wikipedia.org/wiki/Acutance)" but typically reduces performance by a factor of 2. | +| nohalo | string | "nohalo" | [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. | +| vertexSplitQuadraticBasisSpline | string | "vsqbs" | [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents "staircasing" when enlarging. | + + + +## format +An Object containing nested boolean values representing the available input and output formats/methods. + + +**Example** +```js +console.log(sharp.format); +``` + + +## vendor An Object containing the platform and architecture of the current and installed vendored binaries. -### Examples -```javascript +**Example** +```js console.log(sharp.vendor); ``` -## cache -Gets or, when options are provided, sets the limits of *libvips'* operation cache. +## queue +An EventEmitter that emits a `change` event when a task is either: +- queued, waiting for _libuv_ to provide a worker thread +- complete + + +**Example** +```js +sharp.queue.on('change', function(queueLength) { + console.log('Queue contains ' + queueLength + ' task(s)'); +}); +``` + + +## cache +Gets or, when options are provided, sets the limits of _libvips'_ operation cache. Existing entries in the cache will be trimmed after any change in limits. This method always returns cache statistics, useful for determining how much working memory is required for a particular task. -### Parameters -* `options` **([Object][1] | [boolean][10])** Object with the following attributes, or boolean where true uses default cache settings and false removes all caching (optional, default `true`) - * `options.memory` **[number][11]** is the maximum memory in MB to use for this cache (optional, default `50`) - * `options.files` **[number][11]** is the maximum number of files to hold open (optional, default `20`) - * `options.items` **[number][11]** is the maximum number of operations to cache (optional, default `100`) +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [options] | Object \| boolean | true | Object with the following attributes, or boolean where true uses default cache settings and false removes all caching | +| [options.memory] | number | 50 | is the maximum memory in MB to use for this cache | +| [options.files] | number | 20 | is the maximum number of files to hold open | +| [options.items] | number | 100 | is the maximum number of operations to cache | -### Examples - -```javascript +**Example** +```js const stats = sharp.cache(); ``` - -```javascript +**Example** +```js sharp.cache( { items: 200 } ); sharp.cache( { files: 0 } ); sharp.cache(false); ``` -Returns **[Object][1]** ## concurrency - Gets or, when a concurrency is provided, sets -the maximum number of threads *libvips* should use to process *each image*. +the maximum number of threads _libvips_ should use to process _each image_. These are from a thread pool managed by glib, which helps avoid the overhead of creating new threads. @@ -115,102 +110,59 @@ The maximum number of images that sharp can process in parallel is controlled by libuv's `UV_THREADPOOL_SIZE` environment variable, which defaults to 4. -[https://nodejs.org/api/cli.html#uv\_threadpool\_sizesize][12] +https://nodejs.org/api/cli.html#uv_threadpool_sizesize For example, by default, a machine with 8 CPU cores will process 4 images in parallel and use up to 8 threads per image, so there will be up to 32 concurrent threads. -### Parameters -* `concurrency` **[number][11]?** +**Returns**: number - concurrency -### Examples +| Param | Type | +| --- | --- | +| [concurrency] | number | -```javascript +**Example** +```js const threads = sharp.concurrency(); // 4 sharp.concurrency(2); // 2 sharp.concurrency(0); // 4 ``` -Returns **[number][11]** concurrency - -## queue - -An EventEmitter that emits a `change` event when a task is either: - -* queued, waiting for *libuv* to provide a worker thread -* complete - -### Examples - -```javascript -sharp.queue.on('change', function(queueLength) { - console.log('Queue contains ' + queueLength + ' task(s)'); -}); -``` ## counters - Provides access to internal task counters. +- queue is the number of tasks this module has queued waiting for _libuv_ to provide a worker thread from its pool. +- process is the number of resize tasks currently being processed. -* queue is the number of tasks this module has queued waiting for *libuv* to provide a worker thread from its pool. -* process is the number of resize tasks currently being processed. -### Examples - -```javascript +**Example** +```js const counters = sharp.counters(); // { queue: 2, process: 4 } ``` -Returns **[Object][1]** ## simd - Get and set use of SIMD vector unit instructions. Requires libvips to have been compiled with liborc support. Improves the performance of `resize`, `blur` and `sharpen` operations by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON. -### Parameters -* `simd` **[boolean][10]** (optional, default `true`) -### Examples +| Param | Type | Default | +| --- | --- | --- | +| [simd] | boolean | true | -```javascript +**Example** +```js const simd = sharp.simd(); // simd is `true` if the runtime use of liborc is currently enabled ``` - -```javascript +**Example** +```js const simd = sharp.simd(false); // prevent libvips from using liborc at runtime -``` - -Returns **[boolean][10]** - -[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object - -[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String - -[3]: http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation - -[4]: http://en.wikipedia.org/wiki/Bilinear_interpolation - -[5]: http://en.wikipedia.org/wiki/Bicubic_interpolation - -[6]: https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100 - -[7]: http://en.wikipedia.org/wiki/Acutance - -[8]: http://eprints.soton.ac.uk/268086/ - -[9]: https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48 - -[10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean - -[11]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number - -[12]: https://nodejs.org/api/cli.html#uv_threadpool_sizesize +``` \ No newline at end of file diff --git a/docs/build.js b/docs/build.js index b9ee88df..4922bbcc 100644 --- a/docs/build.js +++ b/docs/build.js @@ -2,6 +2,7 @@ const fs = require('fs').promises; const path = require('path'); +const jsdoc2md = require('jsdoc-to-markdown'); [ 'constructor', @@ -14,13 +15,21 @@ const path = require('path'); 'output', 'utility' ].forEach(async (m) => { - const documentation = await import('documentation'); - const input = path.join('lib', `${m}.js`); const output = path.join('docs', `api-${m}.md`); - const ast = await documentation.build(input, { shallow: true }); - const markdown = await documentation.formats.md(ast, { markdownToc: false }); + const ast = await jsdoc2md.getTemplateData({ files: input }); + const markdown = await jsdoc2md.render({ + data: ast, + 'global-index-format': 'none', + 'module-index-format': 'none' + }); - await fs.writeFile(output, markdown); + const cleanMarkdown = markdown + .replace(/(## [A-Za-z]+)[^\n]*/g, '$1') // simplify headings to match those of documentationjs, ensures existing URLs work + .replace(/<\/a>/g, '') // remove anchors, let docute add these (at markdown to HTML render time) + .replace(/\*\*Kind\*\*: global[^\n]+/g, '') // remove all "global" Kind labels (requires JSDoc refactoring) + .trim(); + + await fs.writeFile(output, cleanMarkdown); }); diff --git a/docs/index.html b/docs/index.html index f8eba79f..ab2f0c6f 100644 --- a/docs/index.html +++ b/docs/index.html @@ -77,9 +77,7 @@ .map(function (sidebarLink) { return sidebarLink.title; })[0]; - return title - ? md.replace(//, '# ' + title) - : md; + return title ? `# ${title}\n${md}` : md; }); } }; diff --git a/docs/search-index.json b/docs/search-index.json index 26fa311f..48088c8b 100644 --- a/docs/search-index.json +++ b/docs/search-index.json @@ -1 +1 @@ -[{"t":"Prerequisites","d":"Node.js 14.15.0","k":"prerequisites node","l":"/install#prerequisites"},{"t":"Prebuilt binaries","d":"Ready-compiled sharp and libvips binaries are provided for use on the most common platforms macOS x64 10.13 macOS ARM64 Linux x64 glibc 2.17, musl 1.1.24, CPU with SSE4.2 Linux ARM64 glibc 2.17, musl","k":"prebuilt binaries compiled libvips common platforms macos arm linux glibc musl cpu sse","l":"/install#prebuilt-binaries"},{"t":"Common problems","d":"The architecture and platform of Node.js used for npm install must be the same as the architecture and platform of Node.js used at runtime. See the cross-platform","k":"common problems architecture platform node npm install runtime cross","l":"/install#common-problems"},{"t":"Apple M1","d":"Prebuilt sharp and libvips binaries have been provided for macOS on ARM64 since sharp v0.29.0.","k":"apple prebuilt libvips binaries macos arm","l":"/install#apple-m1"},{"t":"Custom libvips","d":"To use a custom, globally-installed version of libvips instead of the provided binaries, make sure it is at least the version listed under config.libvips in the package.json file and that it can be lo","k":"custom libvips globally installed version instead binaries listed config package json file","l":"/install#custom-libvips"},{"t":"Building from source","d":"This module will be compiled from source at npm install time when a globally-installed libvips is detected set the SHARP_IGNORE_GLOBAL_LIBVIPS environment variable to skip this, prebuilt sharp binarie","k":"building source module compiled npm install time globally installed libvips detected environment variable skip prebuilt binarie","l":"/install#building-from-source"},{"t":"Custom prebuilt binaries","d":"This is an advanced approach that most people will not require.","k":"custom prebuilt binaries advanced approach people require","l":"/install#custom-prebuilt-binaries"},{"t":"Prebuilt sharp binaries","d":"To install the prebuilt sharp binaries from a custom URL, set the sharp_binary_host npm config option or the npm_config_sharp_binary_host environment variable. To install the prebuilt sharp binaries f","k":"prebuilt binaries install custom url npm config option environment variable","l":"/install#prebuilt-sharp-binaries"},{"t":"Prebuilt libvips binaries","d":"To install the prebuilt libvips binaries from a custom URL, set the sharp_libvips_binary_host npm config option or the npm_config_sharp_libvips_binary_host environment variable. To install the prebuil","k":"prebuilt libvips binaries install custom url npm config option environment variable prebuil","l":"/install#prebuilt-libvips-binaries"},{"t":"Chinese mirror","d":"A mirror site based in China, provided by Alibaba, contains binaries for both sharp and libvips. To use this either set the following configuration sh npm config set sharp_binary_host https//npmmirror","k":"chinese mirror china alibaba binaries libvips configuration npm config https npmmirror","l":"/install#chinese-mirror"},{"t":"FreeBSD","d":"The vips package must be installed before npm install is run. sh pkg install -y pkgconf vips sh cd /usr/ports/graphics/vips/ make install clean","k":"freebsd vips package installed npm install pkg pkgconf usr ports graphics clean","l":"/install#freebsd"},{"t":"Linux memory allocator","d":"The default memory allocator on most glibc-based Linux systems e.g. Debian, Red Hat is unsuitable for long-running, multi-threaded processes that involve lots of small memory allocations. For this rea","k":"linux memory allocator glibc systems debian red hat long running multi threaded processes small allocations rea","l":"/install#linux-memory-allocator"},{"t":"Heroku","d":"Add the jemalloc buildpack to reduce the effects of memory fragmentation. Set NODE_MODULES_CACHE","k":"heroku add jemalloc buildpack reduce effects memory fragmentation","l":"/install#heroku"},{"t":"AWS Lambda","d":"The node_modules directory of the deployment package must include binaries for the Linux x64 platform. When building your deployment package on machines other than Linux x64 glibc, run the following a","k":"aws lambda nodemodules directory deployment package binaries linux platform building machines glibc","l":"/install#aws-lambda"},{"t":"webpack","d":"Ensure sharp is excluded from bundling via the externals configuration. js externals sharp commonjs sharp","k":"webpack excluded bundling via externals configuration commonjs","l":"/install#webpack"},{"t":"esbuild","d":"Ensure sharp is excluded from bundling via the external","k":"esbuild excluded bundling via external","l":"/install#esbuild"},{"t":"Fonts","d":"When creating text images or rendering SVG images that contain text elements, fontconfig is used to find the relevant fonts. On Windows and macOS systems, all system fonts are available for use. On ma","k":"fonts creating text images rendering svg contain elements fontconfig find relevant windows macos systems system","l":"/install#fonts"},{"t":"Worker threads","d":"On some platforms, including glibc-based Linux, the main thread must call requiresharp _before_ worker threads are created. This is to ensure shared libraries remain loaded in memory until after all t","k":"worker threads platforms glibc linux main thread shared libraries remain loaded memory","l":"/install#worker-threads"},{"t":"Canvas and Windows","d":"The prebuilt binaries provided by canvas for Windows from v2.7.0 onwards depend on the Visual C Runtime MSVCRT. These conflict with the binaries provided by sharp, which depend on the more modern Univ","k":"canvas windows prebuilt binaries onwards depend visual runtime msvcrt conflict modern univ","l":"/install#canvas-and-windows"},{"t":"Sharp","d":"Constructor factory to create an instance of sharp, to which further methods are chained.","k":"constructor factory create instance further methods chained","l":"/api-constructor#sharp"},{"t":"clone","d":"Take a snapshot of the Sharp instance, returning a new instance. Cloned instances inherit the input of their parent instance. This allows multiple output Streams and therefore multiple processing pipe","k":"clone snapshot instance returning new cloned instances inherit input parent multiple output streams processing pipe","l":"/api-constructor#clone"},{"t":"metadata","d":"Fast access to uncached image metadata without decoding any compressed pixel data.","k":"metadata fast access uncached decoding compressed pixel data","l":"/api-input#metadata"},{"t":"stats","d":"Access to pixel-derived image statistics for every channel in the image. A Promise is returned when callback is not provided.","k":"stats access pixel derived statistics channel promise","l":"/api-input#stats"},{"t":"toFile","d":"Write output image data to a file.","k":"tofile write output data file","l":"/api-output#tofile"},{"t":"toBuffer","d":"Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.","k":"tobuffer write output buffer jpeg png webp avif tiff gif raw pixel data","l":"/api-output#tobuffer"},{"t":"withMetadata","d":"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.","k":"withmetadata metadata exif xmp iptc input output convert add web friendly srgb icc profile custom","l":"/api-output#withmetadata"},{"t":"toFormat","d":"Force output to a given format.","k":"toformat force output format","l":"/api-output#toformat"},{"t":"jpeg","d":"Use these JPEG options for output image.","k":"jpeg output quality progressive optimisecoding optimizecoding mozjpeg optimisescans optimizescans force","l":"/api-output#jpeg"},{"t":"png","d":"Use these PNG options for output image.","k":"png output","l":"/api-output#png"},{"t":"webp","d":"Use these WebP options for output image.","k":"webp output quality alphaquality lossless nearlossless smartsubsample effort loop delay minsize mixed force","l":"/api-output#webp"},{"t":"gif","d":"Use these GIF options for the output image.","k":"gif output","l":"/api-output#gif"},{"t":"tiff","d":"Use these TIFF options for output image.","k":"tiff output","l":"/api-output#tiff"},{"t":"avif","d":"Use these AVIF options for output image.","k":"avif output","l":"/api-output#avif"},{"t":"heif","d":"Use these HEIF options for output image.","k":"heif output","l":"/api-output#heif"},{"t":"jxl","d":"Use these JPEG-XL JXL options for output image.","k":"jxl jpeg output","l":"/api-output#jxl"},{"t":"raw","d":"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.","k":"raw force output uncompressed pixel data ordering left right top bottom padding channel rgb rgba greyscale colourspaces depth size overlap angle background skipblanks container layout centre center basename","l":"/api-output#raw"},{"t":"timeout","d":"Set a timeout for processing, in seconds. Use a value of zero to continue processing indefinitely, the default behaviour.","k":"timeout processing seconds zero continue indefinitely behaviour","l":"/api-output#timeout"},{"t":"resize","d":"Resize image to width, height or width x height.","k":"resize width height","l":"/api-resize#resize"},{"t":"extend","d":"Extends/pads the edges of the image with the provided background colour. This operation will always occur after resizing and extraction, if any.","k":"extend extends pads edges background colour operation resizing extraction","l":"/api-resize#extend"},{"t":"extract","d":"Extract/crop a region of the image.","k":"extract crop region","l":"/api-resize#extract"},{"t":"trim","d":"Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.","k":"trim pixels edges contain similar background colour defaults top left pixel","l":"/api-resize#trim"},{"t":"composite","d":"Composite images over the processed resized, extracted etc. image.","k":"composite images processed resized extracted","l":"/api-composite#composite"},{"t":"rotate","d":"Rotate the output image by either an explicit angle or auto-orient based on the EXIF Orientation tag.","k":"rotate output explicit angle auto orient exif orientation tag","l":"/api-operation#rotate"},{"t":"flip","d":"Flip the image about the vertical Y axis. This always occurs before rotation, if any. The use of flip implies the removal of the EXIF Orientation tag, if any.","k":"flip vertical axis rotation removal exif orientation tag","l":"/api-operation#flip"},{"t":"flop","d":"Flop the image about the horizontal X axis. This always occurs before rotation, if any. The use of flop implies the removal of the EXIF Orientation tag, if any.","k":"flop horizontal axis rotation removal exif orientation tag","l":"/api-operation#flop"},{"t":"affine","d":"Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.","k":"affine transform operation resizing extraction rotation","l":"/api-operation#affine"},{"t":"sharpen","d":"Sharpen the image.","k":"sharpen","l":"/api-operation#sharpen"},{"t":"median","d":"Apply median filter. When used without parameters the default window is 3x3.","k":"median apply filter parameters window","l":"/api-operation#median"},{"t":"blur","d":"Blur the image.","k":"blur","l":"/api-operation#blur"},{"t":"flatten","d":"Merge alpha transparency channel, if any, with a background, then remove the alpha channel.","k":"flatten merge alpha transparency channel background remove","l":"/api-operation#flatten"},{"t":"gamma","d":"Apply a gamma correction by reducing the encoding darken pre-resize at a factor of 1/gamma then increasing the encoding brighten post-resize at a factor of gamma. This can improve the perceived bright","k":"gamma apply correction reducing encoding darken pre resize factor increasing brighten post improve perceived bright","l":"/api-operation#gamma"},{"t":"negate","d":"Produce the negative of the image.","k":"negate negative alpha","l":"/api-operation#negate"},{"t":"normalise","d":"Enhance output image contrast by stretching its luminance to cover the full dynamic range.","k":"normalise enhance output contrast stretching luminance cover full dynamic range","l":"/api-operation#normalise"},{"t":"normalize","d":"Alternative spelling of normalise.","k":"normalize normalise","l":"/api-operation#normalize"},{"t":"clahe","d":"Perform contrast limiting adaptive histogram equalization CLAHE10.","k":"clahe contrast limiting adaptive histogram equalization","l":"/api-operation#clahe"},{"t":"convolve","d":"Convolve the image with the specified kernel.","k":"convolve kernel","l":"/api-operation#convolve"},{"t":"threshold","d":"Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0.","k":"threshold pixel greater equal otherwise greyscale grayscale","l":"/api-operation#threshold"},{"t":"boolean","d":"Perform a bitwise boolean operation with operand image.","k":"boolean bitwise operation operand","l":"/api-operation#boolean"},{"t":"linear","d":"Apply the linear formula a input b to the image to adjust image levels.","k":"linear apply formula input adjust levels","l":"/api-operation#linear"},{"t":"recomb","d":"Recomb the image with the specified matrix.","k":"recomb matrix","l":"/api-operation#recomb"},{"t":"modulate","d":"Transforms the image using brightness, saturation, hue rotation, and lightness. Brightness and lightness both operate on luminance, with the difference being that brightness is multiplicative whereas","k":"modulate transforms brightness saturation hue rotation lightness operate luminance difference being multiplicative whereas","l":"/api-operation#modulate"},{"t":"removeAlpha","d":"Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel.","k":"removealpha remove alpha channel","l":"/api-channel#removealpha"},{"t":"ensureAlpha","d":"Ensure the output image has an alpha transparency channel. If missing, the added alpha channel will have the specified transparency level, defaulting to fully-opaque 1. This is a no-op if the image al","k":"ensurealpha output alpha transparency channel missing added level defaulting fully opaque","l":"/api-channel#ensurealpha"},{"t":"extractChannel","d":"Extract a single channel from a multi-channel image.","k":"extractchannel extract single channel multi","l":"/api-channel#extractchannel"},{"t":"joinChannel","d":"Join one or more channels to the image. The meaning of the added channels depends on the output colourspace, set with toColourspace. By default the output image will be web-friendly sRGB, with additio","k":"joinchannel join one channels meaning added depends output colourspace tocolourspace web friendly srgb additio","l":"/api-channel#joinchannel"},{"t":"bandbool","d":"Perform a bitwise boolean operation on all input image channels bands to produce a single channel output image.","k":"bandbool bitwise boolean operation input channels bands single channel output","l":"/api-channel#bandbool"},{"t":"tint","d":"Tint the image using the provided chroma while preserving the image luminance. An alpha channel may be present and will be unchanged by the operation.","k":"tint chroma preserving luminance alpha channel present unchanged operation","l":"/api-colour#tint"},{"t":"greyscale","d":"Convert to 8-bit greyscale 256 shades of grey. This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use gamma with greyscale for the best results. By default th","k":"greyscale convert bit shades grey linear operation input colour space srgb gamma best results","l":"/api-colour#greyscale"},{"t":"grayscale","d":"Alternative spelling of greyscale.","k":"grayscale greyscale","l":"/api-colour#grayscale"},{"t":"pipelineColourspace","d":"Set the pipeline colourspace.","k":"pipeline colourspace","l":"/api-colour#pipelinecolourspace"},{"t":"pipelineColorspace","d":"Alternative spelling of pipelineColourspace.","k":"","l":"/api-colour#pipelinecolorspace"},{"t":"toColourspace","d":"Set the output colourspace. By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.","k":"tocolourspace output colourspace web friendly srgb additional channels interpreted alpha","l":"/api-colour#tocolourspace"},{"t":"toColorspace","d":"Alternative spelling of toColourspace.","k":"tocolorspace tocolourspace","l":"/api-colour#tocolorspace"},{"t":"format","d":"An Object containing nested boolean values representing the available input and output formats/methods.","k":"format object nested boolean representing input output formats methods","l":"/api-utility#format"},{"t":"interpolators","d":"An Object containing the available interpolators and their proper values","k":"interpolators object proper","l":"/api-utility#interpolators"},{"t":"versions","d":"An Object containing the version numbers of libvips and its dependencies.","k":"versions object version numbers libvips dependencies","l":"/api-utility#versions"},{"t":"vendor","d":"An Object containing the platform and architecture of the current and installed vendored binaries.","k":"vendor object platform architecture installed vendored binaries","l":"/api-utility#vendor"},{"t":"cache","d":"Gets or, when options are provided, sets the limits of libvips operation cache. Existing entries in the cache will be trimmed after any change in limits. This method always returns cache statistics, u","k":"cache limits libvips operation existing entries trimmed change method returns statistics memory files items","l":"/api-utility#cache"},{"t":"concurrency","d":"Gets or, when a concurrency is provided, sets the maximum number of threads libvips should use to process each image. These are from a thread pool managed by glib, which helps avoid the overhead of cr","k":"concurrency maximum number threads libvips process thread pool managed glib helps avoid overhead","l":"/api-utility#concurrency"},{"t":"queue","d":"An EventEmitter that emits a change event when a task is either","k":"queue eventemitter emits change event","l":"/api-utility#queue"},{"t":"counters","d":"Provides access to internal task counters.","k":"counters provides access internal","l":"/api-utility#counters"},{"t":"simd","d":"Get and set use of SIMD vector unit instructions. Requires libvips to have been compiled with liborc support.","k":"simd vector unit instructions libvips compiled liborc","l":"/api-utility#simd"}] \ No newline at end of file +[{"t":"Prerequisites","d":"Node.js 14.15.0","k":"prerequisites node","l":"/install#prerequisites"},{"t":"Prebuilt binaries","d":"Ready-compiled sharp and libvips binaries are provided for use on the most common platforms macOS x64 10.13 macOS ARM64 Linux x64 glibc 2.17, musl 1.1.24, CPU with SSE4.2 Linux ARM64 glibc 2.17, musl","k":"prebuilt binaries compiled libvips common platforms macos arm linux glibc musl cpu sse","l":"/install#prebuilt-binaries"},{"t":"Common problems","d":"The architecture and platform of Node.js used for npm install must be the same as the architecture and platform of Node.js used at runtime. See the cross-platform","k":"common problems architecture platform node npm install runtime cross","l":"/install#common-problems"},{"t":"Apple M1","d":"Prebuilt sharp and libvips binaries have been provided for macOS on ARM64 since sharp v0.29.0.","k":"apple prebuilt libvips binaries macos arm","l":"/install#apple-m1"},{"t":"Custom libvips","d":"To use a custom, globally-installed version of libvips instead of the provided binaries, make sure it is at least the version listed under config.libvips in the package.json file and that it can be lo","k":"custom libvips globally installed version instead binaries listed config package json file","l":"/install#custom-libvips"},{"t":"Building from source","d":"This module will be compiled from source at npm install time when a globally-installed libvips is detected set the SHARP_IGNORE_GLOBAL_LIBVIPS environment variable to skip this, prebuilt sharp binarie","k":"building source module compiled npm install time globally installed libvips detected environment variable skip prebuilt binarie","l":"/install#building-from-source"},{"t":"Custom prebuilt binaries","d":"This is an advanced approach that most people will not require.","k":"custom prebuilt binaries advanced approach people require","l":"/install#custom-prebuilt-binaries"},{"t":"Prebuilt sharp binaries","d":"To install the prebuilt sharp binaries from a custom URL, set the sharp_binary_host npm config option or the npm_config_sharp_binary_host environment variable. To install the prebuilt sharp binaries f","k":"prebuilt binaries install custom url npm config option environment variable","l":"/install#prebuilt-sharp-binaries"},{"t":"Prebuilt libvips binaries","d":"To install the prebuilt libvips binaries from a custom URL, set the sharp_libvips_binary_host npm config option or the npm_config_sharp_libvips_binary_host environment variable. To install the prebuil","k":"prebuilt libvips binaries install custom url npm config option environment variable prebuil","l":"/install#prebuilt-libvips-binaries"},{"t":"Chinese mirror","d":"A mirror site based in China, provided by Alibaba, contains binaries for both sharp and libvips. To use this either set the following configuration sh npm config set sharp_binary_host https//npmmirror","k":"chinese mirror china alibaba binaries libvips configuration npm config https npmmirror","l":"/install#chinese-mirror"},{"t":"FreeBSD","d":"The vips package must be installed before npm install is run. sh pkg install -y pkgconf vips sh cd /usr/ports/graphics/vips/ make install clean","k":"freebsd vips package installed npm install pkg pkgconf usr ports graphics clean","l":"/install#freebsd"},{"t":"Linux memory allocator","d":"The default memory allocator on most glibc-based Linux systems e.g. Debian, Red Hat is unsuitable for long-running, multi-threaded processes that involve lots of small memory allocations. For this rea","k":"linux memory allocator glibc systems debian red hat long running multi threaded processes small allocations rea","l":"/install#linux-memory-allocator"},{"t":"Heroku","d":"Add the jemalloc buildpack to reduce the effects of memory fragmentation. Set NODE_MODULES_CACHE","k":"heroku add jemalloc buildpack reduce effects memory fragmentation","l":"/install#heroku"},{"t":"AWS Lambda","d":"The node_modules directory of the deployment package must include binaries for the Linux x64 platform. When building your deployment package on machines other than Linux x64 glibc, run the following a","k":"aws lambda nodemodules directory deployment package binaries linux platform building machines glibc","l":"/install#aws-lambda"},{"t":"webpack","d":"Ensure sharp is excluded from bundling via the externals configuration. js externals sharp commonjs sharp","k":"webpack excluded bundling via externals configuration commonjs","l":"/install#webpack"},{"t":"esbuild","d":"Ensure sharp is excluded from bundling via the external","k":"esbuild excluded bundling via external","l":"/install#esbuild"},{"t":"Fonts","d":"When creating text images or rendering SVG images that contain text elements, fontconfig is used to find the relevant fonts. On Windows and macOS systems, all system fonts are available for use. On ma","k":"fonts creating text images rendering svg contain elements fontconfig find relevant windows macos systems system","l":"/install#fonts"},{"t":"Worker threads","d":"On some platforms, including glibc-based Linux, the main thread must call requiresharp _before_ worker threads are created. This is to ensure shared libraries remain loaded in memory until after all t","k":"worker threads platforms glibc linux main thread shared libraries remain loaded memory","l":"/install#worker-threads"},{"t":"Canvas and Windows","d":"The prebuilt binaries provided by canvas for Windows from v2.7.0 onwards depend on the Visual C Runtime MSVCRT. These conflict with the binaries provided by sharp, which depend on the more modern Univ","k":"canvas windows prebuilt binaries onwards depend visual runtime msvcrt conflict modern univ","l":"/install#canvas-and-windows"}] \ No newline at end of file diff --git a/package.json b/package.json index d953e082..46592cc4 100644 --- a/package.json +++ b/package.json @@ -95,7 +95,7 @@ "test-unit": "nyc --reporter=lcov --reporter=text --check-coverage --branches=100 mocha", "test-licensing": "license-checker --production --summary --onlyAllow=\"Apache-2.0;BSD;ISC;MIT\"", "test-leak": "./test/leak/leak.sh", - "docs-build": "documentation lint lib && node docs/build && node docs/search-index/build", + "docs-build": "node docs/build && node docs/search-index/build", "docs-serve": "cd docs && npx serve", "docs-publish": "cd docs && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp" }, @@ -141,10 +141,10 @@ "devDependencies": { "async": "^3.2.4", "cc": "^3.0.1", - "documentation": "^14.0.1", "exif-reader": "^1.1.0", "extract-zip": "^2.0.1", "icc": "^2.0.0", + "jsdoc-to-markdown": "^8.0.0", "license-checker": "^25.0.1", "mocha": "^10.2.0", "mock-fs": "^5.2.0",