operation.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. 'use strict';
  2. const color = require('color');
  3. const is = require('./is');
  4. /**
  5. * Rotate the output image by either an explicit angle
  6. * or auto-orient based on the EXIF `Orientation` tag.
  7. *
  8. * If an angle is provided, it is converted to a valid positive degree rotation.
  9. * For example, `-450` will produce a 270deg rotation.
  10. *
  11. * When rotating by an angle other than a multiple of 90,
  12. * the background colour can be provided with the `background` option.
  13. *
  14. * If no angle is provided, it is determined from the EXIF data.
  15. * Mirroring is supported and may infer the use of a flip operation.
  16. *
  17. * The use of `rotate` implies the removal of the EXIF `Orientation` tag, if any.
  18. *
  19. * Method order is important when both rotating and extracting regions,
  20. * for example `rotate(x).extract(y)` will produce a different result to `extract(y).rotate(x)`.
  21. *
  22. * @example
  23. * const pipeline = sharp()
  24. * .rotate()
  25. * .resize(null, 200)
  26. * .toBuffer(function (err, outputBuffer, info) {
  27. * // outputBuffer contains 200px high JPEG image data,
  28. * // auto-rotated using EXIF Orientation tag
  29. * // info.width and info.height contain the dimensions of the resized image
  30. * });
  31. * readableStream.pipe(pipeline);
  32. *
  33. * @param {number} [angle=auto] angle of rotation.
  34. * @param {Object} [options] - if present, is an Object with optional attributes.
  35. * @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.
  36. * @returns {Sharp}
  37. * @throws {Error} Invalid parameters
  38. */
  39. function rotate (angle, options) {
  40. if (!is.defined(angle)) {
  41. this.options.useExifOrientation = true;
  42. } else if (is.integer(angle) && !(angle % 90)) {
  43. this.options.angle = angle;
  44. } else if (is.number(angle)) {
  45. this.options.rotationAngle = angle;
  46. if (is.object(options) && options.background) {
  47. const backgroundColour = color(options.background);
  48. this.options.rotationBackground = [
  49. backgroundColour.red(),
  50. backgroundColour.green(),
  51. backgroundColour.blue(),
  52. Math.round(backgroundColour.alpha() * 255)
  53. ];
  54. }
  55. } else {
  56. throw is.invalidParameterError('angle', 'numeric', angle);
  57. }
  58. return this;
  59. }
  60. /**
  61. * Flip the image about the vertical Y axis. This always occurs after rotation, if any.
  62. * The use of `flip` implies the removal of the EXIF `Orientation` tag, if any.
  63. * @param {Boolean} [flip=true]
  64. * @returns {Sharp}
  65. */
  66. function flip (flip) {
  67. this.options.flip = is.bool(flip) ? flip : true;
  68. return this;
  69. }
  70. /**
  71. * Flop the image about the horizontal X axis. This always occurs after rotation, if any.
  72. * The use of `flop` implies the removal of the EXIF `Orientation` tag, if any.
  73. * @param {Boolean} [flop=true]
  74. * @returns {Sharp}
  75. */
  76. function flop (flop) {
  77. this.options.flop = is.bool(flop) ? flop : true;
  78. return this;
  79. }
  80. /**
  81. * Sharpen the image.
  82. * When used without parameters, performs a fast, mild sharpen of the output image.
  83. * When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space.
  84. * Separate control over the level of sharpening in "flat" and "jagged" areas is available.
  85. *
  86. * @param {number} [sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
  87. * @param {number} [flat=1.0] - the level of sharpening to apply to "flat" areas.
  88. * @param {number} [jagged=2.0] - the level of sharpening to apply to "jagged" areas.
  89. * @returns {Sharp}
  90. * @throws {Error} Invalid parameters
  91. */
  92. function sharpen (sigma, flat, jagged) {
  93. if (!is.defined(sigma)) {
  94. // No arguments: default to mild sharpen
  95. this.options.sharpenSigma = -1;
  96. } else if (is.bool(sigma)) {
  97. // Boolean argument: apply mild sharpen?
  98. this.options.sharpenSigma = sigma ? -1 : 0;
  99. } else if (is.number(sigma) && is.inRange(sigma, 0.01, 10000)) {
  100. // Numeric argument: specific sigma
  101. this.options.sharpenSigma = sigma;
  102. // Control over flat areas
  103. if (is.defined(flat)) {
  104. if (is.number(flat) && is.inRange(flat, 0, 10000)) {
  105. this.options.sharpenFlat = flat;
  106. } else {
  107. throw is.invalidParameterError('flat', 'number between 0 and 10000', flat);
  108. }
  109. }
  110. // Control over jagged areas
  111. if (is.defined(jagged)) {
  112. if (is.number(jagged) && is.inRange(jagged, 0, 10000)) {
  113. this.options.sharpenJagged = jagged;
  114. } else {
  115. throw is.invalidParameterError('jagged', 'number between 0 and 10000', jagged);
  116. }
  117. }
  118. } else {
  119. throw is.invalidParameterError('sigma', 'number between 0.01 and 10000', sigma);
  120. }
  121. return this;
  122. }
  123. /**
  124. * Apply median filter.
  125. * When used without parameters the default window is 3x3.
  126. * @param {number} [size=3] square mask size: size x size
  127. * @returns {Sharp}
  128. * @throws {Error} Invalid parameters
  129. */
  130. function median (size) {
  131. if (!is.defined(size)) {
  132. // No arguments: default to 3x3
  133. this.options.medianSize = 3;
  134. } else if (is.integer(size) && is.inRange(size, 1, 1000)) {
  135. // Numeric argument: specific sigma
  136. this.options.medianSize = size;
  137. } else {
  138. throw is.invalidParameterError('size', 'integer between 1 and 1000', size);
  139. }
  140. return this;
  141. }
  142. /**
  143. * Blur the image.
  144. * When used without parameters, performs a fast, mild blur of the output image.
  145. * When a `sigma` is provided, performs a slower, more accurate Gaussian blur.
  146. * @param {number} [sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
  147. * @returns {Sharp}
  148. * @throws {Error} Invalid parameters
  149. */
  150. function blur (sigma) {
  151. if (!is.defined(sigma)) {
  152. // No arguments: default to mild blur
  153. this.options.blurSigma = -1;
  154. } else if (is.bool(sigma)) {
  155. // Boolean argument: apply mild blur?
  156. this.options.blurSigma = sigma ? -1 : 0;
  157. } else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) {
  158. // Numeric argument: specific sigma
  159. this.options.blurSigma = sigma;
  160. } else {
  161. throw is.invalidParameterError('sigma', 'number between 0.3 and 1000', sigma);
  162. }
  163. return this;
  164. }
  165. /**
  166. * Merge alpha transparency channel, if any, with a background.
  167. * @param {Object} [options]
  168. * @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.
  169. * @returns {Sharp}
  170. */
  171. function flatten (options) {
  172. this.options.flatten = is.bool(options) ? options : true;
  173. if (is.object(options)) {
  174. this._setBackgroundColourOption('flattenBackground', options.background);
  175. }
  176. return this;
  177. }
  178. /**
  179. * Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of `1/gamma`
  180. * then increasing the encoding (brighten) post-resize at a factor of `gamma`.
  181. * This can improve the perceived brightness of a resized image in non-linear colour spaces.
  182. * JPEG and WebP input images will not take advantage of the shrink-on-load performance optimisation
  183. * when applying a gamma correction.
  184. *
  185. * Supply a second argument to use a different output gamma value, otherwise the first value is used in both cases.
  186. *
  187. * @param {number} [gamma=2.2] value between 1.0 and 3.0.
  188. * @param {number} [gammaOut] value between 1.0 and 3.0. (optional, defaults to same as `gamma`)
  189. * @returns {Sharp}
  190. * @throws {Error} Invalid parameters
  191. */
  192. function gamma (gamma, gammaOut) {
  193. if (!is.defined(gamma)) {
  194. // Default gamma correction of 2.2 (sRGB)
  195. this.options.gamma = 2.2;
  196. } else if (is.number(gamma) && is.inRange(gamma, 1, 3)) {
  197. this.options.gamma = gamma;
  198. } else {
  199. throw is.invalidParameterError('gamma', 'number between 1.0 and 3.0', gamma);
  200. }
  201. if (!is.defined(gammaOut)) {
  202. // Default gamma correction for output is same as input
  203. this.options.gammaOut = this.options.gamma;
  204. } else if (is.number(gammaOut) && is.inRange(gammaOut, 1, 3)) {
  205. this.options.gammaOut = gammaOut;
  206. } else {
  207. throw is.invalidParameterError('gammaOut', 'number between 1.0 and 3.0', gammaOut);
  208. }
  209. return this;
  210. }
  211. /**
  212. * Produce the "negative" of the image.
  213. * @param {Boolean} [negate=true]
  214. * @returns {Sharp}
  215. */
  216. function negate (negate) {
  217. this.options.negate = is.bool(negate) ? negate : true;
  218. return this;
  219. }
  220. /**
  221. * Enhance output image contrast by stretching its luminance to cover the full dynamic range.
  222. * @param {Boolean} [normalise=true]
  223. * @returns {Sharp}
  224. */
  225. function normalise (normalise) {
  226. this.options.normalise = is.bool(normalise) ? normalise : true;
  227. return this;
  228. }
  229. /**
  230. * Alternative spelling of normalise.
  231. * @param {Boolean} [normalize=true]
  232. * @returns {Sharp}
  233. */
  234. function normalize (normalize) {
  235. return this.normalise(normalize);
  236. }
  237. /**
  238. * Convolve the image with the specified kernel.
  239. *
  240. * @example
  241. * sharp(input)
  242. * .convolve({
  243. * width: 3,
  244. * height: 3,
  245. * kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1]
  246. * })
  247. * .raw()
  248. * .toBuffer(function(err, data, info) {
  249. * // data contains the raw pixel data representing the convolution
  250. * // of the input image with the horizontal Sobel operator
  251. * });
  252. *
  253. * @param {Object} kernel
  254. * @param {number} kernel.width - width of the kernel in pixels.
  255. * @param {number} kernel.height - width of the kernel in pixels.
  256. * @param {Array<number>} kernel.kernel - Array of length `width*height` containing the kernel values.
  257. * @param {number} [kernel.scale=sum] - the scale of the kernel in pixels.
  258. * @param {number} [kernel.offset=0] - the offset of the kernel in pixels.
  259. * @returns {Sharp}
  260. * @throws {Error} Invalid parameters
  261. */
  262. function convolve (kernel) {
  263. if (!is.object(kernel) || !Array.isArray(kernel.kernel) ||
  264. !is.integer(kernel.width) || !is.integer(kernel.height) ||
  265. !is.inRange(kernel.width, 3, 1001) || !is.inRange(kernel.height, 3, 1001) ||
  266. kernel.height * kernel.width !== kernel.kernel.length
  267. ) {
  268. // must pass in a kernel
  269. throw new Error('Invalid convolution kernel');
  270. }
  271. // Default scale is sum of kernel values
  272. if (!is.integer(kernel.scale)) {
  273. kernel.scale = kernel.kernel.reduce(function (a, b) {
  274. return a + b;
  275. }, 0);
  276. }
  277. // Clip scale to a minimum value of 1
  278. if (kernel.scale < 1) {
  279. kernel.scale = 1;
  280. }
  281. if (!is.integer(kernel.offset)) {
  282. kernel.offset = 0;
  283. }
  284. this.options.convKernel = kernel;
  285. return this;
  286. }
  287. /**
  288. * Any pixel value greather than or equal to the threshold value will be set to 255, otherwise it will be set to 0.
  289. * @param {number} [threshold=128] - a value in the range 0-255 representing the level at which the threshold will be applied.
  290. * @param {Object} [options]
  291. * @param {Boolean} [options.greyscale=true] - convert to single channel greyscale.
  292. * @param {Boolean} [options.grayscale=true] - alternative spelling for greyscale.
  293. * @returns {Sharp}
  294. * @throws {Error} Invalid parameters
  295. */
  296. function threshold (threshold, options) {
  297. if (!is.defined(threshold)) {
  298. this.options.threshold = 128;
  299. } else if (is.bool(threshold)) {
  300. this.options.threshold = threshold ? 128 : 0;
  301. } else if (is.integer(threshold) && is.inRange(threshold, 0, 255)) {
  302. this.options.threshold = threshold;
  303. } else {
  304. throw is.invalidParameterError('threshold', 'integer between 0 and 255', threshold);
  305. }
  306. if (!is.object(options) || options.greyscale === true || options.grayscale === true) {
  307. this.options.thresholdGrayscale = true;
  308. } else {
  309. this.options.thresholdGrayscale = false;
  310. }
  311. return this;
  312. }
  313. /**
  314. * Perform a bitwise boolean operation with operand image.
  315. *
  316. * This operation creates an output image where each pixel is the result of
  317. * the selected bitwise boolean `operation` between the corresponding pixels of the input images.
  318. *
  319. * @param {Buffer|string} operand - Buffer containing image data or string containing the path to an image file.
  320. * @param {string} operator - one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.
  321. * @param {Object} [options]
  322. * @param {Object} [options.raw] - describes operand when using raw pixel data.
  323. * @param {number} [options.raw.width]
  324. * @param {number} [options.raw.height]
  325. * @param {number} [options.raw.channels]
  326. * @returns {Sharp}
  327. * @throws {Error} Invalid parameters
  328. */
  329. function boolean (operand, operator, options) {
  330. this.options.boolean = this._createInputDescriptor(operand, options);
  331. if (is.string(operator) && is.inArray(operator, ['and', 'or', 'eor'])) {
  332. this.options.booleanOp = operator;
  333. } else {
  334. throw is.invalidParameterError('operator', 'one of: and, or, eor', operator);
  335. }
  336. return this;
  337. }
  338. /**
  339. * Apply the linear formula a * input + b to the image (levels adjustment)
  340. * @param {number} [a=1.0] multiplier
  341. * @param {number} [b=0.0] offset
  342. * @returns {Sharp}
  343. * @throws {Error} Invalid parameters
  344. */
  345. function linear (a, b) {
  346. if (!is.defined(a)) {
  347. this.options.linearA = 1.0;
  348. } else if (is.number(a)) {
  349. this.options.linearA = a;
  350. } else {
  351. throw is.invalidParameterError('a', 'numeric', a);
  352. }
  353. if (!is.defined(b)) {
  354. this.options.linearB = 0.0;
  355. } else if (is.number(b)) {
  356. this.options.linearB = b;
  357. } else {
  358. throw is.invalidParameterError('b', 'numeric', b);
  359. }
  360. return this;
  361. }
  362. /**
  363. * Recomb the image with the specified matrix.
  364. *
  365. * @since 0.21.1
  366. *
  367. * @example
  368. * sharp(input)
  369. * .recomb([
  370. * [0.3588, 0.7044, 0.1368],
  371. * [0.2990, 0.5870, 0.1140],
  372. * [0.2392, 0.4696, 0.0912],
  373. * ])
  374. * .raw()
  375. * .toBuffer(function(err, data, info) {
  376. * // data contains the raw pixel data after applying the recomb
  377. * // With this example input, a sepia filter has been applied
  378. * });
  379. *
  380. * @param {Array<Array<number>>} inputMatrix - 3x3 Recombination matrix
  381. * @returns {Sharp}
  382. * @throws {Error} Invalid parameters
  383. */
  384. function recomb (inputMatrix) {
  385. if (!Array.isArray(inputMatrix) || inputMatrix.length !== 3 ||
  386. inputMatrix[0].length !== 3 ||
  387. inputMatrix[1].length !== 3 ||
  388. inputMatrix[2].length !== 3
  389. ) {
  390. // must pass in a kernel
  391. throw new Error('Invalid recombination matrix');
  392. }
  393. this.options.recombMatrix = [
  394. inputMatrix[0][0], inputMatrix[0][1], inputMatrix[0][2],
  395. inputMatrix[1][0], inputMatrix[1][1], inputMatrix[1][2],
  396. inputMatrix[2][0], inputMatrix[2][1], inputMatrix[2][2]
  397. ].map(Number);
  398. return this;
  399. }
  400. /**
  401. * Transforms the image using brightness, saturation and hue rotation.
  402. *
  403. * @since 0.22.1
  404. *
  405. * @example
  406. * sharp(input)
  407. * .modulate({
  408. * brightness: 2 // increase lightness by a factor of 2
  409. * });
  410. *
  411. * sharp(input)
  412. * .modulate({
  413. * hue: 180 // hue-rotate by 180 degrees
  414. * });
  415. *
  416. * // decreate brightness and saturation while also hue-rotating by 90 degrees
  417. * sharp(input)
  418. * .modulate({
  419. * brightness: 0.5,
  420. * saturation: 0.5,
  421. * hue: 90
  422. * });
  423. *
  424. * @param {Object} [options]
  425. * @param {number} [options.brightness] Brightness multiplier
  426. * @param {number} [options.saturation] Saturation multiplier
  427. * @param {number} [options.hue] Degrees for hue rotation
  428. * @returns {Sharp}
  429. */
  430. function modulate (options) {
  431. if (!is.plainObject(options)) {
  432. throw is.invalidParameterError('options', 'plain object', options);
  433. }
  434. if ('brightness' in options) {
  435. if (is.number(options.brightness) && options.brightness >= 0) {
  436. this.options.brightness = options.brightness;
  437. } else {
  438. throw is.invalidParameterError('brightness', 'number above zero', options.brightness);
  439. }
  440. }
  441. if ('saturation' in options) {
  442. if (is.number(options.saturation) && options.saturation >= 0) {
  443. this.options.saturation = options.saturation;
  444. } else {
  445. throw is.invalidParameterError('saturation', 'number above zero', options.saturation);
  446. }
  447. }
  448. if ('hue' in options) {
  449. if (is.integer(options.hue)) {
  450. this.options.hue = options.hue % 360;
  451. } else {
  452. throw is.invalidParameterError('hue', 'number', options.hue);
  453. }
  454. }
  455. return this;
  456. }
  457. /**
  458. * Decorate the Sharp prototype with operation-related functions.
  459. * @private
  460. */
  461. module.exports = function (Sharp) {
  462. Object.assign(Sharp.prototype, {
  463. rotate,
  464. flip,
  465. flop,
  466. sharpen,
  467. median,
  468. blur,
  469. flatten,
  470. gamma,
  471. negate,
  472. normalise,
  473. normalize,
  474. convolve,
  475. threshold,
  476. boolean,
  477. linear,
  478. recomb,
  479. modulate
  480. });
  481. };