### Install Sharp with Deno Source: https://sharp.pixelplumbing.com/install Use this command to add the Sharp package to Deno and an example of how to run a Deno script that uses it. Ensure you have the necessary permissions. ```bash deno add --quiet npm:sharp deno run --allow-env --allow-ffi --allow-read --allow-sys ... ``` -------------------------------- ### Install Sharp and Build from Source Source: https://sharp.pixelplumbing.com/install Installs the Sharp package and then runs the build script to compile native addons. This process searches for a globally installed libvips. ```bash npm install sharp npm explore sharp -- npm run build ``` -------------------------------- ### Install Sharp with bun Source: https://sharp.pixelplumbing.com/install Use this command to install the Sharp package using bun. ```bash bun add sharp ``` -------------------------------- ### Install Sharp with npm Source: https://sharp.pixelplumbing.com/install Use this command to install the Sharp package using npm. ```bash npm install sharp ``` -------------------------------- ### Install Sharp with yarn Source: https://sharp.pixelplumbing.com/install Use this command to install the Sharp package using yarn. ```bash yarn add sharp ``` -------------------------------- ### Install sharp Module Source: https://sharp.pixelplumbing.com/ Install the sharp module using npm. This is the primary step to begin using its image processing capabilities. ```bash npm install sharp ``` -------------------------------- ### Install Sharp with pnpm Source: https://sharp.pixelplumbing.com/install Use this command to install the Sharp package using pnpm. ```bash pnpm add sharp ``` -------------------------------- ### Install Node-Addon-API and Node-Gyp Source: https://sharp.pixelplumbing.com/install Installs the node-addon-api and node-gyp packages, which are build dependencies for compiling native addons. Use this if they cannot be found automatically. ```bash npm install --save node-addon-api node-gyp ``` -------------------------------- ### Cross-platform npm install for Linux (glibc) Source: https://sharp.pixelplumbing.com/install Install Sharp for Linux on Intel x64 CPUs using glibc with npm. This is typically used for Debian-based distributions. ```bash npm install --cpu=x64 --os=linux --libc=glibc sharp ``` -------------------------------- ### Install Sharp with WebAssembly Runtime Source: https://sharp.pixelplumbing.com/install Installs Sharp along with the optional @img/sharp-wasm32 package for multi-threaded Wasm runtime environments. Not supported in web browsers or single-threaded environments. ```bash npm install sharp @img/sharp-wasm32 ``` -------------------------------- ### Cross-platform npm install for Linux (musl) Source: https://sharp.pixelplumbing.com/install Install Sharp for Linux on Intel x64 CPUs using musl with npm. This is typically used for Alpine Linux distributions. ```bash npm install --cpu=x64 --os=linux --libc=musl sharp ``` -------------------------------- ### Configure serverless-esbuild for Sharp Binaries Source: https://sharp.pixelplumbing.com/install Specify platform-specific Sharp binary installation for serverless-esbuild in serverless.yml. ```yaml custom: esbuild: external: - sharp packagerOptions: scripts: - npm install --os=linux --cpu=x64 sharp ``` -------------------------------- ### Cross-platform npm install for macOS Source: https://sharp.pixelplumbing.com/install Install Sharp for macOS on both Intel x64 and ARM64 architectures using npm with specific --cpu and --os flags. This is useful for CI/CD environments or when building for multiple macOS targets. ```bash npm install --cpu=x64 --os=darwin sharp npm install --cpu=arm64 --os=darwin sharp ``` -------------------------------- ### Clone and Run Sharp Benchmark Tests Source: https://sharp.pixelplumbing.com/performance Clone the Sharp repository and navigate to the benchmark test directory to run performance comparisons using Docker. This requires Docker to be installed. ```bash git clone https://github.com/lovell/sharp.git cd sharp/test/bench ./run-with-docker.sh ``` -------------------------------- ### Generate Tiles to a Compressed Buffer Source: https://sharp.pixelplumbing.com/api-output This example demonstrates how to generate tiles and output them as a compressed buffer, suitable for direct use or transmission. The `basename` option specifies the name of the directory within the zip file. ```javascript const zipFileWithTiles = await sharp(input) .tile({ basename: "tiles" }) .toBuffer(); ``` -------------------------------- ### Get Sharp and Dependencies Versions Source: https://sharp.pixelplumbing.com/api-utility Access the `versions` object to retrieve version numbers for sharp, libvips, and prebuilt dependencies. ```javascript console.log(sharp.versions); ``` -------------------------------- ### Clone for Multiple File Outputs with Promises Source: https://sharp.pixelplumbing.com/api-constructor This example uses clone() to generate multiple output files with different formats and quality settings, leveraging Promises to manage asynchronous operations. Ensure the 'fetch' API and 'Readable.fromWeb' are available in your environment. ```javascript 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); ``` -------------------------------- ### sharp.simd Source: https://sharp.pixelplumbing.com/api-utility Get and set use of SIMD vector unit instructions. ```APIDOC ## 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. ### Parameters #### simd - **simd** (`boolean`) - Optional - `true` to enable SIMD, `false` to disable. ### Returns - `boolean` - The current SIMD setting. ### Example (Get SIMD status) ```javascript const simd = sharp.simd(); // simd is `true` if the runtime use of highway is currently enabled ``` ### Example (Set SIMD status) ```javascript const simd = sharp.simd(false); // prevent libvips from using highway at runtime ``` ``` -------------------------------- ### Optimize Animated WebP File Size Source: https://sharp.pixelplumbing.com/api-output This example demonstrates how to optimize the file size of an animated WebP image. It utilizes the 'effort' option to increase CPU effort for better compression. Ensure the input WebP file is specified with the 'animated: true' option. ```javascript const outputWebp = await sharp(inputWebp, { animated: true }) .webp({ effort: 6 }) .toBuffer(); ``` -------------------------------- ### Resize with Cover Strategy using Stream Transformer Source: https://sharp.pixelplumbing.com/api-resize Resizes an image to cover a specified area using the 'cover' fit strategy and entropy-based cropping. This example demonstrates using Sharp as a stream transformer for piped input and output. ```javascript const transformer = sharp() .resize({ width: 200, height: 200, fit: sharp.fit.cover, position: sharp.strategy.entropy }); // Read image data from readableStream // Write 200px square auto-cropped image data to writableStream readableStream .pipe(transformer) .pipe(writableStream); ``` -------------------------------- ### Unblock JPEG and PNG Buffer/Stream input Source: https://sharp.pixelplumbing.com/api-utility This example demonstrates how to allow only JPEG and PNG files loaded from a Buffer or Stream, while blocking all other input operations. ```javascript sharp.block({ operation: ['VipsForeignLoad'] }); sharp.unblock({ operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer'] }); ``` -------------------------------- ### Process Image Based on Metadata Source: https://sharp.pixelplumbing.com/api-input Chain metadata retrieval with image processing operations. This example resizes an image to half its original width and converts it to WebP format after fetching its metadata. ```javascript 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 }); ``` -------------------------------- ### Clone for Multiple Output Streams Source: https://sharp.pixelplumbing.com/api-constructor Use clone() to create separate processing pipelines that share a common input stream. This example demonstrates piping to two different writable streams after cloning the initial pipeline. ```javascript 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); ``` -------------------------------- ### Processing Raw Pixel Data with toBuffer Source: https://sharp.pixelplumbing.com/api-output This example shows how to extract raw pixel data, modify it using `Uint8ClampedArray`, and then re-process it with Sharp. It's useful for direct pixel manipulation and creating new images from modified data. ```javascript const { data, info } = await sharp('my-image.jpg') // output the raw pixels .raw() .toBuffer({ resolveWithObject: true }); // create a more type safe way to work with the raw pixel data // this will not copy the data, instead it will change `data`s underlying ArrayBuffer // so `data` and `pixelArray` point to the same memory location const pixelArray = new Uint8ClampedArray(data.buffer); // When you are done changing the pixelArray, sharp takes the `pixelArray` as an input const { width, height, channels } = info; await sharp(pixelArray, { raw: { width, height, channels } }) .toFile('my-changed-image.jpg'); ``` -------------------------------- ### sharp.cache Source: https://sharp.pixelplumbing.com/api-utility Gets or sets the limits of libvips' operation cache and returns cache statistics. ```APIDOC ## cache ### Description 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 - **memory** (`number`) - Optional - The maximum memory in MB to use for this cache. Default is `50`. - **files** (`number`) - Optional - The maximum number of files to hold open. Default is `20`. - **items** (`number`) - Optional - The maximum number of operations to cache. Default is `100`. ### Example (Get Cache Stats) ```javascript const stats = sharp.cache(); ``` ### Example (Set Cache Limits) ```javascript sharp.cache( { items: 200 } ); sharp.cache( { files: 0 } ); sharp.cache(false); ``` ``` -------------------------------- ### Destructure Specific Statistics Source: https://sharp.pixelplumbing.com/api-input This example demonstrates how to directly destructure specific statistical properties like entropy, sharpness, and dominant color from the result of the stats() method using async/await. ```javascript const { entropy, sharpness, dominant } = await sharp(input).stats(); const { r, g, b } = dominant; ``` -------------------------------- ### Fontconfig Error Example Source: https://sharp.pixelplumbing.com/install This error occurs on Linux systems when fontconfig configuration is not found. It indicates an issue with font discovery. ```text Fontconfig error: Cannot load default config file ``` -------------------------------- ### Convert SVG to LZW TIFF Source: https://sharp.pixelplumbing.com/api-output This example demonstrates converting an SVG input to a TIFF file using LZW compression and a bit depth of 1. The output is saved to a file. ```javascript sharp('input.svg') .tiff({ compression: 'lzw', bitdepth: 1 }) .toFile('1-bpp-output.tiff') .then(info => { ... }); ``` -------------------------------- ### Set UV_THREADPOOL_SIZE for Node.js Source: https://sharp.pixelplumbing.com/performance Set the UV_THREADPOOL_SIZE environment variable to match the number of physical CPU cores to increase the number of images Node.js can process in parallel. This should be done before the Node.js process starts. ```bash export UV_THREADPOOL_SIZE="$(lscpu -p | egrep -v \"^#\" | sort -u -t, -k 2,4 | wc -l)" ``` -------------------------------- ### Get Supported Image Formats Source: https://sharp.pixelplumbing.com/api-utility The `format` object contains boolean properties indicating support for various input and output image formats. ```javascript console.log(sharp.format); ``` -------------------------------- ### Normalise Image Contrast Source: https://sharp.pixelplumbing.com/api-operation Enhances image contrast by stretching luminance to a full dynamic range. This example uses default percentile ranges (1% to 99%). ```javascript const output = await sharp(input) .normalise() .toBuffer(); ``` -------------------------------- ### Perform Bitwise AND on Image Channels with Sharp Source: https://sharp.pixelplumbing.com/api-channel Use bandbool with sharp.bool.and to perform a bitwise AND operation on all input image channels, producing a single-channel output. Example shows R & G & B calculation. ```javascript sharp('3-channel-rgb-input.png') .bandbool(sharp.bool.and) .toFile('1-channel-output.png', function (err, info) { // The output will be a single channel image where each pixel `P = R & G & B`. // If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]` // then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`. }); ``` -------------------------------- ### Set pipeline and output colourspace Source: https://sharp.pixelplumbing.com/api-colour Configure the image processing pipeline to use a specific colourspace and define the output colourspace. This example demonstrates running the pipeline in 16 bits per channel RGB and converting the final result to 8 bits per channel sRGB. ```javascript // 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') ``` -------------------------------- ### Output Image to AVIF Uint8Array with Base64 Conversion Source: https://sharp.pixelplumbing.com/api-output This snippet demonstrates converting an image to AVIF format and then to a Uint8Array, followed by conversion to a Base64 string. Ensure the AVIF format is supported by your Sharp installation. ```javascript const { data } = await sharp(input) .avif() .toUint8Array(); const base64String = data.toBase64(); ``` -------------------------------- ### Unblock specific input operations Source: https://sharp.pixelplumbing.com/api-utility Use `sharp.unblock` in conjunction with `sharp.block` to create an allowlist of operations. This example blocks all input operations except for WebP files loaded from the filesystem. ```javascript sharp.block({ operation: ['VipsForeignLoad'] }); sharp.unblock({ operation: ['VipsForeignLoadWebpFile'] }); ``` -------------------------------- ### Normalise Image with Custom Range Source: https://sharp.pixelplumbing.com/api-operation Enhances image contrast using custom lower and upper percentile bounds. This example stretches luminance across the entire 0% to 100% range. ```javascript const output = await sharp(input) .normalise({ lower: 0, upper: 100 }) .toBuffer(); ``` -------------------------------- ### Get Task Counters Source: https://sharp.pixelplumbing.com/api-utility Access `sharp.counters()` to get an object containing the number of queued tasks and currently processing resize tasks. ```javascript const counters = sharp.counters(); // { queue: 2, process: 4 } ``` -------------------------------- ### sharp.concurrency Source: https://sharp.pixelplumbing.com/api-utility Gets or sets the maximum number of threads libvips should use to process each image. ```APIDOC ## 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. ### Parameters #### concurrency - **concurrency** (`number`) - Optional - The maximum number of threads to use. A value of `0` will reset this to the number of CPU cores. ### Returns - `number` - The current concurrency. ### Example ```javascript const threads = sharp.concurrency(); // e.g., 4 sharp.concurrency(2); // Sets concurrency to 2 sharp.concurrency(0); // Resets concurrency to the number of CPU cores ``` ``` -------------------------------- ### clone() Source: https://sharp.pixelplumbing.com/api-constructor Takes a snapshot of the Sharp instance, returning a new instance. Cloned instances inherit the input of their parent instance, enabling multiple output Streams and processing pipelines to share a single input Stream. ```APIDOC ## clone() ### Description Creates a "snapshot" of the current Sharp instance, returning a new, independent Sharp instance. This is useful for creating multiple processing pipelines that share the same input stream. ### Method `clone()` ### Parameters This method does not accept any parameters. ### Returns - `Sharp` - A new Sharp instance with the same input as the original. ### Example ```javascript // First writable stream receives auto-rotated, resized readableStream // Second writable stream 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); ``` ### Example 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); ``` ``` -------------------------------- ### png([options]) Source: https://sharp.pixelplumbing.com/api-output Configures the Sharp image processing pipeline to output an image in PNG format. It accepts an options object to customize the PNG output. ```APIDOC ## png([options]) ### Description Use these PNG options for output image. By default, PNG output is full colour at 8 bits per pixel. Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel. Set `palette` to `true` for slower, indexed PNG output. For 16 bits per pixel output, convert to `rgb16` via toColourspace. ### Method `png` ### Parameters #### Options Object - **options.progressive** (boolean) - Optional - `false` - use progressive (interlace) scan - **options.compressionLevel** (number) - Optional - `6` - zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest) - **options.adaptiveFiltering** (boolean) - Optional - `false` - use adaptive row filtering - **options.palette** (boolean) - Optional - `false` - quantise to a palette-based image with alpha transparency support - **options.quality** (number) - Optional - `100` - use the lowest number of colours needed to achieve given quality, sets `palette` to `true` - **options.effort** (number) - Optional - `7` - CPU effort, between 1 (fastest) and 10 (slowest), sets `palette` to `true` - **options.colours** (number) - Optional - `256` - maximum number of palette entries, sets `palette` to `true` - **options.colors** (number) - Optional - `256` - alternative spelling of `options.colours`, sets `palette` to `true` - **options.dither** (number) - Optional - `1.0` - level of Floyd-Steinberg error diffusion, sets `palette` to `true` - **options.force** (boolean) - Optional - `true` - force PNG output, otherwise attempt to use input format ### Throws - `Error` Invalid options ### Examples ```javascript // Convert any input to full colour PNG output const data = await sharp(input) .png() .toBuffer(); ``` ```javascript // Convert any input to indexed PNG output (slower) const data = await sharp(input) .png({ palette: true }) .toBuffer(); ``` ```javascript // Output 16 bits per pixel RGB(A) const data = await sharp(input) .toColourspace('rgb16') .png() .toBuffer(); ``` ``` -------------------------------- ### pipelineColourspace Source: https://sharp.pixelplumbing.com/api-colour Sets the colourspace for the image processing pipeline. The input image is converted to this colourspace at the start of the pipeline. ```APIDOC ## pipelineColourspace ### 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. ### Method `pipelineColourspace([colourspace])` ### Parameters #### Path Parameters - **colourspace** (string) - Optional - Pipeline colourspace e.g. `rgb16`, `scrgb`, `lab`, `grey16` … ### Request Example ```javascript // 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') ``` ### Response #### Success Response (200) - **Sharp** - Returns the Sharp instance for chaining. ### Throws - `Error` Invalid parameters ### Since 0.29.0 ``` -------------------------------- ### Extract Region, Resize, then Extract Again Source: https://sharp.pixelplumbing.com/api-resize Demonstrates a fixed operation order: extract a region, resize the image, and then extract another region from the resized image. ```javascript sharp(input) .extract({ left: leftOffsetPre, top: topOffsetPre, width: widthPre, height: heightPre }) .resize(width, height) .extract({ left: leftOffsetPost, top: topOffsetPost, width: widthPost, height: heightPost }) .toFile(output, function(err) { // Extract a region, resize, then extract from the resized image }); ``` -------------------------------- ### Get Cache Statistics Source: https://sharp.pixelplumbing.com/api-utility Call `sharp.cache()` without arguments to retrieve statistics about the libvips operation cache. This is useful for understanding memory usage. ```javascript const stats = sharp.cache(); ``` -------------------------------- ### webp([options]) Source: https://sharp.pixelplumbing.com/api-output Configures the output image to be in WebP format with specified options. This method allows fine-grained control over compression, quality, animation, and other WebP-specific features. ```APIDOC ## webp([options]) ### Description Use these WebP options for output image. ### Method `webp` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **options** (Object) - Optional - output options * **options.quality** (number) - Optional - quality, integer 1-100 (default: `80`) * **options.alphaQuality** (number) - Optional - quality of alpha layer, integer 0-100 (default: `100`) * **options.lossless** (boolean) - Optional - use lossless compression mode (default: `false`) * **options.nearLossless** (boolean) - Optional - use near_lossless compression mode (default: `false`) * **options.smartSubsample** (boolean) - Optional - use high quality chroma subsampling (default: `false`) * **options.smartDeblock** (boolean) - Optional - auto-adjust the deblocking filter, can improve low contrast edges (slow) (default: `false`) * **options.preset** (string) - Optional - named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text (default: `"default"`) * **options.effort** (number) - Optional - CPU effort, between 0 (fastest) and 6 (slowest) (default: `4`) * **options.loop** (number) - Optional - number of animation iterations, use 0 for infinite animation (default: `0`) * **options.delay** (number | Array.) - Optional - delay(s) between animation frames (in milliseconds) * **options.minSize** (boolean) - Optional - prevent use of animation key frames to minimise file size (slow) (default: `false`) * **options.mixed** (boolean) - Optional - allow mixture of lossy and lossless animation frames (slow) (default: `false`) * **options.exact** (boolean) - Optional - preserve the colour data in transparent pixels (default: `false`) * **options.force** (boolean) - Optional - force WebP output, otherwise attempt to use input format (default: `true`) ### Request Example ```javascript // Convert any input to lossless WebP output const data = await sharp(input) .webp({ lossless: true }) .toBuffer(); ``` ### Response #### Success Response Returns a Sharp instance for chaining operations. #### Response Example None provided. ### Throws * `Error` Invalid options ``` -------------------------------- ### Unpack Sharp with electron-builder Source: https://sharp.pixelplumbing.com/install Configure electron-builder to unpack Sharp from the ASAR archive. ```json { "build": { "asar": true, "asarUnpack": [ "**/node_modules/sharp/**/*", "**/node_modules/@img/**/*" ] } } ``` -------------------------------- ### Negate Image Source: https://sharp.pixelplumbing.com/api-operation Applies a negation filter to the image. Use this to invert colors. This example negates the entire image including its alpha channel. ```javascript const output = await sharp(input) .negate() .toBuffer(); ``` -------------------------------- ### Sharp Constructor Source: https://sharp.pixelplumbing.com/api-constructor Creates a new Sharp instance for image processing. Supports various input types like Buffers, file paths, and raw pixel data. Options can be provided to control processing behavior, such as error handling, pixel limits, and image orientation. ```APIDOC ## new Sharp([input], [options]) ### Description 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. When using Stream based output, derived attributes are available from the `info` event. Non-critical problems encountered during processing are emitted as `warning` events. Implements the stream.Duplex class. When loading more than one page/frame of an animated image, these are combined as a vertically-stacked “toilet roll” image where the overall height is the `pageHeight` multiplied by the number of `pages`. ### Method `new` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters **input** (`Buffer` | `ArrayBuffer` | `Uint8Array` | `Uint8ClampedArray` | `Int8Array` | `Uint16Array` | `Int16Array` | `Uint32Array` | `Int32Array` | `Float32Array` | `Float64Array` | `string` | `Array`) - Description: If present, can be a Buffer / ArrayBuffer / 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. An array of inputs can be provided, and these will be joined together. JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. **options** (`Object`) - Description: If present, is an Object with optional attributes. - **failOn** (`string`) - Default: "warning" - Description: When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): ‘none’, ‘truncated’, ‘error’, ‘warning’. Higher levels imply lower levels. Invalid metadata will always abort. Use the default ‘warning’ level with untrusted input. - **limitInputPixels** (`number` | `boolean`) - Default: 268402689 - Description: 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). - **limitInputChannels** (`number` | `boolean`) - Default: 5 - Description: Do not process input images where the number of channels exceeds this limit. Assumes image metadata can be trusted. An integral Number of channels, zero or false to remove limit, true to use default limit of 5. - **unlimited** (`boolean`) - Default: false - Description: Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). - **autoOrient** (`boolean`) - Default: false - Description: Set this to `true` to rotate/flip the image to match EXIF `Orientation`, if any. - **sequentialRead** (`boolean`) - Default: true - Description: Set this to `false` to use random access rather than sequential read. Some operations will do this automatically. - **density** (`number`) - Default: 72 - Description: The DPI at which to render SVG and PDF images, in the range 1 to 100000. - **ignoreIcc** (`number`) - Default: false - Description: Should the embedded ICC profile, if any, be ignored. - **pages** (`number`) - Default: 1 - Description: Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages. - **page** (`number`) - Default: 0 - Description: Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based. - **animated** (`boolean`) - Default: false - Description: Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`. - **raw** (`Object`) - Description: Describes raw pixel input image data. See `raw()` for pixel ordering. - **width** (`number`) - Description: Integral number of pixels wide. - **height** (`number`) - Description: Integral number of pixels high. - **channels** (`number`) - Description: Integral number of channels, between 1 and 4. - **premultiplied** (`boolean`) - Description: Specifies that the raw input has already been premultiplied, set to `true` to avoid sharp premultiplying the image. (optional, default `false`) - **pageHeight** (`number`) - Description: The pixel height of each page/frame for animated images, must be an integral factor of `raw.height`. - **create** (`Object`) - Description: Describes a new image to be created. - **width** (`number`) - Description: Integral number of pixels wide. - **height** (`number`) - Description: Integral number of pixels high. - **channels** (`number`) - Description: Integral number of channels, either 3 (RGB) or 4 (RGBA). - **background** (`string` | `Object`) - Description: Parsed by the color module to extract values for red, green, blue and alpha. - **pageHeight** (`number`) - Description: The pixel height of each page/frame for animated images, must be an integral factor of `create.height`. - **noise** (`Object`) - Description: Describes a noise to be created. ### Throws * `Error` Invalid parameters ### Request Example None ### Response #### Success Response None #### Response Example None ``` -------------------------------- ### Image Composite with Transformations Source: https://sharp.pixelplumbing.com/api-composite Demonstrates chaining multiple image transformations including rotation, resizing, flattening, compositing with an overlay image, sharpening, metadata inclusion, and outputting as WebP. ```javascript sharp('input.png') .rotate(180) .resize(300) .flatten( { background: '#ff6600' } ) .composite([{ input: 'overlay.png', gravity: 'southeast' }]) .sharpen() .withMetadata() .webp( { quality: 90 } ) .toBuffer() .then(function(outputBuffer) { // outputBuffer contains upside down, 300px wide, alpha channel flattened // onto orange background, composited with overlay.png with SE gravity, // sharpened, with metadata, 90% quality WebP image data. Phew! }); ``` -------------------------------- ### Block all TIFF input operations Source: https://sharp.pixelplumbing.com/api-utility Use `sharp.block` to prevent specific libvips operations from executing. This example blocks all operations related to loading TIFF files. ```javascript sharp.block({ operation: ['VipsForeignLoadTiff'] }); ``` -------------------------------- ### Generate RGBA Image from Text with Pango Source: https://sharp.pixelplumbing.com/api-constructor Generates an RGBA image from text using Pango markup, specifying font, color, background, and DPI. Requires Pango to be installed. ```javascript // Generate an rgba image from text using pango markup and font await sharp({ text: { text: 'Red!blue', font: 'sans', rgba: true, dpi: 300 } }).toFile('text_rgba.png'); ``` -------------------------------- ### Get Auto-Oriented Dimensions Source: https://sharp.pixelplumbing.com/api-input Retrieve image dimensions that take EXIF Orientation into account. This ensures that the reported width and height reflect the image's intended display orientation. ```javascript // Get dimensions taking EXIF Orientation into account. const { autoOrient } = await sharp(input).metadata(); const { width, height } = autoOrient; ``` -------------------------------- ### raw([options]) Source: https://sharp.pixelplumbing.com/api-output Forces the output to be raw, uncompressed pixel data. Pixel ordering is left-to-right, top-to-bottom, without padding. Channel ordering is RGB or RGBA for non-greyscale colourspaces. ```APIDOC ## raw([options]) ### Description 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 - **options** (Object) - Optional - output options - **options.depth** (string) - Optional - bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex. Default: `"uchar"` ### Throws - `Error` Invalid options ### Example ```javascript // Extract raw, unsigned 8-bit RGB pixel data from JPEG input const { data, info } = await sharp('input.jpg') .raw() .toBuffer({ resolveWithObject: true }); ``` ### Example ```javascript // 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(); ``` ``` -------------------------------- ### Get Image Metadata Source: https://sharp.pixelplumbing.com/api-input Retrieve uncached image metadata without decoding pixel data. This is useful for quickly accessing image properties like dimensions and format before processing. ```javascript const metadata = await sharp(input).metadata(); ``` -------------------------------- ### gif([options]) Source: https://sharp.pixelplumbing.com/api-output Configures the output image to be in GIF format with specified options. This method allows fine-grained control over GIF encoding parameters. ```APIDOC ## gif([options]) ### Description 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. ### Method `gif` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **options** (Object) - Optional - output options * **options.reuse** (boolean) - Optional - re-use existing palette, otherwise generate new (slow) (default: `true`) * **options.progressive** (boolean) - Optional - use progressive (interlace) scan (default: `false`) * **options.colours** (number) - Optional - maximum number of palette entries, including transparency, between 2 and 256 (default: `256`) * **options.colors** (number) - Optional - alternative spelling of `options.colours` (default: `256`) * **options.effort** (number) - Optional - CPU effort, between 1 (fastest) and 10 (slowest) (default: `7`) * **options.dither** (number) - Optional - level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) (default: `1.0`) * **options.interFrameMaxError** (number) - Optional - maximum inter-frame error for transparency, between 0 (lossless) and 32 (default: `0`) * **options.interPaletteMaxError** (number) - Optional - maximum inter-palette error for palette reuse, between 0 and 256 (default: `3`) * **options.keepDuplicateFrames** (boolean) - Optional - keep duplicate frames in the output instead of combining them (default: `false`) * **options.loop** (number) - Optional - number of animation iterations, use 0 for infinite animation (default: `0`) * **options.delay** (number | Array.) - Optional - delay(s) between animation frames (in milliseconds) * **options.force** (boolean) - Optional - force GIF output, otherwise attempt to use input format (default: `true`) ### Throws * `Error` Invalid options ### Since 0.30.0 ### Examples ```javascript // Convert PNG to GIF await sharp(pngBuffer) .gif() .toBuffer(); ``` ```javascript // Convert animated WebP to animated GIF await sharp('animated.webp', { animated: true }) .toFile('animated.gif'); ``` ```javascript // 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 // Lossy file size reduction of animated GIF await sharp('in.gif', { animated: true }) .gif({ interFrameMaxError: 8 }) .toFile('optim.gif'); ``` ``` -------------------------------- ### Convert to Full Colour PNG Source: https://sharp.pixelplumbing.com/api-output Use this snippet to convert any input image format to a full-colour PNG. Ensure the 'sharp' library is imported and the input is correctly specified. ```javascript const data = await sharp(input) .png() .toBuffer(); ``` -------------------------------- ### Convolve Image with Kernel Source: https://sharp.pixelplumbing.com/api-operation Applies a convolution kernel to the image. Requires kernel dimensions and values, with optional scale and offset parameters. The example demonstrates using the Sobel operator. ```javascript sharp(input) .convolve({ width: 3, height: 3, kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1] }) .raw() .toBuffer(function(err, data, info) { // data contains the raw pixel data representing the convolution // of the input image with the horizontal Sobel operator }); ``` -------------------------------- ### Convert to Lossless WebP Source: https://sharp.pixelplumbing.com/api-output Use this snippet to convert any input image format to a lossless WebP output. Ensure the 'sharp' library is imported and the input file path is correctly specified. ```javascript const data = await sharp(input) .webp({ lossless: true }) .toBuffer(); ``` -------------------------------- ### jxl([options]) Source: https://sharp.pixelplumbing.com/api-output Configures the output image to use JPEG-XL (JXL) format with specified options. This feature is experimental and requires a custom libvips build. ```APIDOC ## 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. ### Parameters #### Options - **options** (Object) - Optional - output options - **options.distance** (number) - Optional - maximum encoding error, between 0 (highest quality) and 15 (lowest quality). Default: `1.0` - **options.quality** (number) - Optional - calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified - **options.decodingTier** (number) - Optional - target decode speed tier, between 0 (highest quality) and 4 (lowest quality). Default: `0` - **options.lossless** (boolean) - Optional - use lossless compression. Default: `false` - **options.effort** (number) - Optional - CPU effort, between 1 (fastest) and 9 (slowest). Default: `7` - **options.loop** (number) - Optional - number of animation iterations, use 0 for infinite animation. - **options.delay** (number | Array.) - Optional - delay(s) between animation frames (in milliseconds). ### Throws - `Error` Invalid options ``` -------------------------------- ### Get Image Statistics with Callback Source: https://sharp.pixelplumbing.com/api-input Use this snippet to retrieve image statistics using a Promise-based approach. The .then() block will receive an object containing channel statistics and image properties. ```javascript const image = sharp(inputJpg); image .stats() .then(function(stats) { // stats contains the channel-wise statistics array and the isOpaque value }); ``` -------------------------------- ### Stream Image Data for IIIF Tile Generation Source: https://sharp.pixelplumbing.com/api-output This snippet shows how to pipe image data from a readable stream through Sharp for IIIF tile generation and then pipe the output to a writable stream. This is efficient for processing large images or streams. ```javascript const iiififier = sharp().tile({ layout: "iiif" }); readableStream .pipe(iiififier) .pipe(writeableStream); ``` -------------------------------- ### toBuffer([options], [callback]) Source: https://sharp.pixelplumbing.com/api-output Writes image output to a Buffer. Supports JPEG, PNG, WebP, AVIF, TIFF, GIF, and raw pixel data. The output format can be set using toFormat or format-specific functions. By default, all metadata is removed. A Promise is returned when no callback is provided. ```APIDOC ## toBuffer([options], [callback]) ### Description Writes image output to a Buffer. Supports JPEG, PNG, WebP, AVIF, TIFF, GIF, and raw pixel data. The output format can be set using `toFormat` or format-specific functions. By default, all metadata is removed. A Promise is returned when no callback is provided. ### Method `toBuffer` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (`Object`, optional) - Options for the toBuffer method. - **options.resolveWithObject** (`boolean`, optional) - Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`. - **callback** (`function`, optional) - A callback function that receives `(err, data, info)`. - `err`: An error, if any. - `data`: The output image data (Buffer). - `info`: An object containing output image details such as `format`, `size`, `width`, `height`, `channels`, `premultiplied`, `cropOffsetLeft`, `cropOffsetTop`, `pageHeight`, `pages`, and `textAutofitDpi`. ### Request Example ```javascript sharp(input) .toBuffer((err, data, info) => { ... }); ``` ### Response #### Success Response - **Promise** (`Promise.`): Returns a Promise that resolves with the image data as a Buffer when no callback is provided. - **Object** (`{ data: Buffer, info: Object }`): When `options.resolveWithObject` is true, the Promise resolves with an object containing `data` (Buffer) and `info` (Object). #### Response Example ```javascript sharp(input) .toBuffer() .then(data => { ... }) .catch(err => { ... }); ``` ```javascript sharp(input) .png() .toBuffer({ resolveWithObject: true }) .then(({ data, info }) => { ... }) .catch(err => { ... }); ``` ```javascript const { data, info } = await sharp('my-image.jpg') .raw() .toBuffer({ resolveWithObject: true }); ``` ``` -------------------------------- ### Set MALLOC_ARENA_MAX for Memory Allocation Source: https://sharp.pixelplumbing.com/performance Reduce memory fragmentation on glibc-based Linux systems by setting the MALLOC_ARENA_MAX environment variable to a lower value, such as 2. This should be done before the Node.js process starts. ```bash export MALLOC_ARENA_MAX="2" ``` -------------------------------- ### toColorspace Source: https://sharp.pixelplumbing.com/api-colour Alternative spelling for setting the output colourspace. ```APIDOC ## toColorspace ### Description Alternative spelling of `toColourspace`. ### Method `toColorspace([colorspace])` ### Parameters #### Path Parameters - **colorspace** (string) - Optional - Output colorspace. ### Response #### Success Response (200) - **Sharp** - Returns the Sharp instance for chaining. ### Throws - `Error` Invalid parameters ```