### Install node-addon-api and node-gyp Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/install.md Install these dependencies if they are not found during the build process for sharp from source. ```sh npm install --save node-addon-api node-gyp ``` -------------------------------- ### Install sharp with bun Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/install.md Use bun to add the sharp library as a project dependency. ```sh bun add sharp ``` -------------------------------- ### Install sharp via npm Source: https://github.com/lovell/sharp/blob/main/README.md Use npm to install the sharp module as a project dependency. ```sh npm install sharp ``` -------------------------------- ### Install sharp with yarn Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/install.md Use yarn to add the sharp library as a project dependency. ```sh yarn add sharp ``` -------------------------------- ### Install sharp with WebAssembly support Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/install.md Install the optional @img/sharp-wasm32 package to enable multi-threaded WebAssembly support in compatible runtime environments. ```sh npm install sharp @img/sharp-wasm32 ``` -------------------------------- ### Install sharp with pnpm Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/install.md Use pnpm to add the sharp library as a project dependency. ```sh pnpm add sharp ``` -------------------------------- ### Convert to High Quality JP2 Output with Sharp Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-output.md This example converts an input image to JP2 with maximum quality and full chroma subsampling. Requires `libvips` compiled with OpenJPEG support. ```js const data = await sharp(input) .jp2({ quality: 100, chromaSubsampling: '4:4:4' }) .toBuffer(); ``` -------------------------------- ### Rotate and Resize Image with Sharp Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-operation.md This example demonstrates how the order of `rotate` and `resize` operations affects the final image output, highlighting the importance of method chaining order in Sharp. ```js const rotateThenResize = await sharp(input) .rotate(90) .resize({ width: 16, height: 8, fit: 'fill' }) .toBuffer(); const resizeThenRotate = await sharp(input) .resize({ width: 16, height: 8, fit: 'fill' }) .rotate(90) .toBuffer(); ``` -------------------------------- ### Install sharp for Linux cross-platform with npm Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/install.md Install sharp for specific Linux C standard libraries (glibc and musl) using npm to support cross-platform lockfiles. ```sh npm install --cpu=x64 --os=linux --libc=glibc sharp ``` ```sh npm install --cpu=x64 --os=linux --libc=musl sharp ``` -------------------------------- ### Clone Sharp Instance for Multiple File Outputs with Promises Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-constructor.md This example demonstrates using `clone()` to generate multiple output files (different sizes, formats) from a single downloaded image stream, managing completion with Promises. ```javascript // 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 sharpStream = sharp(); const promises = []; promises.push( sharpStream .clone() .jpeg({ quality: 100 }) .toFile("originalFile.jpg") ); promises.push( sharpStream .clone() .resize({ width: 500 }) .jpeg({ quality: 80 }) .toFile("optimized-500.jpg") ); promises.push( sharpStream .clone() .resize({ width: 500 }) .webp({ quality: 80 }) .toFile("optimized-500.webp") ); const res = await fetch("https://www.example.com/some-file.jpg") Readable.fromWeb(res.body).pipe(sharpStream); await Promise.all(promises); ``` -------------------------------- ### Configure serverless-esbuild for sharp native binaries Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/install.md Ensure platform-specific 'sharp' binaries are installed for serverless-esbuild deployments by configuring 'external' and 'packagerOptions' in `serverless.yml`. ```yaml custom: esbuild: external: - sharp packagerOptions: scripts: - npm install --os=linux --cpu=x64 sharp ``` -------------------------------- ### Create a Blank PNG Image with sharp Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-constructor.md This example shows how to generate a new blank PNG image with specified dimensions, channels, and a semi-translucent background color using the `create` option in the sharp constructor. ```javascript // Create a blank 300x200 PNG image of semi-translucent red pixels sharp({ create: { width: 300, height: 200, channels: 4, background: { r: 255, g: 0, b: 0, alpha: 0.5 } } }) .png() .toBuffer() .then( ... ); ``` -------------------------------- ### Join Multiple Images into a Grid with sharp Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-constructor.md This example demonstrates how to combine multiple input images into a single grid. The `join` option in the constructor specifies the grid layout and gutter size. ```javascript // Join four input images as a 2x2 grid with a 4 pixel gutter const data = await sharp( [image1, image2, image3, image4], { join: { across: 2, shim: 4 } } ).toBuffer(); ``` -------------------------------- ### Install sharp for macOS cross-platform with npm Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/install.md Install sharp for specific macOS CPU architectures (x64 and ARM64) using npm to support cross-platform lockfiles. ```sh npm install --cpu=x64 --os=darwin sharp ``` ```sh npm install --cpu=arm64 --os=darwin sharp ``` -------------------------------- ### Create Image from Raw Pixel Data with sharp Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-constructor.md This example demonstrates creating an image from a raw `Uint8Array` of pixel data. The `raw` option in the constructor is essential to specify image dimensions and channels when the input lacks this metadata. ```javascript // 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, { // because the input does not contain its dimensions or how many channels it has // we need to specify it in the constructor options raw: { width: 2, height: 1, channels: 3 } }); await image.toFile('my-two-pixels.png'); ``` -------------------------------- ### Allow Only WebP Input from Filesystem with sharp.block and sharp.unblock (JavaScript) Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-utility.md This example first blocks all foreign load operations, then specifically unblocks WebP file loading, effectively allowing only WebP input from the filesystem. ```js sharp.block({ operation: ['VipsForeignLoad'] }); sharp.unblock({ operation: ['VipsForeignLoadWebpFile'] }); ``` -------------------------------- ### Generate Black and White Image from Text with sharp Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-constructor.md This example shows how to create a black and white image directly from a text string. The `text` option in the constructor allows setting the text content and maximum dimensions. ```javascript // Generate an image from text await sharp({ text: { text: 'Hello, world!', width: 400, // max width height: 300 // max height } }).toFile('text_bw.png'); ``` -------------------------------- ### Extract Raw Alpha Channel Data with Sharp.js Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-output.md This example demonstrates how to extract the alpha channel as raw, unsigned 16-bit pixel data from a PNG input, ensuring an alpha channel exists before extraction. ```js // Extract alpha channel as raw, unsigned 16-bit pixel data from PNG input const data = await sharp('input.png') .ensureAlpha() .extractChannel(3) .toColourspace('b-w') .raw({ depth: 'ushort' }) .toBuffer(); ``` -------------------------------- ### Set output density (DPI) (JavaScript) Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-output.md Sets the output image's density (DPI) in its EXIF metadata. This example sets the density to 96 DPI before outputting to a buffer. ```js const data = await sharp(input) .withDensity(96) .toBuffer(); ``` -------------------------------- ### cache([options]) Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-utility.md 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. ```APIDOC ## Method: cache([options]) ### Description This method allows you to inspect or modify the caching behavior of the underlying _libvips_ library. When called without arguments, it returns current cache statistics. When an `options` object is provided, it sets new limits for the cache, trimming existing entries if necessary. Passing `false` as an option disables all caching. ### Parameters - **[options]** (Object | boolean) - Optional. An object with cache configuration attributes, or a boolean. - If `true`, uses default cache settings. - If `false`, removes all caching. - If an `Object`, it can contain: - **[options.memory]** (number) - Default: `50`. Maximum memory in MB to use for the cache. - **[options.files]** (number) - Default: `20`. Maximum number of files to hold open in the cache. - **[options.items]** (number) - Default: `100`. Maximum number of operations to cache. ### Returns Object - Cache statistics, regardless of whether options were provided. ### Examples #### Get current cache statistics ```javascript const stats = sharp.cache(); console.log(stats); /* Example output: { memory: { current: 10, high: 50, max: 50 }, files: { current: 5, high: 20, max: 20 }, items: { current: 15, high: 100, max: 100 } } */ ``` #### Set cache item limit ```javascript sharp.cache( { items: 200 } ); ``` #### Disable file caching ```javascript sharp.cache( { files: 0 } ); ``` #### Disable all caching ```javascript sharp.cache(false); ``` ``` -------------------------------- ### jxl([options]) ⇒ Sharp Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-output.md 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. ```APIDOC ## jxl jxl([options]) ### Description 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. ### Method jxl ### Endpoint jxl([options]) ### Parameters #### Body Parameters - **options** (Object) - Optional - output options - **options.distance** (number) - Optional - Default: 1.0 - maximum encoding error, between 0 (highest quality) and 15 (lowest quality) - **options.quality** (number) - Optional - calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified - **options.decodingTier** (number) - Optional - Default: 0 - target decode speed tier, between 0 (highest quality) and 4 (lowest quality) - **options.lossless** (boolean) - Optional - Default: false - use lossless compression - **options.effort** (number) - Optional - Default: 7 - CPU effort, between 1 (fastest) and 9 (slowest) - **options.loop** (number) - Optional - Default: 0 - number of animation iterations, use 0 for infinite animation - **options.delay** (number | Array.) - Optional - delay(s) between animation frames (in milliseconds) ``` -------------------------------- ### timeout(options) Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-output.md 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. ```APIDOC ## timeout(options) ### Description 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) - Configuration options for the timeout. - **seconds** (number) - Number of seconds after which processing will be stopped. ### Example ```js // Ensure processing takes no longer than 3 seconds try { const data = await sharp(input) .blur(1000) .timeout({ seconds: 3 }) .toBuffer(); } catch (err) { if (err.message.includes('timeout')) { ... } } ``` ``` -------------------------------- ### new Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-constructor.md Initializes a new `sharp` image processing instance with various configuration options. ```APIDOC ## new Sharp([options]) ### Description Initializes a new `sharp` image processing instance with various configuration options. ### Method Signature `new Sharp([options])` ### Parameters #### options (Object) - Optional - Configuration options for the sharp instance. - **options.raw.pageHeight** (number) - Optional - The pixel height of each page/frame for animated images, must be an integral factor of `raw.height`. - **options.create** (Object) - Optional - describes a new image to be created. - **options.create.width** (number) - Optional - integral number of pixels wide. - **options.create.height** (number) - Optional - integral number of pixels high. - **options.create.channels** (number) - Optional - integral number of channels, either 3 (RGB) or 4 (RGBA). - **options.create.background** (string | Object) - Optional - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. - **options.create.pageHeight** (number) - Optional - The pixel height of each page/frame for animated images, must be an integral factor of `create.height`. - **options.create.noise** (Object) - Optional - describes a noise to be created. - **options.create.noise.type** (string) - Optional - type of generated noise, currently only `gaussian` is supported. - **options.create.noise.mean** (number) - Optional - Default: `128` - Mean value of pixels in the generated noise. - **options.create.noise.sigma** (number) - Optional - Default: `30` - Standard deviation of pixel values in the generated noise. - **options.text** (Object) - Optional - describes a new text image to be created. - **options.text.text** (string) - Optional - text to render as a UTF-8 string. It can contain Pango markup, for example `LeMonde`. - **options.text.font** (string) - Optional - font name to render with. - **options.text.fontfile** (string) - Optional - absolute filesystem path to a font file that can be used by `font`. - **options.text.width** (number) - Optional - Default: `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) - Optional - Default: `0` - Maximum 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) - Optional - Default: `'left'` - Alignment style for multi-line text (`'left'`, `'centre'`, `'center'`, `'right'`). - **options.text.justify** (boolean) - Optional - Default: `false` - set this to true to apply justification to the text. - **options.text.dpi** (number) - Optional - Default: `72` - the resolution (size) at which to render the text. Does not take effect if `height` is specified. - **options.text.rgba** (boolean) - Optional - Default: `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) - Optional - Default: `0` - text line height in points. Will use the font line height if none is specified. - **options.text.wrap** (string) - Optional - Default: `'word'` - word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'. - **options.join** (Object) - Optional - describes how an array of input images should be joined. - **options.join.across** (number) - Optional - Default: `1` - number of images to join horizontally. - **options.join.animated** (boolean) - Optional - Default: `false` - set this to `true` to join the images as an animated image. - **options.join.shim** (number) - Optional - Default: `0` - number of pixels to insert between joined images. - **options.join.background** (string | Object) - Optional - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. - **options.join.halign** (string) - Optional - Default: `'left'` - horizontal alignment style for images joined horizontally (`'left'`, `'centre'`, `'center'`, `'right'`). - **options.join.valign** (string) - Optional - Default: `'top'` - vertical alignment style for images joined vertically (`'top'`, `'centre'`, `'center'`, `'bottom'`). - **options.tiff** (Object) - Optional - Describes TIFF specific options. - **options.tiff.subifd** (number) - Optional - Default: `-1` - Sub Image File Directory to extract for OME-TIFF, defaults to main image. - **options.svg** (Object) - Optional - Describes SVG specific options. - **options.svg.stylesheet** (string) - Optional - Custom CSS for SVG input, applied with a User Origin during the CSS cascade. - **options.svg.highBitdepth** (boolean) - Optional - Default: `false` - Set to `true` to render SVG input at 32-bits per channel (128-bit) instead of 8-bits per channel (32-bit) RGBA. ``` -------------------------------- ### Build sharp from source using npm Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/install.md Use these commands to build the sharp library from source, which will attempt to locate a globally-installed libvips. ```sh npm install sharp npm explore sharp -- npm run build ``` -------------------------------- ### Get Auto-Oriented Dimensions from Metadata Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-input.md Extracts `width` and `height` from the `autoOrient` property of the metadata, which accounts for EXIF orientation. ```js // Get dimensions taking EXIF Orientation into account. const { autoOrient } = await sharp(input).metadata(); const { width, height } = autoOrient; ``` -------------------------------- ### concurrency([concurrency]) Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-utility.md Gets or sets the maximum number of threads libvips should use to process each image. Returns the current concurrency. ```APIDOC ## concurrency([concurrency]) ### Description 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 creating new threads. This method always returns the current concurrency. ### Method Signature concurrency([concurrency]) ### Parameters - **[concurrency]** (number) - Optional - The maximum number of threads. A value of `0` will reset this to the number of CPU cores. ### Returns - **concurrency** (number) - The current concurrency. ### Example ```js const threads = sharp.concurrency(); // 4 sharp.concurrency(2); // 2 sharp.concurrency(0); // 4 ``` ``` -------------------------------- ### Get Image Metadata Asynchronously Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-input.md Retrieves image metadata using an async/await pattern, returning a Promise that resolves with the metadata object. ```js const metadata = await sharp(input).metadata(); ``` -------------------------------- ### Get Image Statistics with Promise in JavaScript Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-input.md Use `sharp().stats()` with a Promise to asynchronously retrieve channel-wise statistics and opacity information for an image. ```js const image = sharp(inputJpg); image .stats() .then(function(stats) { // stats contains the channel-wise statistics array and the isOpaque value }); ``` -------------------------------- ### simd([simd]) Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-utility.md Gets or sets the use of SIMD vector unit instructions for performance improvement in operations like resize, blur, and sharpen. ```APIDOC ## simd([simd]) ### Description Get and set use of SIMD vector unit instructions. Requires libvips to have been compiled with highway 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. ### Method Signature simd([simd]) ### Parameters - **[simd]** (boolean) - Optional - Default `true`. Whether to enable or disable SIMD. ### Returns - **boolean** (boolean) - `true` if the runtime use of highway is currently enabled, `false` otherwise. ### Example ```js const simd = sharp.simd(); // simd is `true` if the runtime use of highway is currently enabled ``` ### Example ```js const simd = sharp.simd(false); // prevent libvips from using highway at runtime ``` ``` -------------------------------- ### Run Sharp Benchmark Test with Docker Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/performance.md This snippet clones the sharp repository, navigates to the benchmark test directory, and executes the tests using a Docker script. ```sh git clone https://github.com/lovell/sharp.git cd sharp/test/bench ./run-with-docker.sh ``` -------------------------------- ### Process Image Based on Metadata Using Promises Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-input.md Demonstrates chaining operations using Promises to resize an image to half its original width and convert it to WebP, based on retrieved metadata. ```js const image = sharp(inputJpg); image .metadata() .then(function(metadata) { return image .resize(Math.round(metadata.width / 2)) .webp() .toBuffer(); }) .then(function(data) { // data contains a WebP image half the width and height of the original JPEG }); ``` -------------------------------- ### affine(matrix, [options]) Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-operation.md 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. By default, new pixels are filled with a black background. You can provide a background colour with the `background` option. A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`. ```APIDOC ## affine(matrix, [options]) ### Description Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any. ### Method `affine` ### Parameters #### Method Parameters - **matrix** (Array.<Array.<number>> | Array.<number>) - Required - affine transformation matrix - **options** (Object) - Optional - if present, is an Object with optional attributes. - **background** (String | Object) - Optional - Default: "#000000" - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. - **idx** (Number) - Optional - Default: 0 - input horizontal offset - **idy** (Number) - Optional - Default: 0 - input vertical offset - **odx** (Number) - Optional - Default: 0 - output horizontal offset - **ody** (Number) - Optional - Default: 0 - output vertical offset - **interpolator** (String) - Optional - Default: sharp.interpolators.bicubic - interpolator ### Throws - `Error` Invalid parameters ### Example ```js const pipeline = sharp() .affine([[1, 0.3], [0.1, 0.7]], { background: 'white', interpolator: sharp.interpolators.nohalo }) .toBuffer((err, outputBuffer, info) => { // outputBuffer contains the transformed image // info.width and info.height contain the new dimensions }); inputStream .pipe(pipeline); ``` ``` -------------------------------- ### Write Image to File (JavaScript) Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-output.md Writes processed image data to a file, inferring the output format from the file extension. Examples show both callback and Promise-based error handling. ```javascript sharp(input) .toFile('output.png', (err, info) => { ... }); ``` ```javascript sharp(input) .toFile('output.png') .then(info => { ... }) .catch(err => { ... }); ``` -------------------------------- ### Set MALLOC_ARENA_MAX for glibc Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/performance.md Reduces memory fragmentation when using the default Linux glibc memory allocator by limiting the number of memory pools. This environment variable should be set before the Node.js process starts. ```sh export MALLOC_ARENA_MAX="2" ``` -------------------------------- ### tile([options]) Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-output.md Configures the Sharp instance to produce tile-based deep zoom (image pyramid) output. This method allows setting various options for tile generation, including size, overlap, rotation, background color, pyramid depth, and output container/layout. It integrates with `toFormat`, `jpeg`, `png`, `webp`, and `toFile` for output. ```APIDOC ## tile([options])\n\n### Description\nConfigures the Sharp instance to produce tile-based deep zoom (image pyramid) output. This method allows setting various options for tile generation, including size, overlap, rotation, background color, pyramid depth, and output container/layout. It integrates with `toFormat`, `jpeg`, `png`, `webp`, and `toFile` for output.\n\n### Method Name\ntile\n\n### Parameters\n#### Options Object\n- **options** (Object) - Optional - An object containing configuration options for tile generation.\n - **size** (number) - Optional - Default: `256` - tile size in pixels, a value between 1 and 8192.\n - **overlap** (number) - Optional - Default: `0` - tile overlap in pixels, a value between 0 and 8192.\n - **angle** (number) - Optional - Default: `0` - tile angle of rotation, must be a multiple of 90.\n - **background** (string | Object) - Optional - Default: `"{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.\n - **depth** (string) - Optional - how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout.\n - **skipBlanks** (number) - Optional - Default: `-1` - Threshold to skip tile generation. Range is 0-255 for 8-bit images, 0-65535 for 16-bit images. Default is 5 for `google` layout, -1 (no skip) otherwise.\n - **container** (string) - Optional - Default: `"'fs'"` - tile container, with value `fs` (filesystem) or `zip` (compressed file).\n - **layout** (string) - Optional - Default: `"'dz'"` - filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`.\n - **centre** (boolean) - Optional - Default: `false` - centre image in tile.\n - **center** (boolean) - Optional - Default: `false` - alternative spelling of centre.\n - **id** (string) - Optional - Default: `"'https://example.com/iiif'"` - when `layout` is `iiif`/`iiif3`, sets the `@id`/`id` attribute of `info.json`\n - **basename** (string) - Optional - the name of the directory within the zip file when container is `zip`.\n\n### Throws\n- `Error` - Invalid parameters\n\n### Returns\n`Sharp` - Returns the Sharp instance for chaining.\n\n### Usage Examples\n```js\nsharp('input.tiff')\n .png()\n .tile({\n size: 512\n })\n .toFile('output.dz', function(err, info) {\n // output.dzi is the Deep Zoom XML definition\n // output_files contains 512x512 tiles grouped by zoom level\n });\n```\n```js\nconst zipFileWithTiles = await sharp(input)\n .tile({ basename: "tiles" })\n .toBuffer();\n```\n```js\nconst iiififier = sharp().tile({ layout: "iiif" });\nreadableStream\n .pipe(iiififier)\n .pipe(writeableStream);\n``` ``` -------------------------------- ### Extend Image with Solid Color Padding (JavaScript) Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-resize.md Use this example to add a solid color row of pixels to the bottom edge of an image. The `background` property can accept a color string like 'red'. ```js // Add a row of 10 red pixels to the bottom sharp(input) .extend({ bottom: 10, background: 'red' }) ... ``` -------------------------------- ### webp([options]) Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-output.md Applies WebP output options to the image. This method allows fine-grained control over WebP compression, quality, and animation settings, returning a `Sharp` instance for further processing. ```APIDOC ## Method: webp([options]) ### Description Use these WebP options for output image. ### Signature `webp([options]) ⇒ Sharp` ### Parameters - **[options]** (Object) - Optional - output options - **[options.quality]** (number) - Optional - Default: 80 - quality, integer 1-100 - **[options.alphaQuality]** (number) - Optional - Default: 100 - quality of alpha layer, integer 0-100 - **[options.lossless]** (boolean) - Optional - Default: false - use lossless compression mode - **[options.nearLossless]** (boolean) - Optional - Default: false - use near_lossless compression mode - **[options.smartSubsample]** (boolean) - Optional - Default: false - use high quality chroma subsampling - **[options.smartDeblock]** (boolean) - Optional - Default: false - auto-adjust the deblocking filter, can improve low contrast edges (slow) - **[options.preset]** (string) - Optional - Default: "default" - named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text - **[options.effort]** (number) - Optional - Default: 4 - CPU effort, between 0 (fastest) and 6 (slowest) - **[options.loop]** (number) - Optional - Default: 0 - number of animation iterations, use 0 for infinite animation - **[options.delay]** (number | Array.) - Optional - delay(s) between animation frames (in milliseconds) - **[options.minSize]** (boolean) - Optional - Default: false - prevent use of animation key frames to minimise file size (slow) - **[options.mixed]** (boolean) - Optional - Default: false - allow mixture of lossy and lossless animation frames (slow) - **[options.exact]** (boolean) - Optional - Default: false - preserve the colour data in transparent pixels - **[options.force]** (boolean) - Optional - Default: true - force WebP output, otherwise attempt to use input format ### Throws - `Error` - Invalid options ### Code Examples ```js // Convert any input to lossless WebP output const data = await sharp(input) .webp({ lossless: true }) .toBuffer(); ``` ```js // Optimise the file size of an animated WebP const outputWebp = await sharp(inputWebp, { animated: true }) .webp({ effort: 6 }) .toBuffer(); ``` ``` -------------------------------- ### withMetadata([options]) Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-output.md Keep most metadata (EXIF, XMP, IPTC) from the input image in the output image. This will also convert to and add a web-friendly sRGB ICC profile if appropriate. Allows orientation and density to be set or updated. ```APIDOC ## withMetadata([options]) ### Description Keep most metadata (EXIF, XMP, IPTC) from the input image in the output image. This will also convert to and add a web-friendly sRGB ICC profile if appropriate. Allows orientation and density to be set or updated. ### Method Signature withMetadata([options]) ⇒ `Sharp` ### Parameters - **[options]** (`Object`) - Optional - - **[options.orientation]** (`number`) - Optional - Used to update the EXIF `Orientation` tag, integer between 1 and 8. - **[options.density]** (`number`) - Optional - Number of pixels per inch (DPI). ### Throws - `Error` - Invalid parameters ### Examples ```js const outputSrgbWithMetadata = await sharp(inputRgbWithMetadata) .withMetadata() .toBuffer(); ``` ```js // Set output metadata to 96 DPI const data = await sharp(input) .withMetadata({ density: 96 }) .toBuffer(); ``` ``` -------------------------------- ### pipelineColourspace([colourspace]) ⇒ Sharp Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-colour.md 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](#tocolourspace). ```APIDOC ## pipelineColourspace([colourspace]) ⇒ `Sharp` ### Description 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](#tocolourspace). ### Method Signature `pipelineColourspace([colourspace]) ⇒ Sharp` ### Parameters #### Method Parameters - **[colourspace]** (`string`) - Optional - pipeline colourspace e.g. `rgb16`, `scrgb`, `lab`, `grey16` [...](https://www.libvips.org/API/current/enum.Interpretation.html) ### 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') .toColourspace('srgb') .toFile('16bpc-pipeline-to-8bpc-output.png') ``` ### Returns `Sharp` object. ``` -------------------------------- ### Convert Image to HDR Using Gain Map with Sharp Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-output.md Utilize `withGainMap` to convert the main image to HDR using its gain map metadata before further processing, discarding the original gain map. If the output is JPEG, a new ISO 21496-1 gain map will be generated. ```js const outputWithRegeneratedGainMap = await sharp(inputWithGainMap) .withGainMap() .toBuffer(); ``` -------------------------------- ### clone() Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-constructor.md 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. ```APIDOC ## clone() ### Description 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. ### Signature `clone() ### Returns - `Sharp` - A new Sharp instance that inherits the input of its parent. ### Examples ```js // firstWritableStream receives auto-rotated, resized readableStream // secondWritableStream receives auto-rotated, extracted region of readableStream const pipeline = sharp().rotate(); pipeline .clone() .resize(800, 600) .pipe(firstWritableStream); pipeline .clone() .extract({ left: 20, top: 20, width: 100, height: 100 }) .pipe(secondWritableStream); readableStream.pipe(pipeline); ``` ```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 sharpStream = sharp(); const promises = []; promises.push( sharpStream .clone() .jpeg({ quality: 100 }) .toFile("originalFile.jpg") ); promises.push( sharpStream .clone() .resize({ width: 500 }) .jpeg({ quality: 80 }) .toFile("optimized-500.jpg") ); promises.push( sharpStream .clone() .webp({ quality: 80 }) .toFile("optimized-500.webp") ); const res = await fetch("https://www.example.com/some-file.jpg") Readable.fromWeb(res.body).pipe(sharpStream); await Promise.all(promises); ``` ``` -------------------------------- ### Access Internal Task Counters in JavaScript Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-utility.md Call `sharp.counters()` to get an object containing the current number of queued and actively processed tasks within the sharp module, providing insight into internal task management. ```js const counters = sharp.counters(); // { queue: 2, process: 4 } ``` -------------------------------- ### Convert to Lossless JP2 Output with Sharp Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-output.md Use this snippet to convert any input image to a lossless JP2 format. Requires `libvips` compiled with OpenJPEG support. ```js const data = await sharp(input) .jp2({ lossless: true }) .toBuffer(); ``` -------------------------------- ### Migrating Deprecated Resize Functions in sharp v0.21.0 Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/changelog/v0.21.0.md Illustrates the migration path for deprecated resize-related functions, showing how old calls are replaced by options within the `resize` function. ```javascript embed('north') ``` ```javascript resize(width, height, { fit: 'contain', position: 'north' }) ``` ```javascript crop('attention') ``` ```javascript resize(width, height, { fit: 'cover', position: 'attention' }) ``` ```javascript max().withoutEnlargement() ``` ```javascript resize(width, height, { fit: 'inside', withoutEnlargement: true }) ``` -------------------------------- ### Set Processing Timeout with Sharp in JavaScript Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-output.md Use this snippet to limit the execution time of image processing operations. The timeout clock starts when the input image is opened, and errors can be caught to handle timeout exceptions. ```js // Ensure processing takes no longer than 3 seconds try { const data = await sharp(input) .blur(1000) .timeout({ seconds: 3 }) .toBuffer(); } catch (err) { if (err.message.includes('timeout')) { ... } } ``` -------------------------------- ### Set UV_THREADPOOL_SIZE for Node.js Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/performance.md Increases the libuv thread pool size to match the number of physical CPU cores, optimizing parallel image processing with sharp. This environment variable should be set before the Node.js process starts. ```sh export UV_THREADPOOL_SIZE="$(lscpu -p | egrep -v "^#" | sort -u -t, -k 2,4 | wc -l)" ``` -------------------------------- ### Run Deno application with sharp Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/install.md Execute a Deno application that uses sharp, ensuring necessary permissions are granted for file system and environment access. ```sh deno run --allow-env --allow-ffi --allow-read --allow-sys ... ``` -------------------------------- ### Stream IIIF Tiles using Sharp Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-output.md This snippet illustrates how to pipe a readable stream through `sharp` to generate IIIF-compliant tiles, which are then piped to a writable stream. ```js const iiififier = sharp().tile({ layout: "iiif" }); readableStream .pipe(iiififier) .pipe(writeableStream); ``` -------------------------------- ### avif([options]) Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-output.md Use these AVIF options for output image. AVIF image sequences are not supported. ```APIDOC ## avif ### Description Use these AVIF options for output image. AVIF image sequences are not supported. ### Signature avif([options]) ⇒ Sharp ### Parameters #### Options Object - **quality** (number) - Optional - Default: 50 - quality, integer 1-100 - **lossless** (boolean) - Optional - Default: false - use lossless compression - **effort** (number) - Optional - Default: 4 - CPU effort, between 0 (fastest) and 9 (slowest) - **chromaSubsampling** (string) - Optional - Default: '4:4:4' - set to '4:2:0' to use chroma subsampling - **bitdepth** (number) - Optional - Default: 8 - set bitdepth to 8, 10 or 12 bit - **tune** (string) - Optional - Default: 'auto' - tune output for a quality metric, one of 'auto' (default), 'iq', 'psnr' or 'ssim' ### Example ```js const data = await sharp(input) .avif({ effort: 2 }) .toBuffer(); ``` ```js const data = await sharp(input) .avif({ lossless: true }) .toBuffer(); ``` ### Returns - **Type**: Sharp - **Description**: A Sharp instance for chaining operations. ``` -------------------------------- ### Get and Set libvips Concurrency in JavaScript Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-utility.md Use `sharp.concurrency()` to retrieve the current thread limit or set a new maximum number of threads for libvips to use per image. A value of `0` resets the concurrency to the number of CPU cores. ```js const threads = sharp.concurrency(); // 4 sharp.concurrency(2); // 2 sharp.concurrency(0); // 4 ``` -------------------------------- ### Clone Sharp Instance for Multiple Output Streams Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-constructor.md Use `clone()` to create multiple processing pipelines from a single input stream, allowing different transformations (e.g., resize, extract) to be applied concurrently to the same image data. ```javascript // firstWritableStream receives auto-rotated, resized readableStream // secondWritableStream receives auto-rotated, extracted region of readableStream const pipeline = sharp().rotate(); pipeline .clone() .resize(800, 600) .pipe(firstWritableStream); pipeline .clone() .extract({ left: 20, top: 20, width: 100, height: 100 }) .pipe(secondWritableStream); readableStream.pipe(pipeline); ``` -------------------------------- ### Process Image from Remote URL via Node.js Streams Source: https://github.com/lovell/sharp/blob/main/docs/src/content/docs/api-constructor.md This example demonstrates processing an image fetched from a URL using Node.js streams. It resizes the image and logs its height upon receiving the 'info' event before piping to a writable stream. ```javascript // Read image data from remote URL, // resize to 300 pixels wide, // emit an 'info' event with calculated dimensions // and finally write image data to writableStream const { body } = await fetch('https://...'); const readableStream = Readable.fromWeb(body); const transformer = sharp() .resize(300) .on('info', ({ height }) => { console.log(`Image height is ${height}`); }); readableStream.pipe(transformer).pipe(writableStream); ```