output.js 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666
  1. /*!
  2. Copyright 2013 Lovell Fuller and others.
  3. SPDX-License-Identifier: Apache-2.0
  4. */
  5. const path = require('node:path');
  6. const is = require('./is');
  7. const sharp = require('./sharp');
  8. const formats = new Map([
  9. ['heic', 'heif'],
  10. ['heif', 'heif'],
  11. ['avif', 'avif'],
  12. ['jpeg', 'jpeg'],
  13. ['jpg', 'jpeg'],
  14. ['jpe', 'jpeg'],
  15. ['tile', 'tile'],
  16. ['dz', 'tile'],
  17. ['png', 'png'],
  18. ['raw', 'raw'],
  19. ['tiff', 'tiff'],
  20. ['tif', 'tiff'],
  21. ['webp', 'webp'],
  22. ['gif', 'gif'],
  23. ['jp2', 'jp2'],
  24. ['jpx', 'jp2'],
  25. ['j2k', 'jp2'],
  26. ['j2c', 'jp2'],
  27. ['jxl', 'jxl']
  28. ]);
  29. const jp2Regex = /\.(jp[2x]|j2[kc])$/i;
  30. const errJp2Save = () => new Error('JP2 output requires libvips with support for OpenJPEG');
  31. const bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math.log2(colours)));
  32. /**
  33. * Write output image data to a file.
  34. *
  35. * If an explicit output format is not selected, it will be inferred from the extension,
  36. * with JPEG, PNG, WebP, AVIF, TIFF, GIF, DZI, and libvips' V format supported.
  37. * Note that raw pixel data is only supported for buffer output.
  38. *
  39. * By default all metadata will be removed, which includes EXIF-based orientation.
  40. * See {@link #withmetadata withMetadata} for control over this.
  41. *
  42. * The caller is responsible for ensuring directory structures and permissions exist.
  43. *
  44. * A `Promise` is returned when `callback` is not provided.
  45. *
  46. * @example
  47. * sharp(input)
  48. * .toFile('output.png', (err, info) => { ... });
  49. *
  50. * @example
  51. * sharp(input)
  52. * .toFile('output.png')
  53. * .then(info => { ... })
  54. * .catch(err => { ... });
  55. *
  56. * @param {string} fileOut - the path to write the image data to.
  57. * @param {Function} [callback] - called on completion with two arguments `(err, info)`.
  58. * `info` contains the output image `format`, `size` (bytes), `width`, `height`,
  59. * `channels` and `premultiplied` (indicating if premultiplication was used).
  60. * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
  61. * When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region.
  62. * Animated output will also contain `pageHeight` and `pages`.
  63. * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.
  64. * @returns {Promise<Object>} - when no callback is provided
  65. * @throws {Error} Invalid parameters
  66. */
  67. function toFile (fileOut, callback) {
  68. let err;
  69. if (!is.string(fileOut)) {
  70. err = new Error('Missing output file path');
  71. } else if (is.string(this.options.input.file) && path.resolve(this.options.input.file) === path.resolve(fileOut)) {
  72. err = new Error('Cannot use same file for input and output');
  73. } else if (jp2Regex.test(path.extname(fileOut)) && !this.constructor.format.jp2k.output.file) {
  74. err = errJp2Save();
  75. }
  76. if (err) {
  77. if (is.fn(callback)) {
  78. callback(err);
  79. } else {
  80. return Promise.reject(err);
  81. }
  82. } else {
  83. this.options.fileOut = fileOut;
  84. const stack = Error();
  85. return this._pipeline(callback, stack);
  86. }
  87. return this;
  88. }
  89. /**
  90. * Write output to a Buffer.
  91. * JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.
  92. *
  93. * Use {@link #toformat toFormat} or one of the format-specific functions such as {@link #jpeg jpeg}, {@link #png png} etc. to set the output format.
  94. *
  95. * If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output.
  96. *
  97. * By default all metadata will be removed, which includes EXIF-based orientation.
  98. * See {@link #withmetadata withMetadata} for control over this.
  99. *
  100. * `callback`, if present, gets three arguments `(err, data, info)` where:
  101. * - `err` is an error, if any.
  102. * - `data` is the output image data.
  103. * - `info` contains the output image `format`, `size` (bytes), `width`, `height`,
  104. * `channels` and `premultiplied` (indicating if premultiplication was used).
  105. * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
  106. * Animated output will also contain `pageHeight` and `pages`.
  107. * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.
  108. *
  109. * A `Promise` is returned when `callback` is not provided.
  110. *
  111. * @example
  112. * sharp(input)
  113. * .toBuffer((err, data, info) => { ... });
  114. *
  115. * @example
  116. * sharp(input)
  117. * .toBuffer()
  118. * .then(data => { ... })
  119. * .catch(err => { ... });
  120. *
  121. * @example
  122. * sharp(input)
  123. * .png()
  124. * .toBuffer({ resolveWithObject: true })
  125. * .then(({ data, info }) => { ... })
  126. * .catch(err => { ... });
  127. *
  128. * @example
  129. * const { data, info } = await sharp('my-image.jpg')
  130. * // output the raw pixels
  131. * .raw()
  132. * .toBuffer({ resolveWithObject: true });
  133. *
  134. * // create a more type safe way to work with the raw pixel data
  135. * // this will not copy the data, instead it will change `data`s underlying ArrayBuffer
  136. * // so `data` and `pixelArray` point to the same memory location
  137. * const pixelArray = new Uint8ClampedArray(data.buffer);
  138. *
  139. * // When you are done changing the pixelArray, sharp takes the `pixelArray` as an input
  140. * const { width, height, channels } = info;
  141. * await sharp(pixelArray, { raw: { width, height, channels } })
  142. * .toFile('my-changed-image.jpg');
  143. *
  144. * @param {Object} [options]
  145. * @param {boolean} [options.resolveWithObject] Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`.
  146. * @param {Function} [callback]
  147. * @returns {Promise<Buffer>} - when no callback is provided
  148. */
  149. function toBuffer (options, callback) {
  150. if (is.object(options)) {
  151. this._setBooleanOption('resolveWithObject', options.resolveWithObject);
  152. } else if (this.options.resolveWithObject) {
  153. this.options.resolveWithObject = false;
  154. }
  155. this.options.fileOut = '';
  156. const stack = Error();
  157. return this._pipeline(is.fn(options) ? options : callback, stack);
  158. }
  159. /**
  160. * Keep all EXIF metadata from the input image in the output image.
  161. *
  162. * EXIF metadata is unsupported for TIFF output.
  163. *
  164. * @since 0.33.0
  165. *
  166. * @example
  167. * const outputWithExif = await sharp(inputWithExif)
  168. * .keepExif()
  169. * .toBuffer();
  170. *
  171. * @returns {Sharp}
  172. */
  173. function keepExif () {
  174. this.options.keepMetadata |= 0b00001;
  175. return this;
  176. }
  177. /**
  178. * Set EXIF metadata in the output image, ignoring any EXIF in the input image.
  179. *
  180. * @since 0.33.0
  181. *
  182. * @example
  183. * const dataWithExif = await sharp(input)
  184. * .withExif({
  185. * IFD0: {
  186. * Copyright: 'The National Gallery'
  187. * },
  188. * IFD3: {
  189. * GPSLatitudeRef: 'N',
  190. * GPSLatitude: '51/1 30/1 3230/100',
  191. * GPSLongitudeRef: 'W',
  192. * GPSLongitude: '0/1 7/1 4366/100'
  193. * }
  194. * })
  195. * .toBuffer();
  196. *
  197. * @param {Object<string, Object<string, string>>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.
  198. * @returns {Sharp}
  199. * @throws {Error} Invalid parameters
  200. */
  201. function withExif (exif) {
  202. if (is.object(exif)) {
  203. for (const [ifd, entries] of Object.entries(exif)) {
  204. if (is.object(entries)) {
  205. for (const [k, v] of Object.entries(entries)) {
  206. if (is.string(v)) {
  207. this.options.withExif[`exif-${ifd.toLowerCase()}-${k}`] = v;
  208. } else {
  209. throw is.invalidParameterError(`${ifd}.${k}`, 'string', v);
  210. }
  211. }
  212. } else {
  213. throw is.invalidParameterError(ifd, 'object', entries);
  214. }
  215. }
  216. } else {
  217. throw is.invalidParameterError('exif', 'object', exif);
  218. }
  219. this.options.withExifMerge = false;
  220. return this.keepExif();
  221. }
  222. /**
  223. * Update EXIF metadata from the input image in the output image.
  224. *
  225. * @since 0.33.0
  226. *
  227. * @example
  228. * const dataWithMergedExif = await sharp(inputWithExif)
  229. * .withExifMerge({
  230. * IFD0: {
  231. * Copyright: 'The National Gallery'
  232. * }
  233. * })
  234. * .toBuffer();
  235. *
  236. * @param {Object<string, Object<string, string>>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.
  237. * @returns {Sharp}
  238. * @throws {Error} Invalid parameters
  239. */
  240. function withExifMerge (exif) {
  241. this.withExif(exif);
  242. this.options.withExifMerge = true;
  243. return this;
  244. }
  245. /**
  246. * Keep ICC profile from the input image in the output image.
  247. *
  248. * When input and output colour spaces differ, use with {@link /api-colour/#tocolourspace toColourspace} and optionally {@link /api-colour/#pipelinecolourspace pipelineColourspace}.
  249. *
  250. * @since 0.33.0
  251. *
  252. * @example
  253. * const outputWithIccProfile = await sharp(inputWithIccProfile)
  254. * .keepIccProfile()
  255. * .toBuffer();
  256. *
  257. * @example
  258. * const cmykOutputWithIccProfile = await sharp(cmykInputWithIccProfile)
  259. * .pipelineColourspace('cmyk')
  260. * .toColourspace('cmyk')
  261. * .keepIccProfile()
  262. * .toBuffer();
  263. *
  264. * @returns {Sharp}
  265. */
  266. function keepIccProfile () {
  267. this.options.keepMetadata |= 0b01000;
  268. return this;
  269. }
  270. /**
  271. * Transform using an ICC profile and attach to the output image.
  272. *
  273. * This can either be an absolute filesystem path or
  274. * built-in profile name (`srgb`, `p3`, `cmyk`).
  275. *
  276. * @since 0.33.0
  277. *
  278. * @example
  279. * const outputWithP3 = await sharp(input)
  280. * .withIccProfile('p3')
  281. * .toBuffer();
  282. *
  283. * @param {string} icc - Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk).
  284. * @param {Object} [options]
  285. * @param {number} [options.attach=true] Should the ICC profile be included in the output image metadata?
  286. * @returns {Sharp}
  287. * @throws {Error} Invalid parameters
  288. */
  289. function withIccProfile (icc, options) {
  290. if (is.string(icc)) {
  291. this.options.withIccProfile = icc;
  292. } else {
  293. throw is.invalidParameterError('icc', 'string', icc);
  294. }
  295. this.keepIccProfile();
  296. if (is.object(options)) {
  297. if (is.defined(options.attach)) {
  298. if (is.bool(options.attach)) {
  299. if (!options.attach) {
  300. this.options.keepMetadata &= ~0b01000;
  301. }
  302. } else {
  303. throw is.invalidParameterError('attach', 'boolean', options.attach);
  304. }
  305. }
  306. }
  307. return this;
  308. }
  309. /**
  310. * Keep XMP metadata from the input image in the output image.
  311. *
  312. * @since 0.34.3
  313. *
  314. * @example
  315. * const outputWithXmp = await sharp(inputWithXmp)
  316. * .keepXmp()
  317. * .toBuffer();
  318. *
  319. * @returns {Sharp}
  320. */
  321. function keepXmp () {
  322. this.options.keepMetadata |= 0b00010;
  323. return this;
  324. }
  325. /**
  326. * Set XMP metadata in the output image.
  327. *
  328. * Supported by PNG, JPEG, WebP, and TIFF output.
  329. *
  330. * @since 0.34.3
  331. *
  332. * @example
  333. * const xmpString = `
  334. * <?xml version="1.0"?>
  335. * <x:xmpmeta xmlns:x="adobe:ns:meta/">
  336. * <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  337. * <rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">
  338. * <dc:creator><rdf:Seq><rdf:li>John Doe</rdf:li></rdf:Seq></dc:creator>
  339. * </rdf:Description>
  340. * </rdf:RDF>
  341. * </x:xmpmeta>`;
  342. *
  343. * const data = await sharp(input)
  344. * .withXmp(xmpString)
  345. * .toBuffer();
  346. *
  347. * @param {string} xmp String containing XMP metadata to be embedded in the output image.
  348. * @returns {Sharp}
  349. * @throws {Error} Invalid parameters
  350. */
  351. function withXmp (xmp) {
  352. if (is.string(xmp) && xmp.length > 0) {
  353. this.options.withXmp = xmp;
  354. this.options.keepMetadata |= 0b00010;
  355. } else {
  356. throw is.invalidParameterError('xmp', 'non-empty string', xmp);
  357. }
  358. return this;
  359. }
  360. /**
  361. * Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image.
  362. *
  363. * The default behaviour, when `keepMetadata` is not used, is to convert to the device-independent
  364. * sRGB colour space and strip all metadata, including the removal of any ICC profile.
  365. *
  366. * @since 0.33.0
  367. *
  368. * @example
  369. * const outputWithMetadata = await sharp(inputWithMetadata)
  370. * .keepMetadata()
  371. * .toBuffer();
  372. *
  373. * @returns {Sharp}
  374. */
  375. function keepMetadata () {
  376. this.options.keepMetadata = 0b11111;
  377. return this;
  378. }
  379. /**
  380. * Keep most metadata (EXIF, XMP, IPTC) from the input image in the output image.
  381. *
  382. * This will also convert to and add a web-friendly sRGB ICC profile if appropriate.
  383. *
  384. * Allows orientation and density to be set or updated.
  385. *
  386. * @example
  387. * const outputSrgbWithMetadata = await sharp(inputRgbWithMetadata)
  388. * .withMetadata()
  389. * .toBuffer();
  390. *
  391. * @example
  392. * // Set output metadata to 96 DPI
  393. * const data = await sharp(input)
  394. * .withMetadata({ density: 96 })
  395. * .toBuffer();
  396. *
  397. * @param {Object} [options]
  398. * @param {number} [options.orientation] Used to update the EXIF `Orientation` tag, integer between 1 and 8.
  399. * @param {number} [options.density] Number of pixels per inch (DPI).
  400. * @returns {Sharp}
  401. * @throws {Error} Invalid parameters
  402. */
  403. function withMetadata (options) {
  404. this.keepMetadata();
  405. this.withIccProfile('srgb');
  406. if (is.object(options)) {
  407. if (is.defined(options.orientation)) {
  408. if (is.integer(options.orientation) && is.inRange(options.orientation, 1, 8)) {
  409. this.options.withMetadataOrientation = options.orientation;
  410. } else {
  411. throw is.invalidParameterError('orientation', 'integer between 1 and 8', options.orientation);
  412. }
  413. }
  414. if (is.defined(options.density)) {
  415. if (is.number(options.density) && options.density > 0) {
  416. this.options.withMetadataDensity = options.density;
  417. } else {
  418. throw is.invalidParameterError('density', 'positive number', options.density);
  419. }
  420. }
  421. if (is.defined(options.icc)) {
  422. this.withIccProfile(options.icc);
  423. }
  424. if (is.defined(options.exif)) {
  425. this.withExifMerge(options.exif);
  426. }
  427. }
  428. return this;
  429. }
  430. /**
  431. * Force output to a given format.
  432. *
  433. * @example
  434. * // Convert any input to PNG output
  435. * const data = await sharp(input)
  436. * .toFormat('png')
  437. * .toBuffer();
  438. *
  439. * @param {(string|Object)} format - as a string or an Object with an 'id' attribute
  440. * @param {Object} options - output options
  441. * @returns {Sharp}
  442. * @throws {Error} unsupported format or options
  443. */
  444. function toFormat (format, options) {
  445. const actualFormat = formats.get((is.object(format) && is.string(format.id) ? format.id : format).toLowerCase());
  446. if (!actualFormat) {
  447. throw is.invalidParameterError('format', `one of: ${[...formats.keys()].join(', ')}`, format);
  448. }
  449. return this[actualFormat](options);
  450. }
  451. /**
  452. * Use these JPEG options for output image.
  453. *
  454. * @example
  455. * // Convert any input to very high quality JPEG output
  456. * const data = await sharp(input)
  457. * .jpeg({
  458. * quality: 100,
  459. * chromaSubsampling: '4:4:4'
  460. * })
  461. * .toBuffer();
  462. *
  463. * @example
  464. * // Use mozjpeg to reduce output JPEG file size (slower)
  465. * const data = await sharp(input)
  466. * .jpeg({ mozjpeg: true })
  467. * .toBuffer();
  468. *
  469. * @param {Object} [options] - output options
  470. * @param {number} [options.quality=80] - quality, integer 1-100
  471. * @param {boolean} [options.progressive=false] - use progressive (interlace) scan
  472. * @param {string} [options.chromaSubsampling='4:2:0'] - set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling
  473. * @param {boolean} [options.optimiseCoding=true] - optimise Huffman coding tables
  474. * @param {boolean} [options.optimizeCoding=true] - alternative spelling of optimiseCoding
  475. * @param {boolean} [options.mozjpeg=false] - use mozjpeg defaults, equivalent to `{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }`
  476. * @param {boolean} [options.trellisQuantisation=false] - apply trellis quantisation
  477. * @param {boolean} [options.overshootDeringing=false] - apply overshoot deringing
  478. * @param {boolean} [options.optimiseScans=false] - optimise progressive scans, forces progressive
  479. * @param {boolean} [options.optimizeScans=false] - alternative spelling of optimiseScans
  480. * @param {number} [options.quantisationTable=0] - quantization table to use, integer 0-8
  481. * @param {number} [options.quantizationTable=0] - alternative spelling of quantisationTable
  482. * @param {boolean} [options.force=true] - force JPEG output, otherwise attempt to use input format
  483. * @returns {Sharp}
  484. * @throws {Error} Invalid options
  485. */
  486. function jpeg (options) {
  487. if (is.object(options)) {
  488. if (is.defined(options.quality)) {
  489. if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {
  490. this.options.jpegQuality = options.quality;
  491. } else {
  492. throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);
  493. }
  494. }
  495. if (is.defined(options.progressive)) {
  496. this._setBooleanOption('jpegProgressive', options.progressive);
  497. }
  498. if (is.defined(options.chromaSubsampling)) {
  499. if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) {
  500. this.options.jpegChromaSubsampling = options.chromaSubsampling;
  501. } else {
  502. throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);
  503. }
  504. }
  505. const optimiseCoding = is.bool(options.optimizeCoding) ? options.optimizeCoding : options.optimiseCoding;
  506. if (is.defined(optimiseCoding)) {
  507. this._setBooleanOption('jpegOptimiseCoding', optimiseCoding);
  508. }
  509. if (is.defined(options.mozjpeg)) {
  510. if (is.bool(options.mozjpeg)) {
  511. if (options.mozjpeg) {
  512. this.options.jpegTrellisQuantisation = true;
  513. this.options.jpegOvershootDeringing = true;
  514. this.options.jpegOptimiseScans = true;
  515. this.options.jpegProgressive = true;
  516. this.options.jpegQuantisationTable = 3;
  517. }
  518. } else {
  519. throw is.invalidParameterError('mozjpeg', 'boolean', options.mozjpeg);
  520. }
  521. }
  522. const trellisQuantisation = is.bool(options.trellisQuantization) ? options.trellisQuantization : options.trellisQuantisation;
  523. if (is.defined(trellisQuantisation)) {
  524. this._setBooleanOption('jpegTrellisQuantisation', trellisQuantisation);
  525. }
  526. if (is.defined(options.overshootDeringing)) {
  527. this._setBooleanOption('jpegOvershootDeringing', options.overshootDeringing);
  528. }
  529. const optimiseScans = is.bool(options.optimizeScans) ? options.optimizeScans : options.optimiseScans;
  530. if (is.defined(optimiseScans)) {
  531. this._setBooleanOption('jpegOptimiseScans', optimiseScans);
  532. if (optimiseScans) {
  533. this.options.jpegProgressive = true;
  534. }
  535. }
  536. const quantisationTable = is.number(options.quantizationTable) ? options.quantizationTable : options.quantisationTable;
  537. if (is.defined(quantisationTable)) {
  538. if (is.integer(quantisationTable) && is.inRange(quantisationTable, 0, 8)) {
  539. this.options.jpegQuantisationTable = quantisationTable;
  540. } else {
  541. throw is.invalidParameterError('quantisationTable', 'integer between 0 and 8', quantisationTable);
  542. }
  543. }
  544. }
  545. return this._updateFormatOut('jpeg', options);
  546. }
  547. /**
  548. * Use these PNG options for output image.
  549. *
  550. * By default, PNG output is full colour at 8 bits per pixel.
  551. *
  552. * Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel.
  553. * Set `palette` to `true` for slower, indexed PNG output.
  554. *
  555. * For 16 bits per pixel output, convert to `rgb16` via
  556. * {@link /api-colour/#tocolourspace toColourspace}.
  557. *
  558. * @example
  559. * // Convert any input to full colour PNG output
  560. * const data = await sharp(input)
  561. * .png()
  562. * .toBuffer();
  563. *
  564. * @example
  565. * // Convert any input to indexed PNG output (slower)
  566. * const data = await sharp(input)
  567. * .png({ palette: true })
  568. * .toBuffer();
  569. *
  570. * @example
  571. * // Output 16 bits per pixel RGB(A)
  572. * const data = await sharp(input)
  573. * .toColourspace('rgb16')
  574. * .png()
  575. * .toBuffer();
  576. *
  577. * @param {Object} [options]
  578. * @param {boolean} [options.progressive=false] - use progressive (interlace) scan
  579. * @param {number} [options.compressionLevel=6] - zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest)
  580. * @param {boolean} [options.adaptiveFiltering=false] - use adaptive row filtering
  581. * @param {boolean} [options.palette=false] - quantise to a palette-based image with alpha transparency support
  582. * @param {number} [options.quality=100] - use the lowest number of colours needed to achieve given quality, sets `palette` to `true`
  583. * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest), sets `palette` to `true`
  584. * @param {number} [options.colours=256] - maximum number of palette entries, sets `palette` to `true`
  585. * @param {number} [options.colors=256] - alternative spelling of `options.colours`, sets `palette` to `true`
  586. * @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, sets `palette` to `true`
  587. * @param {boolean} [options.force=true] - force PNG output, otherwise attempt to use input format
  588. * @returns {Sharp}
  589. * @throws {Error} Invalid options
  590. */
  591. function png (options) {
  592. if (is.object(options)) {
  593. if (is.defined(options.progressive)) {
  594. this._setBooleanOption('pngProgressive', options.progressive);
  595. }
  596. if (is.defined(options.compressionLevel)) {
  597. if (is.integer(options.compressionLevel) && is.inRange(options.compressionLevel, 0, 9)) {
  598. this.options.pngCompressionLevel = options.compressionLevel;
  599. } else {
  600. throw is.invalidParameterError('compressionLevel', 'integer between 0 and 9', options.compressionLevel);
  601. }
  602. }
  603. if (is.defined(options.adaptiveFiltering)) {
  604. this._setBooleanOption('pngAdaptiveFiltering', options.adaptiveFiltering);
  605. }
  606. const colours = options.colours || options.colors;
  607. if (is.defined(colours)) {
  608. if (is.integer(colours) && is.inRange(colours, 2, 256)) {
  609. this.options.pngBitdepth = bitdepthFromColourCount(colours);
  610. } else {
  611. throw is.invalidParameterError('colours', 'integer between 2 and 256', colours);
  612. }
  613. }
  614. if (is.defined(options.palette)) {
  615. this._setBooleanOption('pngPalette', options.palette);
  616. } else if ([options.quality, options.effort, options.colours, options.colors, options.dither].some(is.defined)) {
  617. this._setBooleanOption('pngPalette', true);
  618. }
  619. if (this.options.pngPalette) {
  620. if (is.defined(options.quality)) {
  621. if (is.integer(options.quality) && is.inRange(options.quality, 0, 100)) {
  622. this.options.pngQuality = options.quality;
  623. } else {
  624. throw is.invalidParameterError('quality', 'integer between 0 and 100', options.quality);
  625. }
  626. }
  627. if (is.defined(options.effort)) {
  628. if (is.integer(options.effort) && is.inRange(options.effort, 1, 10)) {
  629. this.options.pngEffort = options.effort;
  630. } else {
  631. throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort);
  632. }
  633. }
  634. if (is.defined(options.dither)) {
  635. if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) {
  636. this.options.pngDither = options.dither;
  637. } else {
  638. throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither);
  639. }
  640. }
  641. }
  642. }
  643. return this._updateFormatOut('png', options);
  644. }
  645. /**
  646. * Use these WebP options for output image.
  647. *
  648. * @example
  649. * // Convert any input to lossless WebP output
  650. * const data = await sharp(input)
  651. * .webp({ lossless: true })
  652. * .toBuffer();
  653. *
  654. * @example
  655. * // Optimise the file size of an animated WebP
  656. * const outputWebp = await sharp(inputWebp, { animated: true })
  657. * .webp({ effort: 6 })
  658. * .toBuffer();
  659. *
  660. * @param {Object} [options] - output options
  661. * @param {number} [options.quality=80] - quality, integer 1-100
  662. * @param {number} [options.alphaQuality=100] - quality of alpha layer, integer 0-100
  663. * @param {boolean} [options.lossless=false] - use lossless compression mode
  664. * @param {boolean} [options.nearLossless=false] - use near_lossless compression mode
  665. * @param {boolean} [options.smartSubsample=false] - use high quality chroma subsampling
  666. * @param {boolean} [options.smartDeblock=false] - auto-adjust the deblocking filter, can improve low contrast edges (slow)
  667. * @param {string} [options.preset='default'] - named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text
  668. * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 6 (slowest)
  669. * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation
  670. * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)
  671. * @param {boolean} [options.minSize=false] - prevent use of animation key frames to minimise file size (slow)
  672. * @param {boolean} [options.mixed=false] - allow mixture of lossy and lossless animation frames (slow)
  673. * @param {boolean} [options.force=true] - force WebP output, otherwise attempt to use input format
  674. * @returns {Sharp}
  675. * @throws {Error} Invalid options
  676. */
  677. function webp (options) {
  678. if (is.object(options)) {
  679. if (is.defined(options.quality)) {
  680. if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {
  681. this.options.webpQuality = options.quality;
  682. } else {
  683. throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);
  684. }
  685. }
  686. if (is.defined(options.alphaQuality)) {
  687. if (is.integer(options.alphaQuality) && is.inRange(options.alphaQuality, 0, 100)) {
  688. this.options.webpAlphaQuality = options.alphaQuality;
  689. } else {
  690. throw is.invalidParameterError('alphaQuality', 'integer between 0 and 100', options.alphaQuality);
  691. }
  692. }
  693. if (is.defined(options.lossless)) {
  694. this._setBooleanOption('webpLossless', options.lossless);
  695. }
  696. if (is.defined(options.nearLossless)) {
  697. this._setBooleanOption('webpNearLossless', options.nearLossless);
  698. }
  699. if (is.defined(options.smartSubsample)) {
  700. this._setBooleanOption('webpSmartSubsample', options.smartSubsample);
  701. }
  702. if (is.defined(options.smartDeblock)) {
  703. this._setBooleanOption('webpSmartDeblock', options.smartDeblock);
  704. }
  705. if (is.defined(options.preset)) {
  706. if (is.string(options.preset) && is.inArray(options.preset, ['default', 'photo', 'picture', 'drawing', 'icon', 'text'])) {
  707. this.options.webpPreset = options.preset;
  708. } else {
  709. throw is.invalidParameterError('preset', 'one of: default, photo, picture, drawing, icon, text', options.preset);
  710. }
  711. }
  712. if (is.defined(options.effort)) {
  713. if (is.integer(options.effort) && is.inRange(options.effort, 0, 6)) {
  714. this.options.webpEffort = options.effort;
  715. } else {
  716. throw is.invalidParameterError('effort', 'integer between 0 and 6', options.effort);
  717. }
  718. }
  719. if (is.defined(options.minSize)) {
  720. this._setBooleanOption('webpMinSize', options.minSize);
  721. }
  722. if (is.defined(options.mixed)) {
  723. this._setBooleanOption('webpMixed', options.mixed);
  724. }
  725. }
  726. trySetAnimationOptions(options, this.options);
  727. return this._updateFormatOut('webp', options);
  728. }
  729. /**
  730. * Use these GIF options for the output image.
  731. *
  732. * The first entry in the palette is reserved for transparency.
  733. *
  734. * The palette of the input image will be re-used if possible.
  735. *
  736. * @since 0.30.0
  737. *
  738. * @example
  739. * // Convert PNG to GIF
  740. * await sharp(pngBuffer)
  741. * .gif()
  742. * .toBuffer();
  743. *
  744. * @example
  745. * // Convert animated WebP to animated GIF
  746. * await sharp('animated.webp', { animated: true })
  747. * .toFile('animated.gif');
  748. *
  749. * @example
  750. * // Create a 128x128, cropped, non-dithered, animated thumbnail of an animated GIF
  751. * const out = await sharp('in.gif', { animated: true })
  752. * .resize({ width: 128, height: 128 })
  753. * .gif({ dither: 0 })
  754. * .toBuffer();
  755. *
  756. * @example
  757. * // Lossy file size reduction of animated GIF
  758. * await sharp('in.gif', { animated: true })
  759. * .gif({ interFrameMaxError: 8 })
  760. * .toFile('optim.gif');
  761. *
  762. * @param {Object} [options] - output options
  763. * @param {boolean} [options.reuse=true] - re-use existing palette, otherwise generate new (slow)
  764. * @param {boolean} [options.progressive=false] - use progressive (interlace) scan
  765. * @param {number} [options.colours=256] - maximum number of palette entries, including transparency, between 2 and 256
  766. * @param {number} [options.colors=256] - alternative spelling of `options.colours`
  767. * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest)
  768. * @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most)
  769. * @param {number} [options.interFrameMaxError=0] - maximum inter-frame error for transparency, between 0 (lossless) and 32
  770. * @param {number} [options.interPaletteMaxError=3] - maximum inter-palette error for palette reuse, between 0 and 256
  771. * @param {boolean} [options.keepDuplicateFrames=false] - keep duplicate frames in the output instead of combining them
  772. * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation
  773. * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)
  774. * @param {boolean} [options.force=true] - force GIF output, otherwise attempt to use input format
  775. * @returns {Sharp}
  776. * @throws {Error} Invalid options
  777. */
  778. function gif (options) {
  779. if (is.object(options)) {
  780. if (is.defined(options.reuse)) {
  781. this._setBooleanOption('gifReuse', options.reuse);
  782. }
  783. if (is.defined(options.progressive)) {
  784. this._setBooleanOption('gifProgressive', options.progressive);
  785. }
  786. const colours = options.colours || options.colors;
  787. if (is.defined(colours)) {
  788. if (is.integer(colours) && is.inRange(colours, 2, 256)) {
  789. this.options.gifBitdepth = bitdepthFromColourCount(colours);
  790. } else {
  791. throw is.invalidParameterError('colours', 'integer between 2 and 256', colours);
  792. }
  793. }
  794. if (is.defined(options.effort)) {
  795. if (is.number(options.effort) && is.inRange(options.effort, 1, 10)) {
  796. this.options.gifEffort = options.effort;
  797. } else {
  798. throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort);
  799. }
  800. }
  801. if (is.defined(options.dither)) {
  802. if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) {
  803. this.options.gifDither = options.dither;
  804. } else {
  805. throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither);
  806. }
  807. }
  808. if (is.defined(options.interFrameMaxError)) {
  809. if (is.number(options.interFrameMaxError) && is.inRange(options.interFrameMaxError, 0, 32)) {
  810. this.options.gifInterFrameMaxError = options.interFrameMaxError;
  811. } else {
  812. throw is.invalidParameterError('interFrameMaxError', 'number between 0.0 and 32.0', options.interFrameMaxError);
  813. }
  814. }
  815. if (is.defined(options.interPaletteMaxError)) {
  816. if (is.number(options.interPaletteMaxError) && is.inRange(options.interPaletteMaxError, 0, 256)) {
  817. this.options.gifInterPaletteMaxError = options.interPaletteMaxError;
  818. } else {
  819. throw is.invalidParameterError('interPaletteMaxError', 'number between 0.0 and 256.0', options.interPaletteMaxError);
  820. }
  821. }
  822. if (is.defined(options.keepDuplicateFrames)) {
  823. if (is.bool(options.keepDuplicateFrames)) {
  824. this._setBooleanOption('gifKeepDuplicateFrames', options.keepDuplicateFrames);
  825. } else {
  826. throw is.invalidParameterError('keepDuplicateFrames', 'boolean', options.keepDuplicateFrames);
  827. }
  828. }
  829. }
  830. trySetAnimationOptions(options, this.options);
  831. return this._updateFormatOut('gif', options);
  832. }
  833. /**
  834. * Use these JP2 options for output image.
  835. *
  836. * Requires libvips compiled with support for OpenJPEG.
  837. * The prebuilt binaries do not include this - see
  838. * {@link /install#custom-libvips installing a custom libvips}.
  839. *
  840. * @example
  841. * // Convert any input to lossless JP2 output
  842. * const data = await sharp(input)
  843. * .jp2({ lossless: true })
  844. * .toBuffer();
  845. *
  846. * @example
  847. * // Convert any input to very high quality JP2 output
  848. * const data = await sharp(input)
  849. * .jp2({
  850. * quality: 100,
  851. * chromaSubsampling: '4:4:4'
  852. * })
  853. * .toBuffer();
  854. *
  855. * @since 0.29.1
  856. *
  857. * @param {Object} [options] - output options
  858. * @param {number} [options.quality=80] - quality, integer 1-100
  859. * @param {boolean} [options.lossless=false] - use lossless compression mode
  860. * @param {number} [options.tileWidth=512] - horizontal tile size
  861. * @param {number} [options.tileHeight=512] - vertical tile size
  862. * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling
  863. * @returns {Sharp}
  864. * @throws {Error} Invalid options
  865. */
  866. function jp2 (options) {
  867. /* node:coverage ignore next 41 */
  868. if (!this.constructor.format.jp2k.output.buffer) {
  869. throw errJp2Save();
  870. }
  871. if (is.object(options)) {
  872. if (is.defined(options.quality)) {
  873. if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {
  874. this.options.jp2Quality = options.quality;
  875. } else {
  876. throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);
  877. }
  878. }
  879. if (is.defined(options.lossless)) {
  880. if (is.bool(options.lossless)) {
  881. this.options.jp2Lossless = options.lossless;
  882. } else {
  883. throw is.invalidParameterError('lossless', 'boolean', options.lossless);
  884. }
  885. }
  886. if (is.defined(options.tileWidth)) {
  887. if (is.integer(options.tileWidth) && is.inRange(options.tileWidth, 1, 32768)) {
  888. this.options.jp2TileWidth = options.tileWidth;
  889. } else {
  890. throw is.invalidParameterError('tileWidth', 'integer between 1 and 32768', options.tileWidth);
  891. }
  892. }
  893. if (is.defined(options.tileHeight)) {
  894. if (is.integer(options.tileHeight) && is.inRange(options.tileHeight, 1, 32768)) {
  895. this.options.jp2TileHeight = options.tileHeight;
  896. } else {
  897. throw is.invalidParameterError('tileHeight', 'integer between 1 and 32768', options.tileHeight);
  898. }
  899. }
  900. if (is.defined(options.chromaSubsampling)) {
  901. if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) {
  902. this.options.jp2ChromaSubsampling = options.chromaSubsampling;
  903. } else {
  904. throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);
  905. }
  906. }
  907. }
  908. return this._updateFormatOut('jp2', options);
  909. }
  910. /**
  911. * Set animation options if available.
  912. * @private
  913. *
  914. * @param {Object} [source] - output options
  915. * @param {number} [source.loop=0] - number of animation iterations, use 0 for infinite animation
  916. * @param {number[]} [source.delay] - list of delays between animation frames (in milliseconds)
  917. * @param {Object} [target] - target object for valid options
  918. * @throws {Error} Invalid options
  919. */
  920. function trySetAnimationOptions (source, target) {
  921. if (is.object(source) && is.defined(source.loop)) {
  922. if (is.integer(source.loop) && is.inRange(source.loop, 0, 65535)) {
  923. target.loop = source.loop;
  924. } else {
  925. throw is.invalidParameterError('loop', 'integer between 0 and 65535', source.loop);
  926. }
  927. }
  928. if (is.object(source) && is.defined(source.delay)) {
  929. // We allow singular values as well
  930. if (is.integer(source.delay) && is.inRange(source.delay, 0, 65535)) {
  931. target.delay = [source.delay];
  932. } else if (
  933. Array.isArray(source.delay) &&
  934. source.delay.every(is.integer) &&
  935. source.delay.every(v => is.inRange(v, 0, 65535))) {
  936. target.delay = source.delay;
  937. } else {
  938. throw is.invalidParameterError('delay', 'integer or an array of integers between 0 and 65535', source.delay);
  939. }
  940. }
  941. }
  942. /**
  943. * Use these TIFF options for output image.
  944. *
  945. * The `density` can be set in pixels/inch via {@link #withmetadata withMetadata}
  946. * instead of providing `xres` and `yres` in pixels/mm.
  947. *
  948. * @example
  949. * // Convert SVG input to LZW-compressed, 1 bit per pixel TIFF output
  950. * sharp('input.svg')
  951. * .tiff({
  952. * compression: 'lzw',
  953. * bitdepth: 1
  954. * })
  955. * .toFile('1-bpp-output.tiff')
  956. * .then(info => { ... });
  957. *
  958. * @param {Object} [options] - output options
  959. * @param {number} [options.quality=80] - quality, integer 1-100
  960. * @param {boolean} [options.force=true] - force TIFF output, otherwise attempt to use input format
  961. * @param {string} [options.compression='jpeg'] - compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k
  962. * @param {boolean} [options.bigtiff=false] - use BigTIFF variant (has no effect when compression is none)
  963. * @param {string} [options.predictor='horizontal'] - compression predictor options: none, horizontal, float
  964. * @param {boolean} [options.pyramid=false] - write an image pyramid
  965. * @param {boolean} [options.tile=false] - write a tiled tiff
  966. * @param {number} [options.tileWidth=256] - horizontal tile size
  967. * @param {number} [options.tileHeight=256] - vertical tile size
  968. * @param {number} [options.xres=1.0] - horizontal resolution in pixels/mm
  969. * @param {number} [options.yres=1.0] - vertical resolution in pixels/mm
  970. * @param {string} [options.resolutionUnit='inch'] - resolution unit options: inch, cm
  971. * @param {number} [options.bitdepth=8] - reduce bitdepth to 1, 2 or 4 bit
  972. * @param {boolean} [options.miniswhite=false] - write 1-bit images as miniswhite
  973. * @returns {Sharp}
  974. * @throws {Error} Invalid options
  975. */
  976. function tiff (options) {
  977. if (is.object(options)) {
  978. if (is.defined(options.quality)) {
  979. if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {
  980. this.options.tiffQuality = options.quality;
  981. } else {
  982. throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);
  983. }
  984. }
  985. if (is.defined(options.bitdepth)) {
  986. if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [1, 2, 4, 8])) {
  987. this.options.tiffBitdepth = options.bitdepth;
  988. } else {
  989. throw is.invalidParameterError('bitdepth', '1, 2, 4 or 8', options.bitdepth);
  990. }
  991. }
  992. // tiling
  993. if (is.defined(options.tile)) {
  994. this._setBooleanOption('tiffTile', options.tile);
  995. }
  996. if (is.defined(options.tileWidth)) {
  997. if (is.integer(options.tileWidth) && options.tileWidth > 0) {
  998. this.options.tiffTileWidth = options.tileWidth;
  999. } else {
  1000. throw is.invalidParameterError('tileWidth', 'integer greater than zero', options.tileWidth);
  1001. }
  1002. }
  1003. if (is.defined(options.tileHeight)) {
  1004. if (is.integer(options.tileHeight) && options.tileHeight > 0) {
  1005. this.options.tiffTileHeight = options.tileHeight;
  1006. } else {
  1007. throw is.invalidParameterError('tileHeight', 'integer greater than zero', options.tileHeight);
  1008. }
  1009. }
  1010. // miniswhite
  1011. if (is.defined(options.miniswhite)) {
  1012. this._setBooleanOption('tiffMiniswhite', options.miniswhite);
  1013. }
  1014. // pyramid
  1015. if (is.defined(options.pyramid)) {
  1016. this._setBooleanOption('tiffPyramid', options.pyramid);
  1017. }
  1018. // resolution
  1019. if (is.defined(options.xres)) {
  1020. if (is.number(options.xres) && options.xres > 0) {
  1021. this.options.tiffXres = options.xres;
  1022. } else {
  1023. throw is.invalidParameterError('xres', 'number greater than zero', options.xres);
  1024. }
  1025. }
  1026. if (is.defined(options.yres)) {
  1027. if (is.number(options.yres) && options.yres > 0) {
  1028. this.options.tiffYres = options.yres;
  1029. } else {
  1030. throw is.invalidParameterError('yres', 'number greater than zero', options.yres);
  1031. }
  1032. }
  1033. // compression
  1034. if (is.defined(options.compression)) {
  1035. if (is.string(options.compression) && is.inArray(options.compression, ['none', 'jpeg', 'deflate', 'packbits', 'ccittfax4', 'lzw', 'webp', 'zstd', 'jp2k'])) {
  1036. this.options.tiffCompression = options.compression;
  1037. } else {
  1038. throw is.invalidParameterError('compression', 'one of: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k', options.compression);
  1039. }
  1040. }
  1041. // bigtiff
  1042. if (is.defined(options.bigtiff)) {
  1043. this._setBooleanOption('tiffBigtiff', options.bigtiff);
  1044. }
  1045. // predictor
  1046. if (is.defined(options.predictor)) {
  1047. if (is.string(options.predictor) && is.inArray(options.predictor, ['none', 'horizontal', 'float'])) {
  1048. this.options.tiffPredictor = options.predictor;
  1049. } else {
  1050. throw is.invalidParameterError('predictor', 'one of: none, horizontal, float', options.predictor);
  1051. }
  1052. }
  1053. // resolutionUnit
  1054. if (is.defined(options.resolutionUnit)) {
  1055. if (is.string(options.resolutionUnit) && is.inArray(options.resolutionUnit, ['inch', 'cm'])) {
  1056. this.options.tiffResolutionUnit = options.resolutionUnit;
  1057. } else {
  1058. throw is.invalidParameterError('resolutionUnit', 'one of: inch, cm', options.resolutionUnit);
  1059. }
  1060. }
  1061. }
  1062. return this._updateFormatOut('tiff', options);
  1063. }
  1064. /**
  1065. * Use these AVIF options for output image.
  1066. *
  1067. * AVIF image sequences are not supported.
  1068. * Prebuilt binaries support a bitdepth of 8 only.
  1069. *
  1070. * This feature is experimental on the Windows ARM64 platform
  1071. * and requires a CPU with ARM64v8.4 or later.
  1072. *
  1073. * @example
  1074. * const data = await sharp(input)
  1075. * .avif({ effort: 2 })
  1076. * .toBuffer();
  1077. *
  1078. * @example
  1079. * const data = await sharp(input)
  1080. * .avif({ lossless: true })
  1081. * .toBuffer();
  1082. *
  1083. * @since 0.27.0
  1084. *
  1085. * @param {Object} [options] - output options
  1086. * @param {number} [options.quality=50] - quality, integer 1-100
  1087. * @param {boolean} [options.lossless=false] - use lossless compression
  1088. * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest)
  1089. * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling
  1090. * @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit
  1091. * @returns {Sharp}
  1092. * @throws {Error} Invalid options
  1093. */
  1094. function avif (options) {
  1095. return this.heif({ ...options, compression: 'av1' });
  1096. }
  1097. /**
  1098. * Use these HEIF options for output image.
  1099. *
  1100. * Support for patent-encumbered HEIC images using `hevc` compression requires the use of a
  1101. * globally-installed libvips compiled with support for libheif, libde265 and x265.
  1102. *
  1103. * @example
  1104. * const data = await sharp(input)
  1105. * .heif({ compression: 'hevc' })
  1106. * .toBuffer();
  1107. *
  1108. * @since 0.23.0
  1109. *
  1110. * @param {Object} options - output options
  1111. * @param {string} options.compression - compression format: av1, hevc
  1112. * @param {number} [options.quality=50] - quality, integer 1-100
  1113. * @param {boolean} [options.lossless=false] - use lossless compression
  1114. * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest)
  1115. * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling
  1116. * @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit
  1117. * @returns {Sharp}
  1118. * @throws {Error} Invalid options
  1119. */
  1120. function heif (options) {
  1121. if (is.object(options)) {
  1122. if (is.string(options.compression) && is.inArray(options.compression, ['av1', 'hevc'])) {
  1123. this.options.heifCompression = options.compression;
  1124. } else {
  1125. throw is.invalidParameterError('compression', 'one of: av1, hevc', options.compression);
  1126. }
  1127. if (is.defined(options.quality)) {
  1128. if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {
  1129. this.options.heifQuality = options.quality;
  1130. } else {
  1131. throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);
  1132. }
  1133. }
  1134. if (is.defined(options.lossless)) {
  1135. if (is.bool(options.lossless)) {
  1136. this.options.heifLossless = options.lossless;
  1137. } else {
  1138. throw is.invalidParameterError('lossless', 'boolean', options.lossless);
  1139. }
  1140. }
  1141. if (is.defined(options.effort)) {
  1142. if (is.integer(options.effort) && is.inRange(options.effort, 0, 9)) {
  1143. this.options.heifEffort = options.effort;
  1144. } else {
  1145. throw is.invalidParameterError('effort', 'integer between 0 and 9', options.effort);
  1146. }
  1147. }
  1148. if (is.defined(options.chromaSubsampling)) {
  1149. if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) {
  1150. this.options.heifChromaSubsampling = options.chromaSubsampling;
  1151. } else {
  1152. throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);
  1153. }
  1154. }
  1155. if (is.defined(options.bitdepth)) {
  1156. if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [8, 10, 12])) {
  1157. if (options.bitdepth !== 8 && this.constructor.versions.heif) {
  1158. throw is.invalidParameterError('bitdepth when using prebuilt binaries', 8, options.bitdepth);
  1159. }
  1160. this.options.heifBitdepth = options.bitdepth;
  1161. } else {
  1162. throw is.invalidParameterError('bitdepth', '8, 10 or 12', options.bitdepth);
  1163. }
  1164. }
  1165. } else {
  1166. throw is.invalidParameterError('options', 'Object', options);
  1167. }
  1168. return this._updateFormatOut('heif', options);
  1169. }
  1170. /**
  1171. * Use these JPEG-XL (JXL) options for output image.
  1172. *
  1173. * This feature is experimental, please do not use in production systems.
  1174. *
  1175. * Requires libvips compiled with support for libjxl.
  1176. * The prebuilt binaries do not include this - see
  1177. * {@link /install/#custom-libvips installing a custom libvips}.
  1178. *
  1179. * @since 0.31.3
  1180. *
  1181. * @param {Object} [options] - output options
  1182. * @param {number} [options.distance=1.0] - maximum encoding error, between 0 (highest quality) and 15 (lowest quality)
  1183. * @param {number} [options.quality] - calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified
  1184. * @param {number} [options.decodingTier=0] - target decode speed tier, between 0 (highest quality) and 4 (lowest quality)
  1185. * @param {boolean} [options.lossless=false] - use lossless compression
  1186. * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 9 (slowest)
  1187. * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation
  1188. * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)
  1189. * @returns {Sharp}
  1190. * @throws {Error} Invalid options
  1191. */
  1192. function jxl (options) {
  1193. if (is.object(options)) {
  1194. if (is.defined(options.quality)) {
  1195. if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {
  1196. // https://github.com/libjxl/libjxl/blob/0aeea7f180bafd6893c1db8072dcb67d2aa5b03d/tools/cjxl_main.cc#L640-L644
  1197. this.options.jxlDistance = options.quality >= 30
  1198. ? 0.1 + (100 - options.quality) * 0.09
  1199. : 53 / 3000 * options.quality * options.quality - 23 / 20 * options.quality + 25;
  1200. } else {
  1201. throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);
  1202. }
  1203. } else if (is.defined(options.distance)) {
  1204. if (is.number(options.distance) && is.inRange(options.distance, 0, 15)) {
  1205. this.options.jxlDistance = options.distance;
  1206. } else {
  1207. throw is.invalidParameterError('distance', 'number between 0.0 and 15.0', options.distance);
  1208. }
  1209. }
  1210. if (is.defined(options.decodingTier)) {
  1211. if (is.integer(options.decodingTier) && is.inRange(options.decodingTier, 0, 4)) {
  1212. this.options.jxlDecodingTier = options.decodingTier;
  1213. } else {
  1214. throw is.invalidParameterError('decodingTier', 'integer between 0 and 4', options.decodingTier);
  1215. }
  1216. }
  1217. if (is.defined(options.lossless)) {
  1218. if (is.bool(options.lossless)) {
  1219. this.options.jxlLossless = options.lossless;
  1220. } else {
  1221. throw is.invalidParameterError('lossless', 'boolean', options.lossless);
  1222. }
  1223. }
  1224. if (is.defined(options.effort)) {
  1225. if (is.integer(options.effort) && is.inRange(options.effort, 1, 9)) {
  1226. this.options.jxlEffort = options.effort;
  1227. } else {
  1228. throw is.invalidParameterError('effort', 'integer between 1 and 9', options.effort);
  1229. }
  1230. }
  1231. }
  1232. trySetAnimationOptions(options, this.options);
  1233. return this._updateFormatOut('jxl', options);
  1234. }
  1235. /**
  1236. * Force output to be raw, uncompressed pixel data.
  1237. * Pixel ordering is left-to-right, top-to-bottom, without padding.
  1238. * Channel ordering will be RGB or RGBA for non-greyscale colourspaces.
  1239. *
  1240. * @example
  1241. * // Extract raw, unsigned 8-bit RGB pixel data from JPEG input
  1242. * const { data, info } = await sharp('input.jpg')
  1243. * .raw()
  1244. * .toBuffer({ resolveWithObject: true });
  1245. *
  1246. * @example
  1247. * // Extract alpha channel as raw, unsigned 16-bit pixel data from PNG input
  1248. * const data = await sharp('input.png')
  1249. * .ensureAlpha()
  1250. * .extractChannel(3)
  1251. * .toColourspace('b-w')
  1252. * .raw({ depth: 'ushort' })
  1253. * .toBuffer();
  1254. *
  1255. * @param {Object} [options] - output options
  1256. * @param {string} [options.depth='uchar'] - bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex
  1257. * @returns {Sharp}
  1258. * @throws {Error} Invalid options
  1259. */
  1260. function raw (options) {
  1261. if (is.object(options)) {
  1262. if (is.defined(options.depth)) {
  1263. if (is.string(options.depth) && is.inArray(options.depth,
  1264. ['char', 'uchar', 'short', 'ushort', 'int', 'uint', 'float', 'complex', 'double', 'dpcomplex']
  1265. )) {
  1266. this.options.rawDepth = options.depth;
  1267. } else {
  1268. throw is.invalidParameterError('depth', 'one of: char, uchar, short, ushort, int, uint, float, complex, double, dpcomplex', options.depth);
  1269. }
  1270. }
  1271. }
  1272. return this._updateFormatOut('raw');
  1273. }
  1274. /**
  1275. * Use tile-based deep zoom (image pyramid) output.
  1276. *
  1277. * Set the format and options for tile images via the `toFormat`, `jpeg`, `png` or `webp` functions.
  1278. * Use a `.zip` or `.szi` file extension with `toFile` to write to a compressed archive file format.
  1279. *
  1280. * The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`.
  1281. *
  1282. * @example
  1283. * sharp('input.tiff')
  1284. * .png()
  1285. * .tile({
  1286. * size: 512
  1287. * })
  1288. * .toFile('output.dz', function(err, info) {
  1289. * // output.dzi is the Deep Zoom XML definition
  1290. * // output_files contains 512x512 tiles grouped by zoom level
  1291. * });
  1292. *
  1293. * @example
  1294. * const zipFileWithTiles = await sharp(input)
  1295. * .tile({ basename: "tiles" })
  1296. * .toBuffer();
  1297. *
  1298. * @example
  1299. * const iiififier = sharp().tile({ layout: "iiif" });
  1300. * readableStream
  1301. * .pipe(iiififier)
  1302. * .pipe(writeableStream);
  1303. *
  1304. * @param {Object} [options]
  1305. * @param {number} [options.size=256] tile size in pixels, a value between 1 and 8192.
  1306. * @param {number} [options.overlap=0] tile overlap in pixels, a value between 0 and 8192.
  1307. * @param {number} [options.angle=0] tile angle of rotation, must be a multiple of 90.
  1308. * @param {string|Object} [options.background={r: 255, g: 255, b: 255, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to white without transparency.
  1309. * @param {string} [options.depth] how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout.
  1310. * @param {number} [options.skipBlanks=-1] Threshold to skip tile generation. Range is 0-255 for 8-bit images, 0-65535 for 16-bit images. Default is 5 for `google` layout, -1 (no skip) otherwise.
  1311. * @param {string} [options.container='fs'] tile container, with value `fs` (filesystem) or `zip` (compressed file).
  1312. * @param {string} [options.layout='dz'] filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`.
  1313. * @param {boolean} [options.centre=false] centre image in tile.
  1314. * @param {boolean} [options.center=false] alternative spelling of centre.
  1315. * @param {string} [options.id='https://example.com/iiif'] when `layout` is `iiif`/`iiif3`, sets the `@id`/`id` attribute of `info.json`
  1316. * @param {string} [options.basename] the name of the directory within the zip file when container is `zip`.
  1317. * @returns {Sharp}
  1318. * @throws {Error} Invalid parameters
  1319. */
  1320. function tile (options) {
  1321. if (is.object(options)) {
  1322. // Size of square tiles, in pixels
  1323. if (is.defined(options.size)) {
  1324. if (is.integer(options.size) && is.inRange(options.size, 1, 8192)) {
  1325. this.options.tileSize = options.size;
  1326. } else {
  1327. throw is.invalidParameterError('size', 'integer between 1 and 8192', options.size);
  1328. }
  1329. }
  1330. // Overlap of tiles, in pixels
  1331. if (is.defined(options.overlap)) {
  1332. if (is.integer(options.overlap) && is.inRange(options.overlap, 0, 8192)) {
  1333. if (options.overlap > this.options.tileSize) {
  1334. throw is.invalidParameterError('overlap', `<= size (${this.options.tileSize})`, options.overlap);
  1335. }
  1336. this.options.tileOverlap = options.overlap;
  1337. } else {
  1338. throw is.invalidParameterError('overlap', 'integer between 0 and 8192', options.overlap);
  1339. }
  1340. }
  1341. // Container
  1342. if (is.defined(options.container)) {
  1343. if (is.string(options.container) && is.inArray(options.container, ['fs', 'zip'])) {
  1344. this.options.tileContainer = options.container;
  1345. } else {
  1346. throw is.invalidParameterError('container', 'one of: fs, zip', options.container);
  1347. }
  1348. }
  1349. // Layout
  1350. if (is.defined(options.layout)) {
  1351. if (is.string(options.layout) && is.inArray(options.layout, ['dz', 'google', 'iiif', 'iiif3', 'zoomify'])) {
  1352. this.options.tileLayout = options.layout;
  1353. } else {
  1354. throw is.invalidParameterError('layout', 'one of: dz, google, iiif, iiif3, zoomify', options.layout);
  1355. }
  1356. }
  1357. // Angle of rotation,
  1358. if (is.defined(options.angle)) {
  1359. if (is.integer(options.angle) && !(options.angle % 90)) {
  1360. this.options.tileAngle = options.angle;
  1361. } else {
  1362. throw is.invalidParameterError('angle', 'positive/negative multiple of 90', options.angle);
  1363. }
  1364. }
  1365. // Background colour
  1366. this._setBackgroundColourOption('tileBackground', options.background);
  1367. // Depth of tiles
  1368. if (is.defined(options.depth)) {
  1369. if (is.string(options.depth) && is.inArray(options.depth, ['onepixel', 'onetile', 'one'])) {
  1370. this.options.tileDepth = options.depth;
  1371. } else {
  1372. throw is.invalidParameterError('depth', 'one of: onepixel, onetile, one', options.depth);
  1373. }
  1374. }
  1375. // Threshold to skip blank tiles
  1376. if (is.defined(options.skipBlanks)) {
  1377. if (is.integer(options.skipBlanks) && is.inRange(options.skipBlanks, -1, 65535)) {
  1378. this.options.tileSkipBlanks = options.skipBlanks;
  1379. } else {
  1380. throw is.invalidParameterError('skipBlanks', 'integer between -1 and 255/65535', options.skipBlanks);
  1381. }
  1382. } else if (is.defined(options.layout) && options.layout === 'google') {
  1383. this.options.tileSkipBlanks = 5;
  1384. }
  1385. // Center image in tile
  1386. const centre = is.bool(options.center) ? options.center : options.centre;
  1387. if (is.defined(centre)) {
  1388. this._setBooleanOption('tileCentre', centre);
  1389. }
  1390. // @id attribute for IIIF layout
  1391. if (is.defined(options.id)) {
  1392. if (is.string(options.id)) {
  1393. this.options.tileId = options.id;
  1394. } else {
  1395. throw is.invalidParameterError('id', 'string', options.id);
  1396. }
  1397. }
  1398. // Basename for zip container
  1399. if (is.defined(options.basename)) {
  1400. if (is.string(options.basename)) {
  1401. this.options.tileBasename = options.basename;
  1402. } else {
  1403. throw is.invalidParameterError('basename', 'string', options.basename);
  1404. }
  1405. }
  1406. }
  1407. // Format
  1408. if (is.inArray(this.options.formatOut, ['jpeg', 'png', 'webp'])) {
  1409. this.options.tileFormat = this.options.formatOut;
  1410. } else if (this.options.formatOut !== 'input') {
  1411. throw is.invalidParameterError('format', 'one of: jpeg, png, webp', this.options.formatOut);
  1412. }
  1413. return this._updateFormatOut('dz');
  1414. }
  1415. /**
  1416. * Set a timeout for processing, in seconds.
  1417. * Use a value of zero to continue processing indefinitely, the default behaviour.
  1418. *
  1419. * The clock starts when libvips opens an input image for processing.
  1420. * Time spent waiting for a libuv thread to become available is not included.
  1421. *
  1422. * @example
  1423. * // Ensure processing takes no longer than 3 seconds
  1424. * try {
  1425. * const data = await sharp(input)
  1426. * .blur(1000)
  1427. * .timeout({ seconds: 3 })
  1428. * .toBuffer();
  1429. * } catch (err) {
  1430. * if (err.message.includes('timeout')) { ... }
  1431. * }
  1432. *
  1433. * @since 0.29.2
  1434. *
  1435. * @param {Object} options
  1436. * @param {number} options.seconds - Number of seconds after which processing will be stopped
  1437. * @returns {Sharp}
  1438. */
  1439. function timeout (options) {
  1440. if (!is.plainObject(options)) {
  1441. throw is.invalidParameterError('options', 'object', options);
  1442. }
  1443. if (is.integer(options.seconds) && is.inRange(options.seconds, 0, 3600)) {
  1444. this.options.timeoutSeconds = options.seconds;
  1445. } else {
  1446. throw is.invalidParameterError('seconds', 'integer between 0 and 3600', options.seconds);
  1447. }
  1448. return this;
  1449. }
  1450. /**
  1451. * Update the output format unless options.force is false,
  1452. * in which case revert to input format.
  1453. * @private
  1454. * @param {string} formatOut
  1455. * @param {Object} [options]
  1456. * @param {boolean} [options.force=true] - force output format, otherwise attempt to use input format
  1457. * @returns {Sharp}
  1458. */
  1459. function _updateFormatOut (formatOut, options) {
  1460. if (!(is.object(options) && options.force === false)) {
  1461. this.options.formatOut = formatOut;
  1462. }
  1463. return this;
  1464. }
  1465. /**
  1466. * Update a boolean attribute of the this.options Object.
  1467. * @private
  1468. * @param {string} key
  1469. * @param {boolean} val
  1470. * @throws {Error} Invalid key
  1471. */
  1472. function _setBooleanOption (key, val) {
  1473. if (is.bool(val)) {
  1474. this.options[key] = val;
  1475. } else {
  1476. throw is.invalidParameterError(key, 'boolean', val);
  1477. }
  1478. }
  1479. /**
  1480. * Called by a WriteableStream to notify us it is ready for data.
  1481. * @private
  1482. */
  1483. function _read () {
  1484. if (!this.options.streamOut) {
  1485. this.options.streamOut = true;
  1486. const stack = Error();
  1487. this._pipeline(undefined, stack);
  1488. }
  1489. }
  1490. /**
  1491. * Invoke the C++ image processing pipeline
  1492. * Supports callback, stream and promise variants
  1493. * @private
  1494. */
  1495. function _pipeline (callback, stack) {
  1496. if (typeof callback === 'function') {
  1497. // output=file/buffer
  1498. if (this._isStreamInput()) {
  1499. // output=file/buffer, input=stream
  1500. this.on('finish', () => {
  1501. this._flattenBufferIn();
  1502. sharp.pipeline(this.options, (err, data, info) => {
  1503. if (err) {
  1504. callback(is.nativeError(err, stack));
  1505. } else {
  1506. callback(null, data, info);
  1507. }
  1508. });
  1509. });
  1510. } else {
  1511. // output=file/buffer, input=file/buffer
  1512. sharp.pipeline(this.options, (err, data, info) => {
  1513. if (err) {
  1514. callback(is.nativeError(err, stack));
  1515. } else {
  1516. callback(null, data, info);
  1517. }
  1518. });
  1519. }
  1520. return this;
  1521. } else if (this.options.streamOut) {
  1522. // output=stream
  1523. if (this._isStreamInput()) {
  1524. // output=stream, input=stream
  1525. this.once('finish', () => {
  1526. this._flattenBufferIn();
  1527. sharp.pipeline(this.options, (err, data, info) => {
  1528. if (err) {
  1529. this.emit('error', is.nativeError(err, stack));
  1530. } else {
  1531. this.emit('info', info);
  1532. this.push(data);
  1533. }
  1534. this.push(null);
  1535. this.on('end', () => this.emit('close'));
  1536. });
  1537. });
  1538. if (this.streamInFinished) {
  1539. this.emit('finish');
  1540. }
  1541. } else {
  1542. // output=stream, input=file/buffer
  1543. sharp.pipeline(this.options, (err, data, info) => {
  1544. if (err) {
  1545. this.emit('error', is.nativeError(err, stack));
  1546. } else {
  1547. this.emit('info', info);
  1548. this.push(data);
  1549. }
  1550. this.push(null);
  1551. this.on('end', () => this.emit('close'));
  1552. });
  1553. }
  1554. return this;
  1555. } else {
  1556. // output=promise
  1557. if (this._isStreamInput()) {
  1558. // output=promise, input=stream
  1559. return new Promise((resolve, reject) => {
  1560. this.once('finish', () => {
  1561. this._flattenBufferIn();
  1562. sharp.pipeline(this.options, (err, data, info) => {
  1563. if (err) {
  1564. reject(is.nativeError(err, stack));
  1565. } else {
  1566. if (this.options.resolveWithObject) {
  1567. resolve({ data, info });
  1568. } else {
  1569. resolve(data);
  1570. }
  1571. }
  1572. });
  1573. });
  1574. });
  1575. } else {
  1576. // output=promise, input=file/buffer
  1577. return new Promise((resolve, reject) => {
  1578. sharp.pipeline(this.options, (err, data, info) => {
  1579. if (err) {
  1580. reject(is.nativeError(err, stack));
  1581. } else {
  1582. if (this.options.resolveWithObject) {
  1583. resolve({ data, info });
  1584. } else {
  1585. resolve(data);
  1586. }
  1587. }
  1588. });
  1589. });
  1590. }
  1591. }
  1592. }
  1593. /**
  1594. * Decorate the Sharp prototype with output-related functions.
  1595. * @module Sharp
  1596. * @private
  1597. */
  1598. module.exports = (Sharp) => {
  1599. Object.assign(Sharp.prototype, {
  1600. // Public
  1601. toFile,
  1602. toBuffer,
  1603. keepExif,
  1604. withExif,
  1605. withExifMerge,
  1606. keepIccProfile,
  1607. withIccProfile,
  1608. keepXmp,
  1609. withXmp,
  1610. keepMetadata,
  1611. withMetadata,
  1612. toFormat,
  1613. jpeg,
  1614. jp2,
  1615. png,
  1616. webp,
  1617. tiff,
  1618. avif,
  1619. heif,
  1620. jxl,
  1621. gif,
  1622. raw,
  1623. tile,
  1624. timeout,
  1625. // Private
  1626. _updateFormatOut,
  1627. _setBooleanOption,
  1628. _read,
  1629. _pipeline
  1630. });
  1631. };