UNPKG

76.9 kBTypeScriptView Raw
1/**
2 * Copyright 2017 François Nguyen and others.
3 *
4 * Billy Kwok <https://github.com/billykwok>
5 * Bradley Odell <https://github.com/BTOdell>
6 * Espen Hovlandsdal <https://github.com/rexxars>
7 * Floris de Bijl <https://github.com/Fdebijl>
8 * François Nguyen <https://github.com/phurytw>
9 * Jamie Woodbury <https://github.com/JamieWoodbury>
10 * Wooseop Kim <https://github.com/wooseopkim>
11 *
12 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
13 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
14 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
15 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
16 *
17 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of
18 * the Software.
19 *
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
21 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
22 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
23 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 */
25
26// SPDX-License-Identifier: MIT
27
28/// <reference types="node" />
29
30import { Duplex } from 'stream';
31
32//#region Constructor functions
33
34/**
35 * Creates a sharp instance from an image
36 * @param input Buffer containing JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data, or String containing the path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file.
37 * @param options Object with optional attributes.
38 * @throws {Error} Invalid parameters
39 * @returns A sharp instance that can be used to chain operations
40 */
41declare function sharp(options?: sharp.SharpOptions): sharp.Sharp;
42declare function sharp(
43 input?:
44 | Buffer
45 | ArrayBuffer
46 | Uint8Array
47 | Uint8ClampedArray
48 | Int8Array
49 | Uint16Array
50 | Int16Array
51 | Uint32Array
52 | Int32Array
53 | Float32Array
54 | Float64Array
55 | string,
56 options?: sharp.SharpOptions,
57): sharp.Sharp;
58
59declare namespace sharp {
60 /** Object containing nested boolean values representing the available input and output formats/methods. */
61 const format: FormatEnum;
62
63 /** An Object containing the version numbers of sharp, libvips and its dependencies. */
64 const versions: {
65 vips: string;
66 cairo?: string | undefined;
67 croco?: string | undefined;
68 exif?: string | undefined;
69 expat?: string | undefined;
70 ffi?: string | undefined;
71 fontconfig?: string | undefined;
72 freetype?: string | undefined;
73 gdkpixbuf?: string | undefined;
74 gif?: string | undefined;
75 glib?: string | undefined;
76 gsf?: string | undefined;
77 harfbuzz?: string | undefined;
78 jpeg?: string | undefined;
79 lcms?: string | undefined;
80 orc?: string | undefined;
81 pango?: string | undefined;
82 pixman?: string | undefined;
83 png?: string | undefined;
84 sharp?: string | undefined;
85 svg?: string | undefined;
86 tiff?: string | undefined;
87 webp?: string | undefined;
88 avif?: string | undefined;
89 heif?: string | undefined;
90 xml?: string | undefined;
91 zlib?: string | undefined;
92 };
93
94 /** An Object containing the platform and architecture of the current and installed vendored binaries. */
95 const vendor: {
96 current: string;
97 installed: string[];
98 };
99
100 /** An Object containing the available interpolators and their proper values */
101 const interpolators: Interpolators;
102
103 /** An EventEmitter that emits a change event when a task is either queued, waiting for libuv to provide a worker thread, complete */
104 const queue: NodeJS.EventEmitter;
105
106 //#endregion
107
108 //#region Utility functions
109
110 /**
111 * Gets or, when options are provided, sets the limits of libvips' operation cache.
112 * Existing entries in the cache will be trimmed after any change in limits.
113 * This method always returns cache statistics, useful for determining how much working memory is required for a particular task.
114 * @param options Object with the following attributes, or Boolean where true uses default cache settings and false removes all caching (optional, default true)
115 * @returns The cache results.
116 */
117 function cache(options?: boolean | CacheOptions): CacheResult;
118
119 /**
120 * Gets or sets the number of threads libvips' should create to process each image.
121 * The default value is the number of CPU cores. A value of 0 will reset to this default.
122 * The maximum number of images that can be processed in parallel is limited by libuv's UV_THREADPOOL_SIZE environment variable.
123 * @param concurrency The new concurrency value.
124 * @returns The current concurrency value.
125 */
126 function concurrency(concurrency?: number): number;
127
128 /**
129 * Provides access to internal task counters.
130 * @returns Object containing task counters
131 */
132 function counters(): SharpCounters;
133
134 /**
135 * Get and set use of SIMD vector unit instructions. Requires libvips to have been compiled with liborc support.
136 * 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.
137 * @param enable enable or disable use of SIMD vector unit instructions
138 * @returns true if usage of SIMD vector unit instructions is enabled
139 */
140 function simd(enable?: boolean): boolean;
141
142 //#endregion
143
144 const gravity: GravityEnum;
145 const strategy: StrategyEnum;
146 const kernel: KernelEnum;
147 const fit: FitEnum;
148 const bool: BoolEnum;
149
150 interface Sharp extends Duplex {
151 //#region Channel functions
152
153 /**
154 * Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel.
155 * @returns A sharp instance that can be used to chain operations
156 */
157 removeAlpha(): Sharp;
158
159 /**
160 * Ensure alpha channel, if missing. The added alpha channel will be fully opaque. This is a no-op if the image already has an alpha channel.
161 * @param alpha transparency level (0=fully-transparent, 1=fully-opaque) (optional, default 1).
162 * @returns A sharp instance that can be used to chain operations
163 */
164 ensureAlpha(alpha?: number): Sharp;
165
166 /**
167 * Extract a single channel from a multi-channel image.
168 * @param channel zero-indexed channel/band number to extract, or red, green, blue or alpha.
169 * @throws {Error} Invalid channel
170 * @returns A sharp instance that can be used to chain operations
171 */
172 extractChannel(channel: 0 | 1 | 2 | 3 | 'red' | 'green' | 'blue' | 'alpha'): Sharp;
173
174 /**
175 * Join one or more channels to the image. The meaning of the added channels depends on the output colourspace, set with toColourspace().
176 * By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. Channel ordering follows vips convention:
177 * - sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha.
178 * - CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha.
179 *
180 * Buffers may be any of the image formats supported by sharp.
181 * 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.
182 * @param images one or more images (file paths, Buffers).
183 * @param options image options, see sharp() constructor.
184 * @throws {Error} Invalid parameters
185 * @returns A sharp instance that can be used to chain operations
186 */
187 joinChannel(images: string | Buffer | ArrayLike<string | Buffer>, options?: SharpOptions): Sharp;
188
189 /**
190 * Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image.
191 * @param boolOp one of "and", "or" or "eor" to perform that bitwise operation, like the C logic operators &, | and ^ respectively.
192 * @throws {Error} Invalid parameters
193 * @returns A sharp instance that can be used to chain operations
194 */
195 bandbool(boolOp: keyof BoolEnum): Sharp;
196
197 //#endregion
198
199 //#region Color functions
200
201 /**
202 * Tint the image using the provided chroma while preserving the image luminance.
203 * An alpha channel may be present and will be unchanged by the operation.
204 * @param rgb Parsed by the color module to extract chroma values.
205 * @returns A sharp instance that can be used to chain operations
206 */
207 tint(rgb: Color): Sharp;
208
209 /**
210 * Convert to 8-bit greyscale; 256 shades of grey.
211 * This is a linear operation.
212 * If the input image is in a non-linear colour space such as sRGB, use gamma() with greyscale() for the best results.
213 * By default the output image will be web-friendly sRGB and contain three (identical) color channels.
214 * This may be overridden by other sharp operations such as toColourspace('b-w'), which will produce an output image containing one color channel.
215 * An alpha channel may be present, and will be unchanged by the operation.
216 * @param greyscale true to enable and false to disable (defaults to true)
217 * @returns A sharp instance that can be used to chain operations
218 */
219 greyscale(greyscale?: boolean): Sharp;
220
221 /**
222 * Alternative spelling of greyscale().
223 * @param grayscale true to enable and false to disable (defaults to true)
224 * @returns A sharp instance that can be used to chain operations
225 */
226 grayscale(grayscale?: boolean): Sharp;
227
228 /**
229 * Set the pipeline colourspace.
230 * The input image will be converted to the provided colourspace at the start of the pipeline.
231 * All operations will use this colourspace before converting to the output colourspace, as defined by toColourspace.
232 * This feature is experimental and has not yet been fully-tested with all operations.
233 *
234 * @param colourspace pipeline colourspace e.g. rgb16, scrgb, lab, grey16 ...
235 * @throws {Error} Invalid parameters
236 * @returns A sharp instance that can be used to chain operations
237 */
238 pipelineColourspace(colourspace?: string): Sharp;
239
240 /**
241 * Alternative spelling of pipelineColourspace
242 * @param colorspace pipeline colourspace e.g. rgb16, scrgb, lab, grey16 ...
243 * @throws {Error} Invalid parameters
244 * @returns A sharp instance that can be used to chain operations
245 */
246 pipelineColorspace(colorspace?: string): Sharp;
247
248 /**
249 * Set the output colourspace.
250 * By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.
251 * @param colourspace output colourspace e.g. srgb, rgb, cmyk, lab, b-w ...
252 * @throws {Error} Invalid parameters
253 * @returns A sharp instance that can be used to chain operations
254 */
255 toColourspace(colourspace?: string): Sharp;
256
257 /**
258 * Alternative spelling of toColourspace().
259 * @param colorspace output colorspace e.g. srgb, rgb, cmyk, lab, b-w ...
260 * @throws {Error} Invalid parameters
261 * @returns A sharp instance that can be used to chain operations
262 */
263 toColorspace(colorspace: string): Sharp;
264
265 //#endregion
266
267 //#region Composite functions
268
269 /**
270 * Composite image(s) over the processed (resized, extracted etc.) image.
271 *
272 * The images to composite must be the same size or smaller than the processed image.
273 * If both `top` and `left` options are provided, they take precedence over `gravity`.
274 * @param images - Ordered list of images to composite
275 * @throws {Error} Invalid parameters
276 * @returns A sharp instance that can be used to chain operations
277 */
278 composite(images: OverlayOptions[]): Sharp;
279
280 //#endregion
281
282 //#region Input functions
283
284 /**
285 * Take a "snapshot" of the Sharp instance, returning a new instance.
286 * Cloned instances inherit the input of their parent instance.
287 * This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream.
288 * @returns A sharp instance that can be used to chain operations
289 */
290 clone(): Sharp;
291
292 /**
293 * Fast access to (uncached) image metadata without decoding any compressed image data.
294 * @returns A sharp instance that can be used to chain operations
295 */
296 metadata(callback: (err: Error, metadata: Metadata) => void): Sharp;
297
298 /**
299 * Fast access to (uncached) image metadata without decoding any compressed image data.
300 * @returns A promise that resolves with a metadata object
301 */
302 metadata(): Promise<Metadata>;
303
304 /**
305 * Access to pixel-derived image statistics for every channel in the image.
306 * @returns A sharp instance that can be used to chain operations
307 */
308 stats(callback: (err: Error, stats: Stats) => void): Sharp;
309
310 /**
311 * Access to pixel-derived image statistics for every channel in the image.
312 * @returns A promise that resolves with a stats object
313 */
314 stats(): Promise<Stats>;
315
316 //#endregion
317
318 //#region Operation functions
319
320 /**
321 * Rotate the output image by either an explicit angle or auto-orient based on the EXIF Orientation tag.
322 *
323 * If an angle is provided, it is converted to a valid positive degree rotation. For example, -450 will produce a 270deg rotation.
324 *
325 * When rotating by an angle other than a multiple of 90, the background colour can be provided with the background option.
326 *
327 * If no angle is provided, it is determined from the EXIF data. Mirroring is supported and may infer the use of a flip operation.
328 *
329 * The use of rotate implies the removal of the EXIF Orientation tag, if any.
330 *
331 * Method order is important when both rotating and extracting regions, for example rotate(x).extract(y) will produce a different result to extract(y).rotate(x).
332 * @param angle angle of rotation. (optional, default auto)
333 * @param options if present, is an Object with optional attributes.
334 * @throws {Error} Invalid parameters
335 * @returns A sharp instance that can be used to chain operations
336 */
337 rotate(angle?: number, options?: RotateOptions): Sharp;
338
339 /**
340 * Flip the image about the vertical Y axis. This always occurs after rotation, if any.
341 * The use of flip implies the removal of the EXIF Orientation tag, if any.
342 * @param flip true to enable and false to disable (defaults to true)
343 * @returns A sharp instance that can be used to chain operations
344 */
345 flip(flip?: boolean): Sharp;
346
347 /**
348 * Flop the image about the horizontal X axis. This always occurs after rotation, if any.
349 * The use of flop implies the removal of the EXIF Orientation tag, if any.
350 * @param flop true to enable and false to disable (defaults to true)
351 * @returns A sharp instance that can be used to chain operations
352 */
353 flop(flop?: boolean): Sharp;
354
355 /**
356 * Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.
357 * You must provide an array of length 4 or a 2x2 affine transformation matrix.
358 * By default, new pixels are filled with a black background. You can provide a background color with the `background` option.
359 * A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`.
360 *
361 * In the case of a 2x2 matrix, the transform is:
362 * X = matrix[0, 0] * (x + idx) + matrix[0, 1] * (y + idy) + odx
363 * Y = matrix[1, 0] * (x + idx) + matrix[1, 1] * (y + idy) + ody
364 *
365 * where:
366 *
367 * x and y are the coordinates in input image.
368 * X and Y are the coordinates in output image.
369 * (0,0) is the upper left corner.
370 *
371 * @param matrix Affine transformation matrix, may either by a array of length four or a 2x2 matrix array
372 * @param options if present, is an Object with optional attributes.
373 *
374 * @returns A sharp instance that can be used to chain operations
375 */
376 affine(matrix: [number, number, number, number] | Matrix2x2, options?: AffineOptions): Sharp;
377
378 /**
379 * Sharpen the image.
380 * When used without parameters, performs a fast, mild sharpen of the output image.
381 * When a sigma is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space.
382 * Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available.
383 * @param options if present, is an Object with optional attributes
384 * @throws {Error} Invalid parameters
385 * @returns A sharp instance that can be used to chain operations
386 */
387 sharpen(options?: SharpenOptions): Sharp;
388
389 /**
390 * Sharpen the image.
391 * When used without parameters, performs a fast, mild sharpen of the output image.
392 * When a sigma is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space.
393 * Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available.
394 * @param sigma the sigma of the Gaussian mask, where sigma = 1 + radius / 2.
395 * @param flat the level of sharpening to apply to "flat" areas. (optional, default 1.0)
396 * @param jagged the level of sharpening to apply to "jagged" areas. (optional, default 2.0)
397 * @throws {Error} Invalid parameters
398 * @returns A sharp instance that can be used to chain operations
399 *
400 * @deprecated Use the object parameter `sharpen({sigma, m1, m2, x1, y2, y3})` instead
401 */
402 sharpen(sigma?: number, flat?: number, jagged?: number): Sharp;
403
404 /**
405 * Apply median filter. When used without parameters the default window is 3x3.
406 * @param size square mask size: size x size (optional, default 3)
407 * @throws {Error} Invalid parameters
408 * @returns A sharp instance that can be used to chain operations
409 */
410 median(size?: number): Sharp;
411
412 /**
413 * Blur the image.
414 * When used without parameters, performs a fast, mild blur of the output image.
415 * When a sigma is provided, performs a slower, more accurate Gaussian blur.
416 * When a boolean sigma is provided, ether blur mild or disable blur
417 * @param sigma a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where sigma = 1 + radius / 2.
418 * @throws {Error} Invalid parameters
419 * @returns A sharp instance that can be used to chain operations
420 */
421 blur(sigma?: number | boolean): Sharp;
422
423 /**
424 * Merge alpha transparency channel, if any, with background.
425 * @param flatten true to enable and false to disable (defaults to true)
426 * @returns A sharp instance that can be used to chain operations
427 */
428 flatten(flatten?: boolean | FlattenOptions): Sharp;
429
430 /**
431 * Ensure the image has an alpha channel with all white pixel values made fully transparent.
432 * Existing alpha channel values for non-white pixels remain unchanged.
433 * @returns A sharp instance that can be used to chain operations
434 */
435 unflatten(): Sharp;
436
437 /**
438 * 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.
439 * This can improve the perceived brightness of a resized image in non-linear colour spaces.
440 * JPEG and WebP input images will not take advantage of the shrink-on-load performance optimisation when applying a gamma correction.
441 * Supply a second argument to use a different output gamma value, otherwise the first value is used in both cases.
442 * @param gamma value between 1.0 and 3.0. (optional, default 2.2)
443 * @param gammaOut value between 1.0 and 3.0. (optional, defaults to same as gamma)
444 * @throws {Error} Invalid parameters
445 * @returns A sharp instance that can be used to chain operations
446 */
447 gamma(gamma?: number, gammaOut?: number): Sharp;
448
449 /**
450 * Produce the "negative" of the image.
451 * @param negate true to enable and false to disable, or an object of options (defaults to true)
452 * @returns A sharp instance that can be used to chain operations
453 */
454 negate(negate?: boolean | NegateOptions): Sharp;
455
456 /**
457 * Enhance output image contrast by stretching its luminance to cover a full dynamic range.
458 *
459 * Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes.
460 *
461 * Luminance values below the `lower` percentile will be underexposed by clipping to zero.
462 * Luminance values above the `upper` percentile will be overexposed by clipping to the max pixel value.
463 *
464 * @param normalise options
465 * @throws {Error} Invalid parameters
466 * @returns A sharp instance that can be used to chain operations
467 */
468 normalise(normalise?: NormaliseOptions): Sharp;
469
470 /**
471 * Alternative spelling of normalise.
472 * @param normalize options
473 * @throws {Error} Invalid parameters
474 * @returns A sharp instance that can be used to chain operations
475 */
476 normalize(normalize?: NormaliseOptions): Sharp;
477
478 /**
479 * Perform contrast limiting adaptive histogram equalization (CLAHE)
480 *
481 * This will, in general, enhance the clarity of the image by bringing out
482 * darker details. Please read more about CLAHE here:
483 * https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE
484 *
485 * @param options clahe options
486 */
487 clahe(options: ClaheOptions): Sharp;
488
489 /**
490 * Convolve the image with the specified kernel.
491 * @param kernel the specified kernel
492 * @throws {Error} Invalid parameters
493 * @returns A sharp instance that can be used to chain operations
494 */
495 convolve(kernel: Kernel): Sharp;
496
497 /**
498 * Any pixel value greather than or equal to the threshold value will be set to 255, otherwise it will be set to 0.
499 * @param threshold a value in the range 0-255 representing the level at which the threshold will be applied. (optional, default 128)
500 * @param options threshold options
501 * @throws {Error} Invalid parameters
502 * @returns A sharp instance that can be used to chain operations
503 */
504 threshold(threshold?: number, options?: ThresholdOptions): Sharp;
505
506 /**
507 * Perform a bitwise boolean operation with operand image.
508 * 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.
509 * @param operand Buffer containing image data or String containing the path to an image file.
510 * @param operator one of "and", "or" or "eor" to perform that bitwise operation, like the C logic operators &, | and ^ respectively.
511 * @param options describes operand when using raw pixel data.
512 * @throws {Error} Invalid parameters
513 * @returns A sharp instance that can be used to chain operations
514 */
515 boolean(operand: string | Buffer, operator: keyof BoolEnum, options?: { raw: Raw }): Sharp;
516
517 /**
518 * Apply the linear formula a * input + b to the image (levels adjustment)
519 * @param a multiplier (optional, default 1.0)
520 * @param b offset (optional, default 0.0)
521 * @throws {Error} Invalid parameters
522 * @returns A sharp instance that can be used to chain operations
523 */
524 linear(a?: number | number[] | null, b?: number | number[]): Sharp;
525
526 /**
527 * Recomb the image with the specified matrix.
528 * @param inputMatrix 3x3 Recombination matrix
529 * @throws {Error} Invalid parameters
530 * @returns A sharp instance that can be used to chain operations
531 */
532 recomb(inputMatrix: Matrix3x3): Sharp;
533
534 /**
535 * Transforms the image using brightness, saturation, hue rotation and lightness.
536 * Brightness and lightness both operate on luminance, with the difference being that brightness is multiplicative whereas lightness is additive.
537 * @param options describes the modulation
538 * @returns A sharp instance that can be used to chain operations
539 */
540 modulate(options?: {
541 brightness?: number | undefined;
542 saturation?: number | undefined;
543 hue?: number | undefined;
544 lightness?: number | undefined;
545 }): Sharp;
546
547 //#endregion
548
549 //#region Output functions
550
551 /**
552 * Write output image data to a file.
553 * If an explicit output format is not selected, it will be inferred from the extension, with JPEG, PNG, WebP, AVIF, TIFF, DZI, and libvips' V format supported.
554 * Note that raw pixel data is only supported for buffer output.
555 * @param fileOut The path to write the image data to.
556 * @param callback Callback function called on completion with two arguments (err, info). info contains the output image format, size (bytes), width, height and channels.
557 * @throws {Error} Invalid parameters
558 * @returns A sharp instance that can be used to chain operations
559 */
560 toFile(fileOut: string, callback: (err: Error, info: OutputInfo) => void): Sharp;
561
562 /**
563 * Write output image data to a file.
564 * @param fileOut The path to write the image data to.
565 * @throws {Error} Invalid parameters
566 * @returns A promise that fulfills with an object containing information on the resulting file
567 */
568 toFile(fileOut: string): Promise<OutputInfo>;
569
570 /**
571 * Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and RAW output are supported.
572 * By default, the format will match the input image, except SVG input which becomes PNG output.
573 * @param callback Callback function called on completion with three arguments (err, buffer, info).
574 * @returns A sharp instance that can be used to chain operations
575 */
576 toBuffer(callback: (err: Error, buffer: Buffer, info: OutputInfo) => void): Sharp;
577
578 /**
579 * Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and RAW output are supported.
580 * By default, the format will match the input image, except SVG input which becomes PNG output.
581 * @param options resolve options
582 * @param options.resolveWithObject Resolve the Promise with an Object containing data and info properties instead of resolving only with data.
583 * @returns A promise that resolves with the Buffer data.
584 */
585 toBuffer(options?: { resolveWithObject: false }): Promise<Buffer>;
586
587 /**
588 * Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and RAW output are supported.
589 * By default, the format will match the input image, except SVG input which becomes PNG output.
590 * @param options resolve options
591 * @param options.resolveWithObject Resolve the Promise with an Object containing data and info properties instead of resolving only with data.
592 * @returns A promise that resolves with an object containing the Buffer data and an info object containing the output image format, size (bytes), width, height and channels
593 */
594 toBuffer(options: { resolveWithObject: true }): Promise<{ data: Buffer; info: OutputInfo }>;
595
596 /**
597 * Include all metadata (EXIF, XMP, IPTC) from the input image in the output image.
598 * The default behaviour, when withMetadata is not used, is to strip all metadata and convert to the device-independent sRGB colour space.
599 * This will also convert to and add a web-friendly sRGB ICC profile.
600 * @param withMetadata
601 * @throws {Error} Invalid parameters.
602 */
603 withMetadata(withMetadata?: WriteableMetadata): Sharp;
604
605 /**
606 * Use these JPEG options for output image.
607 * @param options Output options.
608 * @throws {Error} Invalid options
609 * @returns A sharp instance that can be used to chain operations
610 */
611 jpeg(options?: JpegOptions): Sharp;
612
613 /**
614 * Use these JP2 (JPEG 2000) options for output image.
615 * @param options Output options.
616 * @throws {Error} Invalid options
617 * @returns A sharp instance that can be used to chain operations
618 */
619 jp2(options?: Jp2Options): Sharp;
620
621 /**
622 * Use these JPEG-XL (JXL) options for output image.
623 * This feature is experimental, please do not use in production systems.
624 * Requires libvips compiled with support for libjxl.
625 * The prebuilt binaries do not include this.
626 * Image metadata (EXIF, XMP) is unsupported.
627 * @param options Output options.
628 * @throws {Error} Invalid options
629 * @returns A sharp instance that can be used to chain operations
630 */
631 jxl(options?: JxlOptions): Sharp;
632
633 /**
634 * Use these PNG options for output image.
635 * PNG output is always full colour at 8 or 16 bits per pixel.
636 * Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel.
637 * @param options Output options.
638 * @throws {Error} Invalid options
639 * @returns A sharp instance that can be used to chain operations
640 */
641 png(options?: PngOptions): Sharp;
642
643 /**
644 * Use these WebP options for output image.
645 * @param options Output options.
646 * @throws {Error} Invalid options
647 * @returns A sharp instance that can be used to chain operations
648 */
649 webp(options?: WebpOptions): Sharp;
650
651 /**
652 * Use these GIF options for output image.
653 * Requires libvips compiled with support for ImageMagick or GraphicsMagick. The prebuilt binaries do not include this - see installing a custom libvips.
654 * @param options Output options.
655 * @throws {Error} Invalid options
656 * @returns A sharp instance that can be used to chain operations
657 */
658 gif(options?: GifOptions): Sharp;
659
660 /**
661 * Use these AVIF options for output image.
662 * Whilst it is possible to create AVIF images smaller than 16x16 pixels, most web browsers do not display these properly.
663 * @param options Output options.
664 * @throws {Error} Invalid options
665 * @returns A sharp instance that can be used to chain operations
666 */
667 avif(options?: AvifOptions): Sharp;
668
669 /**
670 * Use these HEIF options for output image.
671 * Support for patent-encumbered HEIC images requires the use of a globally-installed libvips compiled with support for libheif, libde265 and x265.
672 * @param options Output options.
673 * @throws {Error} Invalid options
674 * @returns A sharp instance that can be used to chain operations
675 */
676 heif(options?: HeifOptions): Sharp;
677
678 /**
679 * Use these TIFF options for output image.
680 * @param options Output options.
681 * @throws {Error} Invalid options
682 * @returns A sharp instance that can be used to chain operations
683 */
684 tiff(options?: TiffOptions): Sharp;
685
686 /**
687 * Force output to be raw, uncompressed uint8 pixel data.
688 * @param options Raw output options.
689 * @throws {Error} Invalid options
690 * @returns A sharp instance that can be used to chain operations
691 */
692 raw(options?: RawOptions): Sharp;
693
694 /**
695 * Force output to a given format.
696 * @param format a String or an Object with an 'id' attribute
697 * @param options output options
698 * @throws {Error} Unsupported format or options
699 * @returns A sharp instance that can be used to chain operations
700 */
701 toFormat(
702 format: keyof FormatEnum | AvailableFormatInfo,
703 options?:
704 | OutputOptions
705 | JpegOptions
706 | PngOptions
707 | WebpOptions
708 | AvifOptions
709 | HeifOptions
710 | JxlOptions
711 | GifOptions
712 | Jp2Options
713 | TiffOptions,
714 ): Sharp;
715
716 /**
717 * Use tile-based deep zoom (image pyramid) output.
718 * Set the format and options for tile images via the toFormat, jpeg, png or webp functions.
719 * Use a .zip or .szi file extension with toFile to write to a compressed archive file format.
720 *
721 * Warning: multiple sharp instances concurrently producing tile output can expose a possible race condition in some versions of libgsf.
722 * @param tile tile options
723 * @throws {Error} Invalid options
724 * @returns A sharp instance that can be used to chain operations
725 */
726 tile(tile?: TileOptions): Sharp;
727
728 /**
729 * Set a timeout for processing, in seconds. Use a value of zero to continue processing indefinitely, the default behaviour.
730 * The clock starts when libvips opens an input image for processing. Time spent waiting for a libuv thread to become available is not included.
731 * @param options Object with a `seconds` attribute between 0 and 3600 (number)
732 * @throws {Error} Invalid options
733 * @returns A sharp instance that can be used to chain operations
734 */
735 timeout(options: TimeoutOptions): Sharp;
736
737 //#endregion
738
739 //#region Resize functions
740
741 /**
742 * Resize image to width, height or width x height.
743 *
744 * When both a width and height are provided, the possible methods by which the image should fit these are:
745 * - cover: Crop to cover both provided dimensions (the default).
746 * - contain: Embed within both provided dimensions.
747 * - fill: Ignore the aspect ratio of the input and stretch to both provided dimensions.
748 * - 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.
749 * - 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.
750 * Some of these values are based on the object-fit CSS property.
751 *
752 * When using a fit of cover or contain, the default position is centre. Other options are:
753 * - sharp.position: top, right top, right, right bottom, bottom, left bottom, left, left top.
754 * - sharp.gravity: north, northeast, east, southeast, south, southwest, west, northwest, center or centre.
755 * - sharp.strategy: cover only, dynamically crop using either the entropy or attention strategy. Some of these values are based on the object-position CSS property.
756 *
757 * The experimental strategy-based approach resizes so one dimension is at its target length then repeatedly ranks edge regions,
758 * discarding the edge with the lowest score based on the selected strategy.
759 * - entropy: focus on the region with the highest Shannon entropy.
760 * - attention: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
761 *
762 * Possible interpolation kernels are:
763 * - nearest: Use nearest neighbour interpolation.
764 * - cubic: Use a Catmull-Rom spline.
765 * - lanczos2: Use a Lanczos kernel with a=2.
766 * - lanczos3: Use a Lanczos kernel with a=3 (the default).
767 *
768 * @param width pixels wide the resultant image should be. Use null or undefined to auto-scale the width to match the height.
769 * @param height pixels high the resultant image should be. Use null or undefined to auto-scale the height to match the width.
770 * @param options resize options
771 * @throws {Error} Invalid parameters
772 * @returns A sharp instance that can be used to chain operations
773 */
774 resize(widthOrOptions?: number | ResizeOptions | null, height?: number | null, options?: ResizeOptions): Sharp;
775
776 /**
777 * Shorthand for resize(null, null, options);
778 *
779 * @param options resize options
780 * @throws {Error} Invalid parameters
781 * @returns A sharp instance that can be used to chain operations
782 */
783 resize(options: ResizeOptions): Sharp;
784
785 /**
786 * Extend / pad / extrude one or more edges of the image with either
787 * the provided background colour or pixels derived from the image.
788 * This operation will always occur after resizing and extraction, if any.
789 * @param extend single pixel count to add to all edges or an Object with per-edge counts
790 * @throws {Error} Invalid parameters
791 * @returns A sharp instance that can be used to chain operations
792 */
793 extend(extend: number | ExtendOptions): Sharp;
794
795 /**
796 * Extract a region of the image.
797 * - Use extract() before resize() for pre-resize extraction.
798 * - Use extract() after resize() for post-resize extraction.
799 * - Use extract() before and after for both.
800 *
801 * @param region The region to extract
802 * @throws {Error} Invalid parameters
803 * @returns A sharp instance that can be used to chain operations
804 */
805 extract(region: Region): Sharp;
806
807 /**
808 * Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.
809 * Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels.
810 * The info response Object will contain trimOffsetLeft and trimOffsetTop properties.
811 * @param trim The specific background colour to trim, the threshold for doing so or an Object with both.
812 * @throws {Error} Invalid parameters
813 * @returns A sharp instance that can be used to chain operations
814 */
815 trim(trim?: string | number | TrimOptions): Sharp;
816
817 //#endregion
818 }
819
820 interface SharpOptions {
821 /**
822 * When to abort processing of invalid pixel data, one of (in order of sensitivity):
823 * 'none' (least), 'truncated', 'error' or 'warning' (most), highers level imply lower levels, invalid metadata will always abort. (optional, default 'warning')
824 */
825 failOn?: FailOnOptions | undefined;
826 /**
827 * By default halt processing and raise an error when loading invalid images.
828 * Set this flag to false if you'd rather apply a "best effort" to decode images,
829 * even if the data is corrupt or invalid. (optional, default true)
830 *
831 * @deprecated Use `failOn` instead
832 */
833 failOnError?: boolean | undefined;
834 /**
835 * Do not process input images where the number of pixels (width x height) exceeds this limit.
836 * Assumes image dimensions contained in the input metadata can be trusted.
837 * An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). (optional, default 268402689)
838 */
839 limitInputPixels?: number | boolean | undefined;
840 /** Set this to true to remove safety features that help prevent memory exhaustion (SVG, PNG). (optional, default false) */
841 unlimited?: boolean | undefined;
842 /** Set this to false to use random access rather than sequential read. Some operations will do this automatically. */
843 sequentialRead?: boolean | undefined;
844 /** Number representing the DPI for vector images in the range 1 to 100000. (optional, default 72) */
845 density?: number | undefined;
846 /** Should the embedded ICC profile, if any, be ignored. */
847 ignoreIcc?: boolean | undefined;
848 /** Number of pages to extract for multi-page input (GIF, TIFF, PDF), use -1 for all pages */
849 pages?: number | undefined;
850 /** Page number to start extracting from for multi-page input (GIF, TIFF, PDF), zero based. (optional, default 0) */
851 page?: number | undefined;
852 /** subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. (optional, default -1) */
853 subifd?: number | undefined;
854 /** Level to extract from a multi-level input (OpenSlide), zero based. (optional, default 0) */
855 level?: number | undefined;
856 /** Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). (optional, default false) */
857 animated?: boolean | undefined;
858 /** Describes raw pixel input image data. See raw() for pixel ordering. */
859 raw?: CreateRaw | undefined;
860 /** Describes a new image to be created. */
861 create?: Create | undefined;
862 /** Describes a new text image to be created. */
863 text?: CreateText | undefined;
864 }
865
866 interface CacheOptions {
867 /** Is the maximum memory in MB to use for this cache (optional, default 50) */
868 memory?: number | undefined;
869 /** Is the maximum number of files to hold open (optional, default 20) */
870 files?: number | undefined;
871 /** Is the maximum number of operations to cache (optional, default 100) */
872 items?: number | undefined;
873 }
874
875 interface TimeoutOptions {
876 /** Number of seconds after which processing will be stopped (default 0, eg disabled) */
877 seconds: number;
878 }
879
880 interface SharpCounters {
881 /** The number of tasks this module has queued waiting for libuv to provide a worker thread from its pool. */
882 queue: number;
883 /** The number of resize tasks currently being processed. */
884 process: number;
885 }
886
887 interface Raw {
888 width: number;
889 height: number;
890 channels: 1 | 2 | 3 | 4;
891 }
892
893 interface CreateRaw extends Raw {
894 /** Specifies that the raw input has already been premultiplied, set to true to avoid sharp premultiplying the image. (optional, default false) */
895 premultiplied?: boolean | undefined;
896 }
897
898 interface Create {
899 /** Number of pixels wide. */
900 width: number;
901 /** Number of pixels high. */
902 height: number;
903 /** Number of bands e.g. 3 for RGB, 4 for RGBA */
904 channels: Channels;
905 /** Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. */
906 background: Color;
907 /** Describes a noise to be created. */
908 noise?: Noise | undefined;
909 }
910
911 interface CreateText {
912 /** Text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`. */
913 text: string;
914 /** Font name to render with. */
915 font?: string;
916 /** Absolute filesystem path to a font file that can be used by `font`. */
917 fontfile?: string;
918 /** Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. (optional, default `0`) */
919 width?: number;
920 /**
921 * Integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution
922 * defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. (optional, default `0`)
923 */
924 height?: number;
925 /** Text alignment ('left', 'centre', 'center', 'right'). (optional, default 'left') */
926 align?: TextAlign;
927 /** Set this to true to apply justification to the text. (optional, default `false`) */
928 justify?: boolean;
929 /** The resolution (size) at which to render the text. Does not take effect if `height` is specified. (optional, default `72`) */
930 dpi?: number;
931 /**
932 * Set this to true to enable RGBA output. This is useful for colour emoji rendering,
933 * or support for pango markup features like `<span foreground="red">Red!</span>`. (optional, default `false`)
934 */
935 rgba?: boolean;
936 /** Text line height in points. Will use the font line height if none is specified. (optional, default `0`) */
937 spacing?: number;
938 /** Word wrapping style when width is provided, one of: 'word', 'char', 'charWord' (prefer char, fallback to word) or 'none' */
939 wrap?: TextWrap;
940 }
941
942 interface WriteableMetadata {
943 /** Value between 1 and 8, used to update the EXIF Orientation tag. */
944 orientation?: number | undefined;
945 /** Filesystem path to output ICC profile, defaults to sRGB. */
946 icc?: string | undefined;
947 /** Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. (optional, default {}) */
948 exif?: Record<string, any> | undefined;
949 /** Number of pixels per inch (DPI) */
950 density?: number | undefined;
951 }
952
953 interface Metadata {
954 /** Number value of the EXIF Orientation header, if present */
955 orientation?: number | undefined;
956 /** Name of decoder used to decompress image data e.g. jpeg, png, webp, gif, svg */
957 format?: keyof FormatEnum | undefined;
958 /** Total size of image in bytes, for Stream and Buffer input only */
959 size?: number | undefined;
960 /** Number of pixels wide (EXIF orientation is not taken into consideration) */
961 width?: number | undefined;
962 /** Number of pixels high (EXIF orientation is not taken into consideration) */
963 height?: number | undefined;
964 /** Name of colour space interpretation */
965 space?: keyof ColourspaceEnum | undefined;
966 /** Number of bands e.g. 3 for sRGB, 4 for CMYK */
967 channels?: Channels | undefined;
968 /** Name of pixel depth format e.g. uchar, char, ushort, float ... */
969 depth?: string | undefined;
970 /** Number of pixels per inch (DPI), if present */
971 density?: number | undefined;
972 /** 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 */
973 chromaSubsampling: string;
974 /** Boolean indicating whether the image is interlaced using a progressive scan */
975 isProgressive?: boolean | undefined;
976 /** Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP */
977 pages?: number | undefined;
978 /** Number of pixels high each page in a multi-page image will be. */
979 pageHeight?: number | undefined;
980 /** Number of times to loop an animated image, zero refers to a continuous loop. */
981 loop?: number | undefined;
982 /** Delay in ms between each page in an animated image, provided as an array of integers. */
983 delay?: number[] | undefined;
984 /** Number of the primary page in a HEIF image */
985 pagePrimary?: number | undefined;
986 /** Boolean indicating the presence of an embedded ICC profile */
987 hasProfile?: boolean | undefined;
988 /** Boolean indicating the presence of an alpha transparency channel */
989 hasAlpha?: boolean | undefined;
990 /** Buffer containing raw EXIF data, if present */
991 exif?: Buffer | undefined;
992 /** Buffer containing raw ICC profile data, if present */
993 icc?: Buffer | undefined;
994 /** Buffer containing raw IPTC data, if present */
995 iptc?: Buffer | undefined;
996 /** Buffer containing raw XMP data, if present */
997 xmp?: Buffer | undefined;
998 /** Buffer containing raw TIFFTAG_PHOTOSHOP data, if present */
999 tifftagPhotoshop?: Buffer | undefined;
1000 /** The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC) */
1001 compression?: 'av1' | 'hevc';
1002 /** Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value */
1003 background?: { r: number; g: number; b: number } | number;
1004 /** Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide */
1005 levels?: LevelMetadata[] | undefined;
1006 /** Number of Sub Image File Directories in an OME-TIFF image */
1007 subifds?: number | undefined;
1008 /** The unit of resolution (density) */
1009 resolutionUnit?: 'inch' | 'cm' | undefined;
1010 /** String containing format for images loaded via *magick */
1011 formatMagick?: string | undefined;
1012 }
1013
1014 interface LevelMetadata {
1015 width: number;
1016 height: number;
1017 }
1018
1019 interface Stats {
1020 /** Array of channel statistics for each channel in the image. */
1021 channels: ChannelStats[];
1022 /** Value to identify if the image is opaque or transparent, based on the presence and use of alpha channel */
1023 isOpaque: boolean;
1024 /** Histogram-based estimation of greyscale entropy, discarding alpha channel if any (experimental) */
1025 entropy: number;
1026 /** Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any (experimental) */
1027 sharpness: number;
1028 /** Object containing most dominant sRGB colour based on a 4096-bin 3D histogram (experimental) */
1029 dominant: { r: number; g: number; b: number };
1030 }
1031
1032 interface ChannelStats {
1033 /** minimum value in the channel */
1034 min: number;
1035 /** maximum value in the channel */
1036 max: number;
1037 /** sum of all values in a channel */
1038 sum: number;
1039 /** sum of squared values in a channel */
1040 squaresSum: number;
1041 /** mean of the values in a channel */
1042 mean: number;
1043 /** standard deviation for the values in a channel */
1044 stdev: number;
1045 /** x-coordinate of one of the pixel where the minimum lies */
1046 minX: number;
1047 /** y-coordinate of one of the pixel where the minimum lies */
1048 minY: number;
1049 /** x-coordinate of one of the pixel where the maximum lies */
1050 maxX: number;
1051 /** y-coordinate of one of the pixel where the maximum lies */
1052 maxY: number;
1053 }
1054
1055 interface OutputOptions {
1056 /** Force format output, otherwise attempt to use input format (optional, default true) */
1057 force?: boolean | undefined;
1058 }
1059
1060 interface JpegOptions extends OutputOptions {
1061 /** Quality, integer 1-100 (optional, default 80) */
1062 quality?: number | undefined;
1063 /** Use progressive (interlace) scan (optional, default false) */
1064 progressive?: boolean | undefined;
1065 /** Set to '4:4:4' to prevent chroma subsampling when quality <= 90 (optional, default '4:2:0') */
1066 chromaSubsampling?: string | undefined;
1067 /** Apply trellis quantisation (optional, default false) */
1068 trellisQuantisation?: boolean | undefined;
1069 /** Apply overshoot deringing (optional, default false) */
1070 overshootDeringing?: boolean | undefined;
1071 /** Optimise progressive scans, forces progressive (optional, default false) */
1072 optimiseScans?: boolean | undefined;
1073 /** Alternative spelling of optimiseScans (optional, default false) */
1074 optimizeScans?: boolean | undefined;
1075 /** Optimise Huffman coding tables (optional, default true) */
1076 optimiseCoding?: boolean | undefined;
1077 /** Alternative spelling of optimiseCoding (optional, default true) */
1078 optimizeCoding?: boolean | undefined;
1079 /** Quantization table to use, integer 0-8 (optional, default 0) */
1080 quantisationTable?: number | undefined;
1081 /** Alternative spelling of quantisationTable (optional, default 0) */
1082 quantizationTable?: number | undefined;
1083 /** Use mozjpeg defaults (optional, default false) */
1084 mozjpeg?: boolean | undefined;
1085 }
1086
1087 interface Jp2Options extends OutputOptions {
1088 /** Quality, integer 1-100 (optional, default 80) */
1089 quality?: number;
1090 /** Use lossless compression mode (optional, default false) */
1091 lossless?: boolean;
1092 /** Horizontal tile size (optional, default 512) */
1093 tileWidth?: number;
1094 /** Vertical tile size (optional, default 512) */
1095 tileHeight?: number;
1096 /** Set to '4:2:0' to enable chroma subsampling (optional, default '4:4:4') */
1097 chromaSubsampling?: '4:4:4' | '4:2:0';
1098 }
1099
1100 interface JxlOptions extends OutputOptions {
1101 /** Maximum encoding error, between 0 (highest quality) and 15 (lowest quality) (optional, default 1.0) */
1102 distance?: number;
1103 /** Calculate distance based on JPEG-like quality, between 1 and 100, overrides distance if specified */
1104 quality?: number;
1105 /** Target decode speed tier, between 0 (highest quality) and 4 (lowest quality) (optional, default 0) */
1106 decodingTier?: number;
1107 /** Use lossless compression (optional, default false) */
1108 lossless?: boolean;
1109 /** CPU effort, between 3 (fastest) and 9 (slowest) (optional, default 7) */
1110 effort?: number | undefined;
1111 }
1112
1113 interface WebpOptions extends OutputOptions, AnimationOptions {
1114 /** Quality, integer 1-100 (optional, default 80) */
1115 quality?: number | undefined;
1116 /** Quality of alpha layer, number from 0-100 (optional, default 100) */
1117 alphaQuality?: number | undefined;
1118 /** Use lossless compression mode (optional, default false) */
1119 lossless?: boolean | undefined;
1120 /** Use near_lossless compression mode (optional, default false) */
1121 nearLossless?: boolean | undefined;
1122 /** Use high quality chroma subsampling (optional, default false) */
1123 smartSubsample?: boolean | undefined;
1124 /** Level of CPU effort to reduce file size, integer 0-6 (optional, default 4) */
1125 effort?: number | undefined;
1126 /** Prevent use of animation key frames to minimise file size (slow) (optional, default false) */
1127 minSize?: number;
1128 /** Allow mixture of lossy and lossless animation frames (slow) (optional, default false) */
1129 mixed?: boolean;
1130 }
1131
1132 interface AvifOptions extends OutputOptions {
1133 /** quality, integer 1-100 (optional, default 50) */
1134 quality?: number | undefined;
1135 /** use lossless compression (optional, default false) */
1136 lossless?: boolean | undefined;
1137 /** Level of CPU effort to reduce file size, between 0 (fastest) and 9 (slowest) (optional, default 4) */
1138 effort?: number | undefined;
1139 /** set to '4:2:0' to use chroma subsampling, requires libvips v8.11.0 (optional, default '4:4:4') */
1140 chromaSubsampling?: string | undefined;
1141 }
1142
1143 interface HeifOptions extends OutputOptions {
1144 /** quality, integer 1-100 (optional, default 50) */
1145 quality?: number | undefined;
1146 /** compression format: av1, hevc (optional, default 'av1') */
1147 compression?: 'av1' | 'hevc' | undefined;
1148 /** use lossless compression (optional, default false) */
1149 lossless?: boolean | undefined;
1150 /** Level of CPU effort to reduce file size, between 0 (fastest) and 9 (slowest) (optional, default 4) */
1151 effort?: number | undefined;
1152 /** set to '4:2:0' to use chroma subsampling (optional, default '4:4:4') */
1153 chromaSubsampling?: string | undefined;
1154 }
1155
1156 interface GifOptions extends OutputOptions, AnimationOptions {
1157 /** Re-use existing palette, otherwise generate new (slow) */
1158 reuse?: boolean | undefined;
1159 /** Use progressive (interlace) scan */
1160 progressive?: boolean | undefined;
1161 /** Maximum number of palette entries, including transparency, between 2 and 256 (optional, default 256) */
1162 colours?: number | undefined;
1163 /** Alternative spelling of "colours". Maximum number of palette entries, including transparency, between 2 and 256 (optional, default 256) */
1164 colors?: number | undefined;
1165 /** Level of CPU effort to reduce file size, between 1 (fastest) and 10 (slowest) (optional, default 7) */
1166 effort?: number | undefined;
1167 /** Level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) (optional, default 1.0) */
1168 dither?: number | undefined;
1169 /** Maximum inter-frame error for transparency, between 0 (lossless) and 32 (optional, default 0) */
1170 interFrameMaxError?: number;
1171 /** Maximum inter-palette error for palette reuse, between 0 and 256 (optional, default 3) */
1172 interPaletteMaxError?: number;
1173 }
1174
1175 interface TiffOptions extends OutputOptions {
1176 /** Quality, integer 1-100 (optional, default 80) */
1177 quality?: number | undefined;
1178 /** Compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k (optional, default 'jpeg') */
1179 compression?: string | undefined;
1180 /** Compression predictor options: none, horizontal, float (optional, default 'horizontal') */
1181 predictor?: string | undefined;
1182 /** Write an image pyramid (optional, default false) */
1183 pyramid?: boolean | undefined;
1184 /** Write a tiled tiff (optional, default false) */
1185 tile?: boolean | undefined;
1186 /** Horizontal tile size (optional, default 256) */
1187 tileWidth?: number | undefined;
1188 /** Vertical tile size (optional, default 256) */
1189 tileHeight?: number | undefined;
1190 /** Horizontal resolution in pixels/mm (optional, default 1.0) */
1191 xres?: number | undefined;
1192 /** Vertical resolution in pixels/mm (optional, default 1.0) */
1193 yres?: number | undefined;
1194 /** Reduce bitdepth to 1, 2 or 4 bit (optional, default 8) */
1195 bitdepth?: 1 | 2 | 4 | 8 | undefined;
1196 /** Resolution unit options: inch, cm (optional, default 'inch') */
1197 resolutionUnit?: 'inch' | 'cm' | undefined;
1198 }
1199
1200 interface PngOptions extends OutputOptions {
1201 /** Use progressive (interlace) scan (optional, default false) */
1202 progressive?: boolean | undefined;
1203 /** zlib compression level, 0-9 (optional, default 6) */
1204 compressionLevel?: number | undefined;
1205 /** Use adaptive row filtering (optional, default false) */
1206 adaptiveFiltering?: boolean | undefined;
1207 /** Use the lowest number of colours needed to achieve given quality (optional, default `100`) */
1208 quality?: number | undefined;
1209 /** Level of CPU effort to reduce file size, between 1 (fastest) and 10 (slowest), sets palette to true (optional, default 7) */
1210 effort?: number | undefined;
1211 /** Quantise to a palette-based image with alpha transparency support (optional, default false) */
1212 palette?: boolean | undefined;
1213 /** Maximum number of palette entries (optional, default 256) */
1214 colours?: number | undefined;
1215 /** Alternative Spelling of "colours". Maximum number of palette entries (optional, default 256) */
1216 colors?: number | undefined;
1217 /** Level of Floyd-Steinberg error diffusion (optional, default 1.0) */
1218 dither?: number | undefined;
1219 }
1220
1221 interface RotateOptions {
1222 /** parsed by the color module to extract values for red, green, blue and alpha. (optional, default "#000000") */
1223 background?: Color | undefined;
1224 }
1225
1226 interface FlattenOptions {
1227 /** background colour, parsed by the color module, defaults to black. (optional, default {r:0,g:0,b:0}) */
1228 background?: Color | undefined;
1229 }
1230
1231 interface NegateOptions {
1232 /** whether or not to negate any alpha channel. (optional, default true) */
1233 alpha?: boolean | undefined;
1234 }
1235
1236 interface NormaliseOptions {
1237 /** Percentile below which luminance values will be underexposed. */
1238 lower?: number | undefined;
1239 /** Percentile above which luminance values will be overexposed. */
1240 upper?: number | undefined;
1241 }
1242
1243 interface ResizeOptions {
1244 /** Alternative means of specifying width. If both are present this takes priority. */
1245 width?: number | undefined;
1246 /** Alternative means of specifying height. If both are present this takes priority. */
1247 height?: number | undefined;
1248 /** How the image should be resized to fit both provided dimensions, one of cover, contain, fill, inside or outside. (optional, default 'cover') */
1249 fit?: keyof FitEnum | undefined;
1250 /** Position, gravity or strategy to use when fit is cover or contain. (optional, default 'centre') */
1251 position?: number | string | undefined;
1252 /** Background colour when using a fit of contain, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */
1253 background?: Color | undefined;
1254 /** The kernel to use for image reduction. (optional, default 'lanczos3') */
1255 kernel?: keyof KernelEnum | undefined;
1256 /** Do not enlarge if the width or height are already less than the specified dimensions, equivalent to GraphicsMagick's > geometry option. (optional, default false) */
1257 withoutEnlargement?: boolean | undefined;
1258 /** Do not reduce if the width or height are already greater than the specified dimensions, equivalent to GraphicsMagick's < geometry option. (optional, default false) */
1259 withoutReduction?: boolean | undefined;
1260 /** 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) */
1261 fastShrinkOnLoad?: boolean | undefined;
1262 }
1263
1264 interface Region {
1265 /** zero-indexed offset from left edge */
1266 left: number;
1267 /** zero-indexed offset from top edge */
1268 top: number;
1269 /** dimension of extracted image */
1270 width: number;
1271 /** dimension of extracted image */
1272 height: number;
1273 }
1274
1275 interface Noise {
1276 /** type of generated noise, currently only gaussian is supported. */
1277 type?: 'gaussian' | undefined;
1278 /** mean of pixels in generated noise. */
1279 mean?: number | undefined;
1280 /** standard deviation of pixels in generated noise. */
1281 sigma?: number | undefined;
1282 }
1283
1284 type ExtendWith = 'background' | 'copy' | 'repeat' | 'mirror';
1285
1286 interface ExtendOptions {
1287 /** single pixel count to top edge (optional, default 0) */
1288 top?: number | undefined;
1289 /** single pixel count to left edge (optional, default 0) */
1290 left?: number | undefined;
1291 /** single pixel count to bottom edge (optional, default 0) */
1292 bottom?: number | undefined;
1293 /** single pixel count to right edge (optional, default 0) */
1294 right?: number | undefined;
1295 /** background colour, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */
1296 background?: Color | undefined;
1297 /** how the extension is done, one of: "background", "copy", "repeat", "mirror" (optional, default `'background'`) */
1298 extendWith?: ExtendWith | undefined;
1299 }
1300
1301 interface TrimOptions {
1302 /** background colour, parsed by the color module, defaults to that of the top-left pixel. (optional) */
1303 background?: Color | undefined;
1304 /** the allowed difference from the above colour, a positive number. (optional, default `10`) */
1305 threshold?: number | undefined;
1306 }
1307
1308 interface RawOptions {
1309 depth?: 'char' | 'uchar' | 'short' | 'ushort' | 'int' | 'uint' | 'float' | 'complex' | 'double' | 'dpcomplex';
1310 }
1311
1312 /** 3 for sRGB, 4 for CMYK */
1313 type Channels = 3 | 4;
1314
1315 interface RGBA {
1316 r?: number | undefined;
1317 g?: number | undefined;
1318 b?: number | undefined;
1319 alpha?: number | undefined;
1320 }
1321
1322 type Color = string | RGBA;
1323
1324 interface Kernel {
1325 /** width of the kernel in pixels. */
1326 width: number;
1327 /** height of the kernel in pixels. */
1328 height: number;
1329 /** Array of length width*height containing the kernel values. */
1330 kernel: ArrayLike<number>;
1331 /** the scale of the kernel in pixels. (optional, default sum) */
1332 scale?: number | undefined;
1333 /** the offset of the kernel in pixels. (optional, default 0) */
1334 offset?: number | undefined;
1335 }
1336
1337 interface ClaheOptions {
1338 /** width of the region */
1339 width: number;
1340 /** height of the region */
1341 height: number;
1342 /** max slope of the cumulative contrast. A value of 0 disables contrast limiting. Valid values are integers in the range 0-100 (inclusive) (optional, default 3) */
1343 maxSlope?: number | undefined;
1344 }
1345
1346 interface ThresholdOptions {
1347 /** convert to single channel greyscale. (optional, default true) */
1348 greyscale?: boolean | undefined;
1349 /** alternative spelling for greyscale. (optional, default true) */
1350 grayscale?: boolean | undefined;
1351 }
1352
1353 interface OverlayOptions extends SharpOptions {
1354 /** Buffer containing image data, String containing the path to an image file, or Create object */
1355 input?: string | Buffer | { create: Create } | { text: CreateText } | { raw: CreateRaw } | undefined;
1356 /** how to blend this image with the image below. (optional, default `'over'`) */
1357 blend?: Blend | undefined;
1358 /** gravity at which to place the overlay. (optional, default 'centre') */
1359 gravity?: Gravity | undefined;
1360 /** the pixel offset from the top edge. */
1361 top?: number | undefined;
1362 /** the pixel offset from the left edge. */
1363 left?: number | undefined;
1364 /** set to true to repeat the overlay image across the entire image with the given gravity. (optional, default false) */
1365 tile?: boolean | undefined;
1366 /** Set to true to avoid premultipling the image below. Equivalent to the --premultiplied vips option. */
1367 premultiplied?: boolean | undefined;
1368 }
1369
1370 interface TileOptions {
1371 /** Tile size in pixels, a value between 1 and 8192. (optional, default 256) */
1372 size?: number | undefined;
1373 /** Tile overlap in pixels, a value between 0 and 8192. (optional, default 0) */
1374 overlap?: number | undefined;
1375 /** Tile angle of rotation, must be a multiple of 90. (optional, default 0) */
1376 angle?: number | undefined;
1377 /** background colour, parsed by the color module, defaults to white without transparency. (optional, default {r:255,g:255,b:255,alpha:1}) */
1378 background?: string | RGBA | undefined;
1379 /** How deep to make the pyramid, possible values are "onepixel", "onetile" or "one" (default based on layout) */
1380 depth?: string | undefined;
1381 /** Threshold to skip tile generation, a value 0 - 255 for 8-bit images or 0 - 65535 for 16-bit images */
1382 skipBlanks?: number | undefined;
1383 /** Tile container, with value fs (filesystem) or zip (compressed file). (optional, default 'fs') */
1384 container?: TileContainer | undefined;
1385 /** Filesystem layout, possible values are dz, iiif, iiif3, zoomify or google. (optional, default 'dz') */
1386 layout?: TileLayout | undefined;
1387 /** Centre image in tile. (optional, default false) */
1388 centre?: boolean | undefined;
1389 /** Alternative spelling of centre. (optional, default false) */
1390 center?: boolean | undefined;
1391 /** When layout is iiif/iiif3, sets the @id/id attribute of info.json (optional, default 'https://example.com/iiif') */
1392 id?: string | undefined;
1393 /** The name of the directory within the zip file when container is `zip`. */
1394 basename?: string | undefined;
1395 }
1396
1397 interface AnimationOptions {
1398 /** Number of animation iterations, a value between 0 and 65535. Use 0 for infinite animation. (optional, default 0) */
1399 loop?: number | undefined;
1400 /** delay(s) between animation frames (in milliseconds), each value between 0 and 65535. (optional) */
1401 delay?: number | number[] | undefined;
1402 }
1403
1404 interface SharpenOptions {
1405 /** The sigma of the Gaussian mask, where sigma = 1 + radius / 2, between 0.000001 and 10000 */
1406 sigma: number;
1407 /** The level of sharpening to apply to "flat" areas, between 0 and 1000000 (optional, default 1.0) */
1408 m1?: number | undefined;
1409 /** The level of sharpening to apply to "jagged" areas, between 0 and 1000000 (optional, default 2.0) */
1410 m2?: number | undefined;
1411 /** Threshold between "flat" and "jagged", between 0 and 1000000 (optional, default 2.0) */
1412 x1?: number | undefined;
1413 /** Maximum amount of brightening, between 0 and 1000000 (optional, default 10.0) */
1414 y2?: number | undefined;
1415 /** Maximum amount of darkening, between 0 and 1000000 (optional, default 20.0) */
1416 y3?: number | undefined;
1417 }
1418
1419 interface AffineOptions {
1420 /** Parsed by the color module to extract values for red, green, blue and alpha. (optional, default "#000000") */
1421 background?: string | object | undefined;
1422 /** Input horizontal offset (optional, default 0) */
1423 idx?: number | undefined;
1424 /** Input vertical offset (optional, default 0) */
1425 idy?: number | undefined;
1426 /** Output horizontal offset (optional, default 0) */
1427 odx?: number | undefined;
1428 /** Output horizontal offset (optional, default 0) */
1429 ody?: number | undefined;
1430 /** Interpolator (optional, default sharp.interpolators.bicubic) */
1431 interpolator?: Interpolators[keyof Interpolators] | undefined;
1432 }
1433
1434 interface OutputInfo {
1435 format: string;
1436 size: number;
1437 width: number;
1438 height: number;
1439 channels: 1 | 2 | 3 | 4;
1440 /** indicating if premultiplication was used */
1441 premultiplied: boolean;
1442 /** Only defined when using a crop strategy */
1443 cropOffsetLeft?: number | undefined;
1444 /** Only defined when using a crop strategy */
1445 cropOffsetTop?: number | undefined;
1446 /** Only defined when using a trim method */
1447 trimOffsetLeft?: number | undefined;
1448 /** Only defined when using a trim method */
1449 trimOffsetTop?: number | undefined;
1450 /** DPI the font was rendered at, only defined when using `text` input */
1451 textAutofitDpi?: number | undefined;
1452 /** When using the attention crop strategy, the focal point of the cropped region */
1453 attentionX?: number | undefined;
1454 attentionY?: number | undefined;
1455 }
1456
1457 interface AvailableFormatInfo {
1458 id: string;
1459 input: { file: boolean; buffer: boolean; stream: boolean; fileSuffix?: string[] };
1460 output: { file: boolean; buffer: boolean; stream: boolean; alias?: string[] };
1461 }
1462
1463 interface FitEnum {
1464 contain: 'contain';
1465 cover: 'cover';
1466 fill: 'fill';
1467 inside: 'inside';
1468 outside: 'outside';
1469 }
1470
1471 interface KernelEnum {
1472 nearest: 'nearest';
1473 cubic: 'cubic';
1474 mitchell: 'mitchell';
1475 lanczos2: 'lanczos2';
1476 lanczos3: 'lanczos3';
1477 }
1478
1479 interface BoolEnum {
1480 and: 'and';
1481 or: 'or';
1482 eor: 'eor';
1483 }
1484
1485 interface ColourspaceEnum {
1486 multiband: string;
1487 'b-w': string;
1488 bw: string;
1489 cmyk: string;
1490 srgb: string;
1491 }
1492
1493 type FailOnOptions = 'none' | 'truncated' | 'error' | 'warning';
1494
1495 type TextAlign = 'left' | 'centre' | 'center' | 'right';
1496
1497 type TextWrap = 'word' | 'char' | 'charWord' | 'none';
1498
1499 type TileContainer = 'fs' | 'zip';
1500
1501 type TileLayout = 'dz' | 'iiif' | 'iiif3' | 'zoomify' | 'google';
1502
1503 type Blend =
1504 | 'clear'
1505 | 'source'
1506 | 'over'
1507 | 'in'
1508 | 'out'
1509 | 'atop'
1510 | 'dest'
1511 | 'dest-over'
1512 | 'dest-in'
1513 | 'dest-out'
1514 | 'dest-atop'
1515 | 'xor'
1516 | 'add'
1517 | 'saturate'
1518 | 'multiply'
1519 | 'screen'
1520 | 'overlay'
1521 | 'darken'
1522 | 'lighten'
1523 | 'color-dodge'
1524 | 'colour-dodge'
1525 | 'color-burn'
1526 | 'colour-burn'
1527 | 'hard-light'
1528 | 'soft-light'
1529 | 'difference'
1530 | 'exclusion';
1531
1532 type Gravity = number | string;
1533
1534 interface GravityEnum {
1535 north: number;
1536 northeast: number;
1537 southeast: number;
1538 south: number;
1539 southwest: number;
1540 west: number;
1541 northwest: number;
1542 east: number;
1543 center: number;
1544 centre: number;
1545 }
1546
1547 interface StrategyEnum {
1548 entropy: number;
1549 attention: number;
1550 }
1551
1552 interface FormatEnum {
1553 avif: AvailableFormatInfo;
1554 dz: AvailableFormatInfo;
1555 fits: AvailableFormatInfo;
1556 gif: AvailableFormatInfo;
1557 heif: AvailableFormatInfo;
1558 input: AvailableFormatInfo;
1559 jpeg: AvailableFormatInfo;
1560 jpg: AvailableFormatInfo;
1561 jp2: AvailableFormatInfo;
1562 jxl: AvailableFormatInfo;
1563 magick: AvailableFormatInfo;
1564 openslide: AvailableFormatInfo;
1565 pdf: AvailableFormatInfo;
1566 png: AvailableFormatInfo;
1567 ppm: AvailableFormatInfo;
1568 raw: AvailableFormatInfo;
1569 svg: AvailableFormatInfo;
1570 tiff: AvailableFormatInfo;
1571 tif: AvailableFormatInfo;
1572 v: AvailableFormatInfo;
1573 webp: AvailableFormatInfo;
1574 }
1575
1576 interface CacheResult {
1577 memory: { current: number; high: number; max: number };
1578 files: { current: number; max: number };
1579 items: { current: number; max: number };
1580 }
1581
1582 interface Interpolators {
1583 /** [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. */
1584 nearest: 'nearest';
1585 /** [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. */
1586 bilinear: 'bilinear';
1587 /** [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). */
1588 bicubic: 'bicubic';
1589 /**
1590 * [LBB interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100).
1591 * Prevents some "[acutance](http://en.wikipedia.org/wiki/Acutance)" but typically reduces performance by a factor of 2.
1592 */
1593 locallyBoundedBicubic: 'lbb';
1594 /** [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. */
1595 nohalo: 'nohalo';
1596 /** [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents "staircasing" when enlarging. */
1597 vertexSplitQuadraticBasisSpline: 'vsqbs';
1598 }
1599
1600 type Matrix2x2 = [[number, number], [number, number]];
1601 type Matrix3x3 = [[number, number, number], [number, number, number], [number, number, number]];
1602}
1603
1604export = sharp;