operation.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  1. // Copyright 2013 Lovell Fuller and others.
  2. // SPDX-License-Identifier: Apache-2.0
  3. 'use strict';
  4. const color = require('color');
  5. const is = require('./is');
  6. /**
  7. * Rotate the output image by either an explicit angle
  8. * or auto-orient based on the EXIF `Orientation` tag.
  9. *
  10. * If an angle is provided, it is converted to a valid positive degree rotation.
  11. * For example, `-450` will produce a 270 degree rotation.
  12. *
  13. * When rotating by an angle other than a multiple of 90,
  14. * the background colour can be provided with the `background` option.
  15. *
  16. * If no angle is provided, it is determined from the EXIF data.
  17. * Mirroring is supported and may infer the use of a flip operation.
  18. *
  19. * The use of `rotate` without an angle will remove the EXIF `Orientation` tag, if any.
  20. *
  21. * Only one rotation can occur per pipeline.
  22. * Previous calls to `rotate` in the same pipeline will be ignored.
  23. *
  24. * Method order is important when rotating, resizing and/or extracting regions,
  25. * for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.
  26. *
  27. * @example
  28. * const pipeline = sharp()
  29. * .rotate()
  30. * .resize(null, 200)
  31. * .toBuffer(function (err, outputBuffer, info) {
  32. * // outputBuffer contains 200px high JPEG image data,
  33. * // auto-rotated using EXIF Orientation tag
  34. * // info.width and info.height contain the dimensions of the resized image
  35. * });
  36. * readableStream.pipe(pipeline);
  37. *
  38. * @example
  39. * const rotateThenResize = await sharp(input)
  40. * .rotate(90)
  41. * .resize({ width: 16, height: 8, fit: 'fill' })
  42. * .toBuffer();
  43. * const resizeThenRotate = await sharp(input)
  44. * .resize({ width: 16, height: 8, fit: 'fill' })
  45. * .rotate(90)
  46. * .toBuffer();
  47. *
  48. * @param {number} [angle=auto] angle of rotation.
  49. * @param {Object} [options] - if present, is an Object with optional attributes.
  50. * @param {string|Object} [options.background="#000000"] parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
  51. * @returns {Sharp}
  52. * @throws {Error} Invalid parameters
  53. */
  54. function rotate (angle, options) {
  55. if (this.options.useExifOrientation || this.options.angle || this.options.rotationAngle) {
  56. this.options.debuglog('ignoring previous rotate options');
  57. }
  58. if (!is.defined(angle)) {
  59. this.options.useExifOrientation = true;
  60. } else if (is.integer(angle) && !(angle % 90)) {
  61. this.options.angle = angle;
  62. } else if (is.number(angle)) {
  63. this.options.rotationAngle = angle;
  64. if (is.object(options) && options.background) {
  65. const backgroundColour = color(options.background);
  66. this.options.rotationBackground = [
  67. backgroundColour.red(),
  68. backgroundColour.green(),
  69. backgroundColour.blue(),
  70. Math.round(backgroundColour.alpha() * 255)
  71. ];
  72. }
  73. } else {
  74. throw is.invalidParameterError('angle', 'numeric', angle);
  75. }
  76. return this;
  77. }
  78. /**
  79. * Mirror the image vertically (up-down) about the x-axis.
  80. * This always occurs before rotation, if any.
  81. *
  82. * This operation does not work correctly with multi-page images.
  83. *
  84. * @example
  85. * const output = await sharp(input).flip().toBuffer();
  86. *
  87. * @param {Boolean} [flip=true]
  88. * @returns {Sharp}
  89. */
  90. function flip (flip) {
  91. this.options.flip = is.bool(flip) ? flip : true;
  92. return this;
  93. }
  94. /**
  95. * Mirror the image horizontally (left-right) about the y-axis.
  96. * This always occurs before rotation, if any.
  97. *
  98. * @example
  99. * const output = await sharp(input).flop().toBuffer();
  100. *
  101. * @param {Boolean} [flop=true]
  102. * @returns {Sharp}
  103. */
  104. function flop (flop) {
  105. this.options.flop = is.bool(flop) ? flop : true;
  106. return this;
  107. }
  108. /**
  109. * Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.
  110. *
  111. * You must provide an array of length 4 or a 2x2 affine transformation matrix.
  112. * By default, new pixels are filled with a black background. You can provide a background color with the `background` option.
  113. * A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`.
  114. *
  115. * In the case of a 2x2 matrix, the transform is:
  116. * - X = `matrix[0, 0]` \* (x + `idx`) + `matrix[0, 1]` \* (y + `idy`) + `odx`
  117. * - Y = `matrix[1, 0]` \* (x + `idx`) + `matrix[1, 1]` \* (y + `idy`) + `ody`
  118. *
  119. * where:
  120. * - x and y are the coordinates in input image.
  121. * - X and Y are the coordinates in output image.
  122. * - (0,0) is the upper left corner.
  123. *
  124. * @since 0.27.0
  125. *
  126. * @example
  127. * const pipeline = sharp()
  128. * .affine([[1, 0.3], [0.1, 0.7]], {
  129. * background: 'white',
  130. * interpolator: sharp.interpolators.nohalo
  131. * })
  132. * .toBuffer((err, outputBuffer, info) => {
  133. * // outputBuffer contains the transformed image
  134. * // info.width and info.height contain the new dimensions
  135. * });
  136. *
  137. * inputStream
  138. * .pipe(pipeline);
  139. *
  140. * @param {Array<Array<number>>|Array<number>} matrix - affine transformation matrix
  141. * @param {Object} [options] - if present, is an Object with optional attributes.
  142. * @param {String|Object} [options.background="#000000"] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
  143. * @param {Number} [options.idx=0] - input horizontal offset
  144. * @param {Number} [options.idy=0] - input vertical offset
  145. * @param {Number} [options.odx=0] - output horizontal offset
  146. * @param {Number} [options.ody=0] - output vertical offset
  147. * @param {String} [options.interpolator=sharp.interpolators.bicubic] - interpolator
  148. * @returns {Sharp}
  149. * @throws {Error} Invalid parameters
  150. */
  151. function affine (matrix, options) {
  152. const flatMatrix = [].concat(...matrix);
  153. if (flatMatrix.length === 4 && flatMatrix.every(is.number)) {
  154. this.options.affineMatrix = flatMatrix;
  155. } else {
  156. throw is.invalidParameterError('matrix', '1x4 or 2x2 array', matrix);
  157. }
  158. if (is.defined(options)) {
  159. if (is.object(options)) {
  160. this._setBackgroundColourOption('affineBackground', options.background);
  161. if (is.defined(options.idx)) {
  162. if (is.number(options.idx)) {
  163. this.options.affineIdx = options.idx;
  164. } else {
  165. throw is.invalidParameterError('options.idx', 'number', options.idx);
  166. }
  167. }
  168. if (is.defined(options.idy)) {
  169. if (is.number(options.idy)) {
  170. this.options.affineIdy = options.idy;
  171. } else {
  172. throw is.invalidParameterError('options.idy', 'number', options.idy);
  173. }
  174. }
  175. if (is.defined(options.odx)) {
  176. if (is.number(options.odx)) {
  177. this.options.affineOdx = options.odx;
  178. } else {
  179. throw is.invalidParameterError('options.odx', 'number', options.odx);
  180. }
  181. }
  182. if (is.defined(options.ody)) {
  183. if (is.number(options.ody)) {
  184. this.options.affineOdy = options.ody;
  185. } else {
  186. throw is.invalidParameterError('options.ody', 'number', options.ody);
  187. }
  188. }
  189. if (is.defined(options.interpolator)) {
  190. if (is.inArray(options.interpolator, Object.values(this.constructor.interpolators))) {
  191. this.options.affineInterpolator = options.interpolator;
  192. } else {
  193. throw is.invalidParameterError('options.interpolator', 'valid interpolator name', options.interpolator);
  194. }
  195. }
  196. } else {
  197. throw is.invalidParameterError('options', 'object', options);
  198. }
  199. }
  200. return this;
  201. }
  202. /**
  203. * Sharpen the image.
  204. *
  205. * When used without parameters, performs a fast, mild sharpen of the output image.
  206. *
  207. * When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space.
  208. * Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available.
  209. *
  210. * See {@link https://www.libvips.org/API/current/libvips-convolution.html#vips-sharpen|libvips sharpen} operation.
  211. *
  212. * @example
  213. * const data = await sharp(input).sharpen().toBuffer();
  214. *
  215. * @example
  216. * const data = await sharp(input).sharpen({ sigma: 2 }).toBuffer();
  217. *
  218. * @example
  219. * const data = await sharp(input)
  220. * .sharpen({
  221. * sigma: 2,
  222. * m1: 0,
  223. * m2: 3,
  224. * x1: 3,
  225. * y2: 15,
  226. * y3: 15,
  227. * })
  228. * .toBuffer();
  229. *
  230. * @param {Object|number} [options] - if present, is an Object with attributes
  231. * @param {number} [options.sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`, between 0.000001 and 10
  232. * @param {number} [options.m1=1.0] - the level of sharpening to apply to "flat" areas, between 0 and 1000000
  233. * @param {number} [options.m2=2.0] - the level of sharpening to apply to "jagged" areas, between 0 and 1000000
  234. * @param {number} [options.x1=2.0] - threshold between "flat" and "jagged", between 0 and 1000000
  235. * @param {number} [options.y2=10.0] - maximum amount of brightening, between 0 and 1000000
  236. * @param {number} [options.y3=20.0] - maximum amount of darkening, between 0 and 1000000
  237. * @param {number} [flat] - (deprecated) see `options.m1`.
  238. * @param {number} [jagged] - (deprecated) see `options.m2`.
  239. * @returns {Sharp}
  240. * @throws {Error} Invalid parameters
  241. */
  242. function sharpen (options, flat, jagged) {
  243. if (!is.defined(options)) {
  244. // No arguments: default to mild sharpen
  245. this.options.sharpenSigma = -1;
  246. } else if (is.bool(options)) {
  247. // Deprecated boolean argument: apply mild sharpen?
  248. this.options.sharpenSigma = options ? -1 : 0;
  249. } else if (is.number(options) && is.inRange(options, 0.01, 10000)) {
  250. // Deprecated numeric argument: specific sigma
  251. this.options.sharpenSigma = options;
  252. // Deprecated control over flat areas
  253. if (is.defined(flat)) {
  254. if (is.number(flat) && is.inRange(flat, 0, 10000)) {
  255. this.options.sharpenM1 = flat;
  256. } else {
  257. throw is.invalidParameterError('flat', 'number between 0 and 10000', flat);
  258. }
  259. }
  260. // Deprecated control over jagged areas
  261. if (is.defined(jagged)) {
  262. if (is.number(jagged) && is.inRange(jagged, 0, 10000)) {
  263. this.options.sharpenM2 = jagged;
  264. } else {
  265. throw is.invalidParameterError('jagged', 'number between 0 and 10000', jagged);
  266. }
  267. }
  268. } else if (is.plainObject(options)) {
  269. if (is.number(options.sigma) && is.inRange(options.sigma, 0.000001, 10)) {
  270. this.options.sharpenSigma = options.sigma;
  271. } else {
  272. throw is.invalidParameterError('options.sigma', 'number between 0.000001 and 10', options.sigma);
  273. }
  274. if (is.defined(options.m1)) {
  275. if (is.number(options.m1) && is.inRange(options.m1, 0, 1000000)) {
  276. this.options.sharpenM1 = options.m1;
  277. } else {
  278. throw is.invalidParameterError('options.m1', 'number between 0 and 1000000', options.m1);
  279. }
  280. }
  281. if (is.defined(options.m2)) {
  282. if (is.number(options.m2) && is.inRange(options.m2, 0, 1000000)) {
  283. this.options.sharpenM2 = options.m2;
  284. } else {
  285. throw is.invalidParameterError('options.m2', 'number between 0 and 1000000', options.m2);
  286. }
  287. }
  288. if (is.defined(options.x1)) {
  289. if (is.number(options.x1) && is.inRange(options.x1, 0, 1000000)) {
  290. this.options.sharpenX1 = options.x1;
  291. } else {
  292. throw is.invalidParameterError('options.x1', 'number between 0 and 1000000', options.x1);
  293. }
  294. }
  295. if (is.defined(options.y2)) {
  296. if (is.number(options.y2) && is.inRange(options.y2, 0, 1000000)) {
  297. this.options.sharpenY2 = options.y2;
  298. } else {
  299. throw is.invalidParameterError('options.y2', 'number between 0 and 1000000', options.y2);
  300. }
  301. }
  302. if (is.defined(options.y3)) {
  303. if (is.number(options.y3) && is.inRange(options.y3, 0, 1000000)) {
  304. this.options.sharpenY3 = options.y3;
  305. } else {
  306. throw is.invalidParameterError('options.y3', 'number between 0 and 1000000', options.y3);
  307. }
  308. }
  309. } else {
  310. throw is.invalidParameterError('sigma', 'number between 0.01 and 10000', options);
  311. }
  312. return this;
  313. }
  314. /**
  315. * Apply median filter.
  316. * When used without parameters the default window is 3x3.
  317. *
  318. * @example
  319. * const output = await sharp(input).median().toBuffer();
  320. *
  321. * @example
  322. * const output = await sharp(input).median(5).toBuffer();
  323. *
  324. * @param {number} [size=3] square mask size: size x size
  325. * @returns {Sharp}
  326. * @throws {Error} Invalid parameters
  327. */
  328. function median (size) {
  329. if (!is.defined(size)) {
  330. // No arguments: default to 3x3
  331. this.options.medianSize = 3;
  332. } else if (is.integer(size) && is.inRange(size, 1, 1000)) {
  333. // Numeric argument: specific sigma
  334. this.options.medianSize = size;
  335. } else {
  336. throw is.invalidParameterError('size', 'integer between 1 and 1000', size);
  337. }
  338. return this;
  339. }
  340. /**
  341. * Blur the image.
  342. *
  343. * When used without parameters, performs a fast 3x3 box blur (equivalent to a box linear filter).
  344. *
  345. * When a `sigma` is provided, performs a slower, more accurate Gaussian blur.
  346. *
  347. * @example
  348. * const boxBlurred = await sharp(input)
  349. * .blur()
  350. * .toBuffer();
  351. *
  352. * @example
  353. * const gaussianBlurred = await sharp(input)
  354. * .blur(5)
  355. * .toBuffer();
  356. *
  357. * @param {number} [sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
  358. * @returns {Sharp}
  359. * @throws {Error} Invalid parameters
  360. */
  361. function blur (sigma) {
  362. if (!is.defined(sigma)) {
  363. // No arguments: default to mild blur
  364. this.options.blurSigma = -1;
  365. } else if (is.bool(sigma)) {
  366. // Boolean argument: apply mild blur?
  367. this.options.blurSigma = sigma ? -1 : 0;
  368. } else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) {
  369. // Numeric argument: specific sigma
  370. this.options.blurSigma = sigma;
  371. } else {
  372. throw is.invalidParameterError('sigma', 'number between 0.3 and 1000', sigma);
  373. }
  374. return this;
  375. }
  376. /**
  377. * Merge alpha transparency channel, if any, with a background, then remove the alpha channel.
  378. *
  379. * See also {@link /api-channel#removealpha|removeAlpha}.
  380. *
  381. * @example
  382. * await sharp(rgbaInput)
  383. * .flatten({ background: '#F0A703' })
  384. * .toBuffer();
  385. *
  386. * @param {Object} [options]
  387. * @param {string|Object} [options.background={r: 0, g: 0, b: 0}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black.
  388. * @returns {Sharp}
  389. */
  390. function flatten (options) {
  391. this.options.flatten = is.bool(options) ? options : true;
  392. if (is.object(options)) {
  393. this._setBackgroundColourOption('flattenBackground', options.background);
  394. }
  395. return this;
  396. }
  397. /**
  398. * Ensure the image has an alpha channel
  399. * with all white pixel values made fully transparent.
  400. *
  401. * Existing alpha channel values for non-white pixels remain unchanged.
  402. *
  403. * This feature is experimental and the API may change.
  404. *
  405. * @since 0.32.1
  406. *
  407. * @example
  408. * await sharp(rgbInput)
  409. * .unflatten()
  410. * .toBuffer();
  411. *
  412. * @example
  413. * await sharp(rgbInput)
  414. * .threshold(128, { grayscale: false }) // converter bright pixels to white
  415. * .unflatten()
  416. * .toBuffer();
  417. */
  418. function unflatten () {
  419. this.options.unflatten = true;
  420. return this;
  421. }
  422. /**
  423. * Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of `1/gamma`
  424. * then increasing the encoding (brighten) post-resize at a factor of `gamma`.
  425. * This can improve the perceived brightness of a resized image in non-linear colour spaces.
  426. * JPEG and WebP input images will not take advantage of the shrink-on-load performance optimisation
  427. * when applying a gamma correction.
  428. *
  429. * Supply a second argument to use a different output gamma value, otherwise the first value is used in both cases.
  430. *
  431. * @param {number} [gamma=2.2] value between 1.0 and 3.0.
  432. * @param {number} [gammaOut] value between 1.0 and 3.0. (optional, defaults to same as `gamma`)
  433. * @returns {Sharp}
  434. * @throws {Error} Invalid parameters
  435. */
  436. function gamma (gamma, gammaOut) {
  437. if (!is.defined(gamma)) {
  438. // Default gamma correction of 2.2 (sRGB)
  439. this.options.gamma = 2.2;
  440. } else if (is.number(gamma) && is.inRange(gamma, 1, 3)) {
  441. this.options.gamma = gamma;
  442. } else {
  443. throw is.invalidParameterError('gamma', 'number between 1.0 and 3.0', gamma);
  444. }
  445. if (!is.defined(gammaOut)) {
  446. // Default gamma correction for output is same as input
  447. this.options.gammaOut = this.options.gamma;
  448. } else if (is.number(gammaOut) && is.inRange(gammaOut, 1, 3)) {
  449. this.options.gammaOut = gammaOut;
  450. } else {
  451. throw is.invalidParameterError('gammaOut', 'number between 1.0 and 3.0', gammaOut);
  452. }
  453. return this;
  454. }
  455. /**
  456. * Produce the "negative" of the image.
  457. *
  458. * @example
  459. * const output = await sharp(input)
  460. * .negate()
  461. * .toBuffer();
  462. *
  463. * @example
  464. * const output = await sharp(input)
  465. * .negate({ alpha: false })
  466. * .toBuffer();
  467. *
  468. * @param {Object} [options]
  469. * @param {Boolean} [options.alpha=true] Whether or not to negate any alpha channel
  470. * @returns {Sharp}
  471. */
  472. function negate (options) {
  473. this.options.negate = is.bool(options) ? options : true;
  474. if (is.plainObject(options) && 'alpha' in options) {
  475. if (!is.bool(options.alpha)) {
  476. throw is.invalidParameterError('alpha', 'should be boolean value', options.alpha);
  477. } else {
  478. this.options.negateAlpha = options.alpha;
  479. }
  480. }
  481. return this;
  482. }
  483. /**
  484. * Enhance output image contrast by stretching its luminance to cover a full dynamic range.
  485. *
  486. * Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes.
  487. *
  488. * Luminance values below the `lower` percentile will be underexposed by clipping to zero.
  489. * Luminance values above the `upper` percentile will be overexposed by clipping to the max pixel value.
  490. *
  491. * @example
  492. * const output = await sharp(input)
  493. * .normalise()
  494. * .toBuffer();
  495. *
  496. * @example
  497. * const output = await sharp(input)
  498. * .normalise({ lower: 0, upper: 100 })
  499. * .toBuffer();
  500. *
  501. * @param {Object} [options]
  502. * @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed.
  503. * @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed.
  504. * @returns {Sharp}
  505. */
  506. function normalise (options) {
  507. if (is.plainObject(options)) {
  508. if (is.defined(options.lower)) {
  509. if (is.number(options.lower) && is.inRange(options.lower, 0, 99)) {
  510. this.options.normaliseLower = options.lower;
  511. } else {
  512. throw is.invalidParameterError('lower', 'number between 0 and 99', options.lower);
  513. }
  514. }
  515. if (is.defined(options.upper)) {
  516. if (is.number(options.upper) && is.inRange(options.upper, 1, 100)) {
  517. this.options.normaliseUpper = options.upper;
  518. } else {
  519. throw is.invalidParameterError('upper', 'number between 1 and 100', options.upper);
  520. }
  521. }
  522. }
  523. if (this.options.normaliseLower >= this.options.normaliseUpper) {
  524. throw is.invalidParameterError('range', 'lower to be less than upper',
  525. `${this.options.normaliseLower} >= ${this.options.normaliseUpper}`);
  526. }
  527. this.options.normalise = true;
  528. return this;
  529. }
  530. /**
  531. * Alternative spelling of normalise.
  532. *
  533. * @example
  534. * const output = await sharp(input)
  535. * .normalize()
  536. * .toBuffer();
  537. *
  538. * @param {Object} [options]
  539. * @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed.
  540. * @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed.
  541. * @returns {Sharp}
  542. */
  543. function normalize (options) {
  544. return this.normalise(options);
  545. }
  546. /**
  547. * Perform contrast limiting adaptive histogram equalization
  548. * {@link https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE|CLAHE}.
  549. *
  550. * This will, in general, enhance the clarity of the image by bringing out darker details.
  551. *
  552. * @since 0.28.3
  553. *
  554. * @example
  555. * const output = await sharp(input)
  556. * .clahe({
  557. * width: 3,
  558. * height: 3,
  559. * })
  560. * .toBuffer();
  561. *
  562. * @param {Object} options
  563. * @param {number} options.width - Integral width of the search window, in pixels.
  564. * @param {number} options.height - Integral height of the search window, in pixels.
  565. * @param {number} [options.maxSlope=3] - Integral level of brightening, between 0 and 100, where 0 disables contrast limiting.
  566. * @returns {Sharp}
  567. * @throws {Error} Invalid parameters
  568. */
  569. function clahe (options) {
  570. if (is.plainObject(options)) {
  571. if (is.integer(options.width) && options.width > 0) {
  572. this.options.claheWidth = options.width;
  573. } else {
  574. throw is.invalidParameterError('width', 'integer greater than zero', options.width);
  575. }
  576. if (is.integer(options.height) && options.height > 0) {
  577. this.options.claheHeight = options.height;
  578. } else {
  579. throw is.invalidParameterError('height', 'integer greater than zero', options.height);
  580. }
  581. if (is.defined(options.maxSlope)) {
  582. if (is.integer(options.maxSlope) && is.inRange(options.maxSlope, 0, 100)) {
  583. this.options.claheMaxSlope = options.maxSlope;
  584. } else {
  585. throw is.invalidParameterError('maxSlope', 'integer between 0 and 100', options.maxSlope);
  586. }
  587. }
  588. } else {
  589. throw is.invalidParameterError('options', 'plain object', options);
  590. }
  591. return this;
  592. }
  593. /**
  594. * Convolve the image with the specified kernel.
  595. *
  596. * @example
  597. * sharp(input)
  598. * .convolve({
  599. * width: 3,
  600. * height: 3,
  601. * kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1]
  602. * })
  603. * .raw()
  604. * .toBuffer(function(err, data, info) {
  605. * // data contains the raw pixel data representing the convolution
  606. * // of the input image with the horizontal Sobel operator
  607. * });
  608. *
  609. * @param {Object} kernel
  610. * @param {number} kernel.width - width of the kernel in pixels.
  611. * @param {number} kernel.height - height of the kernel in pixels.
  612. * @param {Array<number>} kernel.kernel - Array of length `width*height` containing the kernel values.
  613. * @param {number} [kernel.scale=sum] - the scale of the kernel in pixels.
  614. * @param {number} [kernel.offset=0] - the offset of the kernel in pixels.
  615. * @returns {Sharp}
  616. * @throws {Error} Invalid parameters
  617. */
  618. function convolve (kernel) {
  619. if (!is.object(kernel) || !Array.isArray(kernel.kernel) ||
  620. !is.integer(kernel.width) || !is.integer(kernel.height) ||
  621. !is.inRange(kernel.width, 3, 1001) || !is.inRange(kernel.height, 3, 1001) ||
  622. kernel.height * kernel.width !== kernel.kernel.length
  623. ) {
  624. // must pass in a kernel
  625. throw new Error('Invalid convolution kernel');
  626. }
  627. // Default scale is sum of kernel values
  628. if (!is.integer(kernel.scale)) {
  629. kernel.scale = kernel.kernel.reduce(function (a, b) {
  630. return a + b;
  631. }, 0);
  632. }
  633. // Clip scale to a minimum value of 1
  634. if (kernel.scale < 1) {
  635. kernel.scale = 1;
  636. }
  637. if (!is.integer(kernel.offset)) {
  638. kernel.offset = 0;
  639. }
  640. this.options.convKernel = kernel;
  641. return this;
  642. }
  643. /**
  644. * Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0.
  645. * @param {number} [threshold=128] - a value in the range 0-255 representing the level at which the threshold will be applied.
  646. * @param {Object} [options]
  647. * @param {Boolean} [options.greyscale=true] - convert to single channel greyscale.
  648. * @param {Boolean} [options.grayscale=true] - alternative spelling for greyscale.
  649. * @returns {Sharp}
  650. * @throws {Error} Invalid parameters
  651. */
  652. function threshold (threshold, options) {
  653. if (!is.defined(threshold)) {
  654. this.options.threshold = 128;
  655. } else if (is.bool(threshold)) {
  656. this.options.threshold = threshold ? 128 : 0;
  657. } else if (is.integer(threshold) && is.inRange(threshold, 0, 255)) {
  658. this.options.threshold = threshold;
  659. } else {
  660. throw is.invalidParameterError('threshold', 'integer between 0 and 255', threshold);
  661. }
  662. if (!is.object(options) || options.greyscale === true || options.grayscale === true) {
  663. this.options.thresholdGrayscale = true;
  664. } else {
  665. this.options.thresholdGrayscale = false;
  666. }
  667. return this;
  668. }
  669. /**
  670. * Perform a bitwise boolean operation with operand image.
  671. *
  672. * This operation creates an output image where each pixel is the result of
  673. * the selected bitwise boolean `operation` between the corresponding pixels of the input images.
  674. *
  675. * @param {Buffer|string} operand - Buffer containing image data or string containing the path to an image file.
  676. * @param {string} operator - one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.
  677. * @param {Object} [options]
  678. * @param {Object} [options.raw] - describes operand when using raw pixel data.
  679. * @param {number} [options.raw.width]
  680. * @param {number} [options.raw.height]
  681. * @param {number} [options.raw.channels]
  682. * @returns {Sharp}
  683. * @throws {Error} Invalid parameters
  684. */
  685. function boolean (operand, operator, options) {
  686. this.options.boolean = this._createInputDescriptor(operand, options);
  687. if (is.string(operator) && is.inArray(operator, ['and', 'or', 'eor'])) {
  688. this.options.booleanOp = operator;
  689. } else {
  690. throw is.invalidParameterError('operator', 'one of: and, or, eor', operator);
  691. }
  692. return this;
  693. }
  694. /**
  695. * Apply the linear formula `a` * input + `b` to the image to adjust image levels.
  696. *
  697. * When a single number is provided, it will be used for all image channels.
  698. * When an array of numbers is provided, the array length must match the number of channels.
  699. *
  700. * @example
  701. * await sharp(input)
  702. * .linear(0.5, 2)
  703. * .toBuffer();
  704. *
  705. * @example
  706. * await sharp(rgbInput)
  707. * .linear(
  708. * [0.25, 0.5, 0.75],
  709. * [150, 100, 50]
  710. * )
  711. * .toBuffer();
  712. *
  713. * @param {(number|number[])} [a=[]] multiplier
  714. * @param {(number|number[])} [b=[]] offset
  715. * @returns {Sharp}
  716. * @throws {Error} Invalid parameters
  717. */
  718. function linear (a, b) {
  719. if (!is.defined(a) && is.number(b)) {
  720. a = 1.0;
  721. } else if (is.number(a) && !is.defined(b)) {
  722. b = 0.0;
  723. }
  724. if (!is.defined(a)) {
  725. this.options.linearA = [];
  726. } else if (is.number(a)) {
  727. this.options.linearA = [a];
  728. } else if (Array.isArray(a) && a.length && a.every(is.number)) {
  729. this.options.linearA = a;
  730. } else {
  731. throw is.invalidParameterError('a', 'number or array of numbers', a);
  732. }
  733. if (!is.defined(b)) {
  734. this.options.linearB = [];
  735. } else if (is.number(b)) {
  736. this.options.linearB = [b];
  737. } else if (Array.isArray(b) && b.length && b.every(is.number)) {
  738. this.options.linearB = b;
  739. } else {
  740. throw is.invalidParameterError('b', 'number or array of numbers', b);
  741. }
  742. if (this.options.linearA.length !== this.options.linearB.length) {
  743. throw new Error('Expected a and b to be arrays of the same length');
  744. }
  745. return this;
  746. }
  747. /**
  748. * Recombine the image with the specified matrix.
  749. *
  750. * @since 0.21.1
  751. *
  752. * @example
  753. * sharp(input)
  754. * .recomb([
  755. * [0.3588, 0.7044, 0.1368],
  756. * [0.2990, 0.5870, 0.1140],
  757. * [0.2392, 0.4696, 0.0912],
  758. * ])
  759. * .raw()
  760. * .toBuffer(function(err, data, info) {
  761. * // data contains the raw pixel data after applying the matrix
  762. * // With this example input, a sepia filter has been applied
  763. * });
  764. *
  765. * @param {Array<Array<number>>} inputMatrix - 3x3 Recombination matrix
  766. * @returns {Sharp}
  767. * @throws {Error} Invalid parameters
  768. */
  769. function recomb (inputMatrix) {
  770. if (!Array.isArray(inputMatrix) || inputMatrix.length !== 3 ||
  771. inputMatrix[0].length !== 3 ||
  772. inputMatrix[1].length !== 3 ||
  773. inputMatrix[2].length !== 3
  774. ) {
  775. // must pass in a kernel
  776. throw new Error('Invalid recombination matrix');
  777. }
  778. this.options.recombMatrix = [
  779. inputMatrix[0][0], inputMatrix[0][1], inputMatrix[0][2],
  780. inputMatrix[1][0], inputMatrix[1][1], inputMatrix[1][2],
  781. inputMatrix[2][0], inputMatrix[2][1], inputMatrix[2][2]
  782. ].map(Number);
  783. return this;
  784. }
  785. /**
  786. * Transforms the image using brightness, saturation, hue rotation, and lightness.
  787. * Brightness and lightness both operate on luminance, with the difference being that
  788. * brightness is multiplicative whereas lightness is additive.
  789. *
  790. * @since 0.22.1
  791. *
  792. * @example
  793. * // increase brightness by a factor of 2
  794. * const output = await sharp(input)
  795. * .modulate({
  796. * brightness: 2
  797. * })
  798. * .toBuffer();
  799. *
  800. * @example
  801. * // hue-rotate by 180 degrees
  802. * const output = await sharp(input)
  803. * .modulate({
  804. * hue: 180
  805. * })
  806. * .toBuffer();
  807. *
  808. * @example
  809. * // increase lightness by +50
  810. * const output = await sharp(input)
  811. * .modulate({
  812. * lightness: 50
  813. * })
  814. * .toBuffer();
  815. *
  816. * @example
  817. * // decrease brightness and saturation while also hue-rotating by 90 degrees
  818. * const output = await sharp(input)
  819. * .modulate({
  820. * brightness: 0.5,
  821. * saturation: 0.5,
  822. * hue: 90,
  823. * })
  824. * .toBuffer();
  825. *
  826. * @param {Object} [options]
  827. * @param {number} [options.brightness] Brightness multiplier
  828. * @param {number} [options.saturation] Saturation multiplier
  829. * @param {number} [options.hue] Degrees for hue rotation
  830. * @param {number} [options.lightness] Lightness addend
  831. * @returns {Sharp}
  832. */
  833. function modulate (options) {
  834. if (!is.plainObject(options)) {
  835. throw is.invalidParameterError('options', 'plain object', options);
  836. }
  837. if ('brightness' in options) {
  838. if (is.number(options.brightness) && options.brightness >= 0) {
  839. this.options.brightness = options.brightness;
  840. } else {
  841. throw is.invalidParameterError('brightness', 'number above zero', options.brightness);
  842. }
  843. }
  844. if ('saturation' in options) {
  845. if (is.number(options.saturation) && options.saturation >= 0) {
  846. this.options.saturation = options.saturation;
  847. } else {
  848. throw is.invalidParameterError('saturation', 'number above zero', options.saturation);
  849. }
  850. }
  851. if ('hue' in options) {
  852. if (is.integer(options.hue)) {
  853. this.options.hue = options.hue % 360;
  854. } else {
  855. throw is.invalidParameterError('hue', 'number', options.hue);
  856. }
  857. }
  858. if ('lightness' in options) {
  859. if (is.number(options.lightness)) {
  860. this.options.lightness = options.lightness;
  861. } else {
  862. throw is.invalidParameterError('lightness', 'number', options.lightness);
  863. }
  864. }
  865. return this;
  866. }
  867. /**
  868. * Decorate the Sharp prototype with operation-related functions.
  869. * @private
  870. */
  871. module.exports = function (Sharp) {
  872. Object.assign(Sharp.prototype, {
  873. rotate,
  874. flip,
  875. flop,
  876. affine,
  877. sharpen,
  878. median,
  879. blur,
  880. flatten,
  881. unflatten,
  882. gamma,
  883. negate,
  884. normalise,
  885. normalize,
  886. clahe,
  887. convolve,
  888. threshold,
  889. boolean,
  890. linear,
  891. recomb,
  892. modulate
  893. });
  894. };