output.js 57 KB

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