constructor.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. // Copyright 2013 Lovell Fuller and others.
  2. // SPDX-License-Identifier: Apache-2.0
  3. 'use strict';
  4. const util = require('node:util');
  5. const stream = require('node:stream');
  6. const is = require('./is');
  7. require('./sharp');
  8. // Use NODE_DEBUG=sharp to enable libvips warnings
  9. const debuglog = util.debuglog('sharp');
  10. /**
  11. * Constructor factory to create an instance of `sharp`, to which further methods are chained.
  12. *
  13. * JPEG, PNG, WebP, GIF, AVIF or TIFF format image data can be streamed out from this object.
  14. * When using Stream based output, derived attributes are available from the `info` event.
  15. *
  16. * Non-critical problems encountered during processing are emitted as `warning` events.
  17. *
  18. * Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.
  19. *
  20. * When loading more than one page/frame of an animated image,
  21. * these are combined as a vertically-stacked "toilet roll" image
  22. * where the overall height is the `pageHeight` multiplied by the number of `pages`.
  23. *
  24. * @constructs Sharp
  25. *
  26. * @emits Sharp#info
  27. * @emits Sharp#warning
  28. *
  29. * @example
  30. * sharp('input.jpg')
  31. * .resize(300, 200)
  32. * .toFile('output.jpg', function(err) {
  33. * // output.jpg is a 300 pixels wide and 200 pixels high image
  34. * // containing a scaled and cropped version of input.jpg
  35. * });
  36. *
  37. * @example
  38. * // Read image data from remote URL,
  39. * // resize to 300 pixels wide,
  40. * // emit an 'info' event with calculated dimensions
  41. * // and finally write image data to writableStream
  42. * const { body } = fetch('https://...');
  43. * const readableStream = Readable.fromWeb(body);
  44. * const transformer = sharp()
  45. * .resize(300)
  46. * .on('info', ({ height }) => {
  47. * console.log(`Image height is ${height}`);
  48. * });
  49. * readableStream.pipe(transformer).pipe(writableStream);
  50. *
  51. * @example
  52. * // Create a blank 300x200 PNG image of semi-translucent red pixels
  53. * sharp({
  54. * create: {
  55. * width: 300,
  56. * height: 200,
  57. * channels: 4,
  58. * background: { r: 255, g: 0, b: 0, alpha: 0.5 }
  59. * }
  60. * })
  61. * .png()
  62. * .toBuffer()
  63. * .then( ... );
  64. *
  65. * @example
  66. * // Convert an animated GIF to an animated WebP
  67. * await sharp('in.gif', { animated: true }).toFile('out.webp');
  68. *
  69. * @example
  70. * // Read a raw array of pixels and save it to a png
  71. * const input = Uint8Array.from([255, 255, 255, 0, 0, 0]); // or Uint8ClampedArray
  72. * const image = sharp(input, {
  73. * // because the input does not contain its dimensions or how many channels it has
  74. * // we need to specify it in the constructor options
  75. * raw: {
  76. * width: 2,
  77. * height: 1,
  78. * channels: 3
  79. * }
  80. * });
  81. * await image.toFile('my-two-pixels.png');
  82. *
  83. * @example
  84. * // Generate RGB Gaussian noise
  85. * await sharp({
  86. * create: {
  87. * width: 300,
  88. * height: 200,
  89. * channels: 3,
  90. * noise: {
  91. * type: 'gaussian',
  92. * mean: 128,
  93. * sigma: 30
  94. * }
  95. * }
  96. * }).toFile('noise.png');
  97. *
  98. * @example
  99. * // Generate an image from text
  100. * await sharp({
  101. * text: {
  102. * text: 'Hello, world!',
  103. * width: 400, // max width
  104. * height: 300 // max height
  105. * }
  106. * }).toFile('text_bw.png');
  107. *
  108. * @example
  109. * // Generate an rgba image from text using pango markup and font
  110. * await sharp({
  111. * text: {
  112. * text: '<span foreground="red">Red!</span><span background="cyan">blue</span>',
  113. * font: 'sans',
  114. * rgba: true,
  115. * dpi: 300
  116. * }
  117. * }).toFile('text_rgba.png');
  118. *
  119. * @param {(Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string)} [input] - if present, can be
  120. * a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or
  121. * a TypedArray containing raw pixel image data, or
  122. * a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file.
  123. * JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present.
  124. * @param {Object} [options] - if present, is an Object with optional attributes.
  125. * @param {string} [options.failOn='warning'] - 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.
  126. * @param {number|boolean} [options.limitInputPixels=268402689] - Do not process input images where the number of pixels
  127. * (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted.
  128. * An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF).
  129. * @param {boolean} [options.unlimited=false] - Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF).
  130. * @param {boolean} [options.sequentialRead=true] - Set this to `false` to use random access rather than sequential read. Some operations will do this automatically.
  131. * @param {number} [options.density=72] - number representing the DPI for vector images in the range 1 to 100000.
  132. * @param {number} [options.ignoreIcc=false] - should the embedded ICC profile, if any, be ignored.
  133. * @param {number} [options.pages=1] - Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages.
  134. * @param {number} [options.page=0] - Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based.
  135. * @param {number} [options.subifd=-1] - subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image.
  136. * @param {number} [options.level=0] - level to extract from a multi-level input (OpenSlide), zero based.
  137. * @param {boolean} [options.animated=false] - Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`.
  138. * @param {Object} [options.raw] - describes raw pixel input image data. See `raw()` for pixel ordering.
  139. * @param {number} [options.raw.width] - integral number of pixels wide.
  140. * @param {number} [options.raw.height] - integral number of pixels high.
  141. * @param {number} [options.raw.channels] - integral number of channels, between 1 and 4.
  142. * @param {boolean} [options.raw.premultiplied] - specifies that the raw input has already been premultiplied, set to `true`
  143. * to avoid sharp premultiplying the image. (optional, default `false`)
  144. * @param {Object} [options.create] - describes a new image to be created.
  145. * @param {number} [options.create.width] - integral number of pixels wide.
  146. * @param {number} [options.create.height] - integral number of pixels high.
  147. * @param {number} [options.create.channels] - integral number of channels, either 3 (RGB) or 4 (RGBA).
  148. * @param {string|Object} [options.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
  149. * @param {Object} [options.create.noise] - describes a noise to be created.
  150. * @param {string} [options.create.noise.type] - type of generated noise, currently only `gaussian` is supported.
  151. * @param {number} [options.create.noise.mean] - mean of pixels in generated noise.
  152. * @param {number} [options.create.noise.sigma] - standard deviation of pixels in generated noise.
  153. * @param {Object} [options.text] - describes a new text image to be created.
  154. * @param {string} [options.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.
  155. * @param {string} [options.text.font] - font name to render with.
  156. * @param {string} [options.text.fontfile] - absolute filesystem path to a font file that can be used by `font`.
  157. * @param {number} [options.text.width=0] - Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries.
  158. * @param {number} [options.text.height=0] - Maximum integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0.
  159. * @param {string} [options.text.align='left'] - Alignment style for multi-line text (`'left'`, `'centre'`, `'center'`, `'right'`).
  160. * @param {boolean} [options.text.justify=false] - set this to true to apply justification to the text.
  161. * @param {number} [options.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified.
  162. * @param {boolean} [options.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`.
  163. * @param {number} [options.text.spacing=0] - text line height in points. Will use the font line height if none is specified.
  164. * @param {string} [options.text.wrap='word'] - word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'.
  165. * @returns {Sharp}
  166. * @throws {Error} Invalid parameters
  167. */
  168. const Sharp = function (input, options) {
  169. if (arguments.length === 1 && !is.defined(input)) {
  170. throw new Error('Invalid input');
  171. }
  172. if (!(this instanceof Sharp)) {
  173. return new Sharp(input, options);
  174. }
  175. stream.Duplex.call(this);
  176. this.options = {
  177. // resize options
  178. topOffsetPre: -1,
  179. leftOffsetPre: -1,
  180. widthPre: -1,
  181. heightPre: -1,
  182. topOffsetPost: -1,
  183. leftOffsetPost: -1,
  184. widthPost: -1,
  185. heightPost: -1,
  186. width: -1,
  187. height: -1,
  188. canvas: 'crop',
  189. position: 0,
  190. resizeBackground: [0, 0, 0, 255],
  191. useExifOrientation: false,
  192. angle: 0,
  193. rotationAngle: 0,
  194. rotationBackground: [0, 0, 0, 255],
  195. rotateBeforePreExtract: false,
  196. flip: false,
  197. flop: false,
  198. extendTop: 0,
  199. extendBottom: 0,
  200. extendLeft: 0,
  201. extendRight: 0,
  202. extendBackground: [0, 0, 0, 255],
  203. extendWith: 'background',
  204. withoutEnlargement: false,
  205. withoutReduction: false,
  206. affineMatrix: [],
  207. affineBackground: [0, 0, 0, 255],
  208. affineIdx: 0,
  209. affineIdy: 0,
  210. affineOdx: 0,
  211. affineOdy: 0,
  212. affineInterpolator: this.constructor.interpolators.bilinear,
  213. kernel: 'lanczos3',
  214. fastShrinkOnLoad: true,
  215. // operations
  216. tint: [-1, 0, 0, 0],
  217. flatten: false,
  218. flattenBackground: [0, 0, 0],
  219. unflatten: false,
  220. negate: false,
  221. negateAlpha: true,
  222. medianSize: 0,
  223. blurSigma: 0,
  224. precision: 'integer',
  225. minAmpl: 0.2,
  226. sharpenSigma: 0,
  227. sharpenM1: 1,
  228. sharpenM2: 2,
  229. sharpenX1: 2,
  230. sharpenY2: 10,
  231. sharpenY3: 20,
  232. threshold: 0,
  233. thresholdGrayscale: true,
  234. trimBackground: [],
  235. trimThreshold: -1,
  236. trimLineArt: false,
  237. gamma: 0,
  238. gammaOut: 0,
  239. greyscale: false,
  240. normalise: false,
  241. normaliseLower: 1,
  242. normaliseUpper: 99,
  243. claheWidth: 0,
  244. claheHeight: 0,
  245. claheMaxSlope: 3,
  246. brightness: 1,
  247. saturation: 1,
  248. hue: 0,
  249. lightness: 0,
  250. booleanBufferIn: null,
  251. booleanFileIn: '',
  252. joinChannelIn: [],
  253. extractChannel: -1,
  254. removeAlpha: false,
  255. ensureAlpha: -1,
  256. colourspace: 'srgb',
  257. colourspacePipeline: 'last',
  258. composite: [],
  259. // output
  260. fileOut: '',
  261. formatOut: 'input',
  262. streamOut: false,
  263. keepMetadata: 0,
  264. withMetadataOrientation: -1,
  265. withMetadataDensity: 0,
  266. withIccProfile: '',
  267. withExif: {},
  268. withExifMerge: true,
  269. resolveWithObject: false,
  270. // output format
  271. jpegQuality: 80,
  272. jpegProgressive: false,
  273. jpegChromaSubsampling: '4:2:0',
  274. jpegTrellisQuantisation: false,
  275. jpegOvershootDeringing: false,
  276. jpegOptimiseScans: false,
  277. jpegOptimiseCoding: true,
  278. jpegQuantisationTable: 0,
  279. pngProgressive: false,
  280. pngCompressionLevel: 6,
  281. pngAdaptiveFiltering: false,
  282. pngPalette: false,
  283. pngQuality: 100,
  284. pngEffort: 7,
  285. pngBitdepth: 8,
  286. pngDither: 1,
  287. jp2Quality: 80,
  288. jp2TileHeight: 512,
  289. jp2TileWidth: 512,
  290. jp2Lossless: false,
  291. jp2ChromaSubsampling: '4:4:4',
  292. webpQuality: 80,
  293. webpAlphaQuality: 100,
  294. webpLossless: false,
  295. webpNearLossless: false,
  296. webpSmartSubsample: false,
  297. webpPreset: 'default',
  298. webpEffort: 4,
  299. webpMinSize: false,
  300. webpMixed: false,
  301. gifBitdepth: 8,
  302. gifEffort: 7,
  303. gifDither: 1,
  304. gifInterFrameMaxError: 0,
  305. gifInterPaletteMaxError: 3,
  306. gifReuse: true,
  307. gifProgressive: false,
  308. tiffQuality: 80,
  309. tiffCompression: 'jpeg',
  310. tiffPredictor: 'horizontal',
  311. tiffPyramid: false,
  312. tiffMiniswhite: false,
  313. tiffBitdepth: 8,
  314. tiffTile: false,
  315. tiffTileHeight: 256,
  316. tiffTileWidth: 256,
  317. tiffXres: 1.0,
  318. tiffYres: 1.0,
  319. tiffResolutionUnit: 'inch',
  320. heifQuality: 50,
  321. heifLossless: false,
  322. heifCompression: 'av1',
  323. heifEffort: 4,
  324. heifChromaSubsampling: '4:4:4',
  325. heifBitdepth: 8,
  326. jxlDistance: 1,
  327. jxlDecodingTier: 0,
  328. jxlEffort: 7,
  329. jxlLossless: false,
  330. rawDepth: 'uchar',
  331. tileSize: 256,
  332. tileOverlap: 0,
  333. tileContainer: 'fs',
  334. tileLayout: 'dz',
  335. tileFormat: 'last',
  336. tileDepth: 'last',
  337. tileAngle: 0,
  338. tileSkipBlanks: -1,
  339. tileBackground: [255, 255, 255, 255],
  340. tileCentre: false,
  341. tileId: 'https://example.com/iiif',
  342. tileBasename: '',
  343. timeoutSeconds: 0,
  344. linearA: [],
  345. linearB: [],
  346. // Function to notify of libvips warnings
  347. debuglog: warning => {
  348. this.emit('warning', warning);
  349. debuglog(warning);
  350. },
  351. // Function to notify of queue length changes
  352. queueListener: function (queueLength) {
  353. Sharp.queue.emit('change', queueLength);
  354. }
  355. };
  356. this.options.input = this._createInputDescriptor(input, options, { allowStream: true });
  357. return this;
  358. };
  359. Object.setPrototypeOf(Sharp.prototype, stream.Duplex.prototype);
  360. Object.setPrototypeOf(Sharp, stream.Duplex);
  361. /**
  362. * Take a "snapshot" of the Sharp instance, returning a new instance.
  363. * Cloned instances inherit the input of their parent instance.
  364. * This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream.
  365. *
  366. * @example
  367. * const pipeline = sharp().rotate();
  368. * pipeline.clone().resize(800, 600).pipe(firstWritableStream);
  369. * pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 }).pipe(secondWritableStream);
  370. * readableStream.pipe(pipeline);
  371. * // firstWritableStream receives auto-rotated, resized readableStream
  372. * // secondWritableStream receives auto-rotated, extracted region of readableStream
  373. *
  374. * @example
  375. * // Create a pipeline that will download an image, resize it and format it to different files
  376. * // Using Promises to know when the pipeline is complete
  377. * const fs = require("fs");
  378. * const got = require("got");
  379. * const sharpStream = sharp({ failOn: 'none' });
  380. *
  381. * const promises = [];
  382. *
  383. * promises.push(
  384. * sharpStream
  385. * .clone()
  386. * .jpeg({ quality: 100 })
  387. * .toFile("originalFile.jpg")
  388. * );
  389. *
  390. * promises.push(
  391. * sharpStream
  392. * .clone()
  393. * .resize({ width: 500 })
  394. * .jpeg({ quality: 80 })
  395. * .toFile("optimized-500.jpg")
  396. * );
  397. *
  398. * promises.push(
  399. * sharpStream
  400. * .clone()
  401. * .resize({ width: 500 })
  402. * .webp({ quality: 80 })
  403. * .toFile("optimized-500.webp")
  404. * );
  405. *
  406. * // https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md
  407. * got.stream("https://www.example.com/some-file.jpg").pipe(sharpStream);
  408. *
  409. * Promise.all(promises)
  410. * .then(res => { console.log("Done!", res); })
  411. * .catch(err => {
  412. * console.error("Error processing files, let's clean it up", err);
  413. * try {
  414. * fs.unlinkSync("originalFile.jpg");
  415. * fs.unlinkSync("optimized-500.jpg");
  416. * fs.unlinkSync("optimized-500.webp");
  417. * } catch (e) {}
  418. * });
  419. *
  420. * @returns {Sharp}
  421. */
  422. function clone () {
  423. // Clone existing options
  424. const clone = this.constructor.call();
  425. const { debuglog, queueListener, ...options } = this.options;
  426. clone.options = structuredClone(options);
  427. clone.options.debuglog = debuglog;
  428. clone.options.queueListener = queueListener;
  429. // Pass 'finish' event to clone for Stream-based input
  430. if (this._isStreamInput()) {
  431. this.on('finish', () => {
  432. // Clone inherits input data
  433. this._flattenBufferIn();
  434. clone.options.input.buffer = this.options.input.buffer;
  435. clone.emit('finish');
  436. });
  437. }
  438. return clone;
  439. }
  440. Object.assign(Sharp.prototype, { clone });
  441. /**
  442. * Export constructor.
  443. * @private
  444. */
  445. module.exports = Sharp;