resize.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. // Copyright 2013 Lovell Fuller and others.
  2. // SPDX-License-Identifier: Apache-2.0
  3. 'use strict';
  4. const is = require('./is');
  5. /**
  6. * Weighting to apply when using contain/cover fit.
  7. * @member
  8. * @private
  9. */
  10. const gravity = {
  11. center: 0,
  12. centre: 0,
  13. north: 1,
  14. east: 2,
  15. south: 3,
  16. west: 4,
  17. northeast: 5,
  18. southeast: 6,
  19. southwest: 7,
  20. northwest: 8
  21. };
  22. /**
  23. * Position to apply when using contain/cover fit.
  24. * @member
  25. * @private
  26. */
  27. const position = {
  28. top: 1,
  29. right: 2,
  30. bottom: 3,
  31. left: 4,
  32. 'right top': 5,
  33. 'right bottom': 6,
  34. 'left bottom': 7,
  35. 'left top': 8
  36. };
  37. /**
  38. * How to extend the image.
  39. * @member
  40. * @private
  41. */
  42. const extendWith = {
  43. background: 'background',
  44. copy: 'copy',
  45. repeat: 'repeat',
  46. mirror: 'mirror'
  47. };
  48. /**
  49. * Strategies for automagic cover behaviour.
  50. * @member
  51. * @private
  52. */
  53. const strategy = {
  54. entropy: 16,
  55. attention: 17
  56. };
  57. /**
  58. * Reduction kernels.
  59. * @member
  60. * @private
  61. */
  62. const kernel = {
  63. nearest: 'nearest',
  64. linear: 'linear',
  65. cubic: 'cubic',
  66. mitchell: 'mitchell',
  67. lanczos2: 'lanczos2',
  68. lanczos3: 'lanczos3'
  69. };
  70. /**
  71. * Methods by which an image can be resized to fit the provided dimensions.
  72. * @member
  73. * @private
  74. */
  75. const fit = {
  76. contain: 'contain',
  77. cover: 'cover',
  78. fill: 'fill',
  79. inside: 'inside',
  80. outside: 'outside'
  81. };
  82. /**
  83. * Map external fit property to internal canvas property.
  84. * @member
  85. * @private
  86. */
  87. const mapFitToCanvas = {
  88. contain: 'embed',
  89. cover: 'crop',
  90. fill: 'ignore_aspect',
  91. inside: 'max',
  92. outside: 'min'
  93. };
  94. /**
  95. * @private
  96. */
  97. function isRotationExpected (options) {
  98. return (options.angle % 360) !== 0 || options.useExifOrientation === true || options.rotationAngle !== 0;
  99. }
  100. /**
  101. * @private
  102. */
  103. function isResizeExpected (options) {
  104. return options.width !== -1 || options.height !== -1;
  105. }
  106. /**
  107. * Resize image to `width`, `height` or `width x height`.
  108. *
  109. * When both a `width` and `height` are provided, the possible methods by which the image should **fit** these are:
  110. * - `cover`: (default) Preserving aspect ratio, attempt to ensure the image covers both provided dimensions by cropping/clipping to fit.
  111. * - `contain`: Preserving aspect ratio, contain within both provided dimensions using "letterboxing" where necessary.
  112. * - `fill`: Ignore the aspect ratio of the input and stretch to both provided dimensions.
  113. * - `inside`: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified.
  114. * - `outside`: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified.
  115. *
  116. * Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property.
  117. *
  118. * <img alt="Examples of various values for the fit property when resizing" width="100%" style="aspect-ratio: 998/243" src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/api-resize-fit.svg">
  119. *
  120. * When using a **fit** of `cover` or `contain`, the default **position** is `centre`. Other options are:
  121. * - `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`.
  122. * - `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`.
  123. * - `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy.
  124. *
  125. * Some of these values are based on the [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS property.
  126. *
  127. * The strategy-based approach initially resizes so one dimension is at its target length
  128. * then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.
  129. * - `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29).
  130. * - `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
  131. *
  132. * Possible downsizing kernels are:
  133. * - `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation).
  134. * - `linear`: Use a [triangle filter](https://en.wikipedia.org/wiki/Triangular_function).
  135. * - `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline).
  136. * - `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf).
  137. * - `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`.
  138. * - `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
  139. *
  140. * When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators.
  141. * Downsampling kernels without a matching upsampling interpolator map to `cubic`.
  142. *
  143. * Only one resize can occur per pipeline.
  144. * Previous calls to `resize` in the same pipeline will be ignored.
  145. *
  146. * @example
  147. * sharp(input)
  148. * .resize({ width: 100 })
  149. * .toBuffer()
  150. * .then(data => {
  151. * // 100 pixels wide, auto-scaled height
  152. * });
  153. *
  154. * @example
  155. * sharp(input)
  156. * .resize({ height: 100 })
  157. * .toBuffer()
  158. * .then(data => {
  159. * // 100 pixels high, auto-scaled width
  160. * });
  161. *
  162. * @example
  163. * sharp(input)
  164. * .resize(200, 300, {
  165. * kernel: sharp.kernel.nearest,
  166. * fit: 'contain',
  167. * position: 'right top',
  168. * background: { r: 255, g: 255, b: 255, alpha: 0.5 }
  169. * })
  170. * .toFile('output.png')
  171. * .then(() => {
  172. * // output.png is a 200 pixels wide and 300 pixels high image
  173. * // containing a nearest-neighbour scaled version
  174. * // contained within the north-east corner of a semi-transparent white canvas
  175. * });
  176. *
  177. * @example
  178. * const transformer = sharp()
  179. * .resize({
  180. * width: 200,
  181. * height: 200,
  182. * fit: sharp.fit.cover,
  183. * position: sharp.strategy.entropy
  184. * });
  185. * // Read image data from readableStream
  186. * // Write 200px square auto-cropped image data to writableStream
  187. * readableStream
  188. * .pipe(transformer)
  189. * .pipe(writableStream);
  190. *
  191. * @example
  192. * sharp(input)
  193. * .resize(200, 200, {
  194. * fit: sharp.fit.inside,
  195. * withoutEnlargement: true
  196. * })
  197. * .toFormat('jpeg')
  198. * .toBuffer()
  199. * .then(function(outputBuffer) {
  200. * // outputBuffer contains JPEG image data
  201. * // no wider and no higher than 200 pixels
  202. * // and no larger than the input image
  203. * });
  204. *
  205. * @example
  206. * sharp(input)
  207. * .resize(200, 200, {
  208. * fit: sharp.fit.outside,
  209. * withoutReduction: true
  210. * })
  211. * .toFormat('jpeg')
  212. * .toBuffer()
  213. * .then(function(outputBuffer) {
  214. * // outputBuffer contains JPEG image data
  215. * // of at least 200 pixels wide and 200 pixels high while maintaining aspect ratio
  216. * // and no smaller than the input image
  217. * });
  218. *
  219. * @example
  220. * const scaleByHalf = await sharp(input)
  221. * .metadata()
  222. * .then(({ width }) => sharp(input)
  223. * .resize(Math.round(width * 0.5))
  224. * .toBuffer()
  225. * );
  226. *
  227. * @param {number} [width] - How many pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height.
  228. * @param {number} [height] - How many pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width.
  229. * @param {Object} [options]
  230. * @param {number} [options.width] - An alternative means of specifying `width`. If both are present this takes priority.
  231. * @param {number} [options.height] - An alternative means of specifying `height`. If both are present this takes priority.
  232. * @param {String} [options.fit='cover'] - How the image should be resized/cropped to fit the target dimension(s), one of `cover`, `contain`, `fill`, `inside` or `outside`.
  233. * @param {String} [options.position='centre'] - A position, gravity or strategy to use when `fit` is `cover` or `contain`.
  234. * @param {String|Object} [options.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency.
  235. * @param {String} [options.kernel='lanczos3'] - The kernel to use for image reduction and the inferred interpolator to use for upsampling. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load.
  236. * @param {Boolean} [options.withoutEnlargement=false] - Do not scale up if the width *or* height are already less than the target dimensions, equivalent to GraphicsMagick's `>` geometry option. This may result in output dimensions smaller than the target dimensions.
  237. * @param {Boolean} [options.withoutReduction=false] - Do not scale down if the width *or* height are already greater than the target dimensions, equivalent to GraphicsMagick's `<` geometry option. This may still result in a crop to reach the target dimensions.
  238. * @param {Boolean} [options.fastShrinkOnLoad=true] - Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern or round-down of an auto-scaled dimension.
  239. * @returns {Sharp}
  240. * @throws {Error} Invalid parameters
  241. */
  242. function resize (widthOrOptions, height, options) {
  243. if (isResizeExpected(this.options)) {
  244. this.options.debuglog('ignoring previous resize options');
  245. }
  246. if (this.options.widthPost !== -1) {
  247. this.options.debuglog('operation order will be: extract, resize, extract');
  248. }
  249. if (is.defined(widthOrOptions)) {
  250. if (is.object(widthOrOptions) && !is.defined(options)) {
  251. options = widthOrOptions;
  252. } else if (is.integer(widthOrOptions) && widthOrOptions > 0) {
  253. this.options.width = widthOrOptions;
  254. } else {
  255. throw is.invalidParameterError('width', 'positive integer', widthOrOptions);
  256. }
  257. } else {
  258. this.options.width = -1;
  259. }
  260. if (is.defined(height)) {
  261. if (is.integer(height) && height > 0) {
  262. this.options.height = height;
  263. } else {
  264. throw is.invalidParameterError('height', 'positive integer', height);
  265. }
  266. } else {
  267. this.options.height = -1;
  268. }
  269. if (is.object(options)) {
  270. // Width
  271. if (is.defined(options.width)) {
  272. if (is.integer(options.width) && options.width > 0) {
  273. this.options.width = options.width;
  274. } else {
  275. throw is.invalidParameterError('width', 'positive integer', options.width);
  276. }
  277. }
  278. // Height
  279. if (is.defined(options.height)) {
  280. if (is.integer(options.height) && options.height > 0) {
  281. this.options.height = options.height;
  282. } else {
  283. throw is.invalidParameterError('height', 'positive integer', options.height);
  284. }
  285. }
  286. // Fit
  287. if (is.defined(options.fit)) {
  288. const canvas = mapFitToCanvas[options.fit];
  289. if (is.string(canvas)) {
  290. this.options.canvas = canvas;
  291. } else {
  292. throw is.invalidParameterError('fit', 'valid fit', options.fit);
  293. }
  294. }
  295. // Position
  296. if (is.defined(options.position)) {
  297. const pos = is.integer(options.position)
  298. ? options.position
  299. : strategy[options.position] || position[options.position] || gravity[options.position];
  300. if (is.integer(pos) && (is.inRange(pos, 0, 8) || is.inRange(pos, 16, 17))) {
  301. this.options.position = pos;
  302. } else {
  303. throw is.invalidParameterError('position', 'valid position/gravity/strategy', options.position);
  304. }
  305. }
  306. // Background
  307. this._setBackgroundColourOption('resizeBackground', options.background);
  308. // Kernel
  309. if (is.defined(options.kernel)) {
  310. if (is.string(kernel[options.kernel])) {
  311. this.options.kernel = kernel[options.kernel];
  312. } else {
  313. throw is.invalidParameterError('kernel', 'valid kernel name', options.kernel);
  314. }
  315. }
  316. // Without enlargement
  317. if (is.defined(options.withoutEnlargement)) {
  318. this._setBooleanOption('withoutEnlargement', options.withoutEnlargement);
  319. }
  320. // Without reduction
  321. if (is.defined(options.withoutReduction)) {
  322. this._setBooleanOption('withoutReduction', options.withoutReduction);
  323. }
  324. // Shrink on load
  325. if (is.defined(options.fastShrinkOnLoad)) {
  326. this._setBooleanOption('fastShrinkOnLoad', options.fastShrinkOnLoad);
  327. }
  328. }
  329. if (isRotationExpected(this.options) && isResizeExpected(this.options)) {
  330. this.options.rotateBeforePreExtract = true;
  331. }
  332. return this;
  333. }
  334. /**
  335. * Extend / pad / extrude one or more edges of the image with either
  336. * the provided background colour or pixels derived from the image.
  337. * This operation will always occur after resizing and extraction, if any.
  338. *
  339. * @example
  340. * // Resize to 140 pixels wide, then add 10 transparent pixels
  341. * // to the top, left and right edges and 20 to the bottom edge
  342. * sharp(input)
  343. * .resize(140)
  344. * .extend({
  345. * top: 10,
  346. * bottom: 20,
  347. * left: 10,
  348. * right: 10,
  349. * background: { r: 0, g: 0, b: 0, alpha: 0 }
  350. * })
  351. * ...
  352. *
  353. * @example
  354. * // Add a row of 10 red pixels to the bottom
  355. * sharp(input)
  356. * .extend({
  357. * bottom: 10,
  358. * background: 'red'
  359. * })
  360. * ...
  361. *
  362. * @example
  363. * // Extrude image by 8 pixels to the right, mirroring existing right hand edge
  364. * sharp(input)
  365. * .extend({
  366. * right: 8,
  367. * background: 'mirror'
  368. * })
  369. * ...
  370. *
  371. * @param {(number|Object)} extend - single pixel count to add to all edges or an Object with per-edge counts
  372. * @param {number} [extend.top=0]
  373. * @param {number} [extend.left=0]
  374. * @param {number} [extend.bottom=0]
  375. * @param {number} [extend.right=0]
  376. * @param {String} [extend.extendWith='background'] - populate new pixels using this method, one of: background, copy, repeat, mirror.
  377. * @param {String|Object} [extend.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency.
  378. * @returns {Sharp}
  379. * @throws {Error} Invalid parameters
  380. */
  381. function extend (extend) {
  382. if (is.integer(extend) && extend > 0) {
  383. this.options.extendTop = extend;
  384. this.options.extendBottom = extend;
  385. this.options.extendLeft = extend;
  386. this.options.extendRight = extend;
  387. } else if (is.object(extend)) {
  388. if (is.defined(extend.top)) {
  389. if (is.integer(extend.top) && extend.top >= 0) {
  390. this.options.extendTop = extend.top;
  391. } else {
  392. throw is.invalidParameterError('top', 'positive integer', extend.top);
  393. }
  394. }
  395. if (is.defined(extend.bottom)) {
  396. if (is.integer(extend.bottom) && extend.bottom >= 0) {
  397. this.options.extendBottom = extend.bottom;
  398. } else {
  399. throw is.invalidParameterError('bottom', 'positive integer', extend.bottom);
  400. }
  401. }
  402. if (is.defined(extend.left)) {
  403. if (is.integer(extend.left) && extend.left >= 0) {
  404. this.options.extendLeft = extend.left;
  405. } else {
  406. throw is.invalidParameterError('left', 'positive integer', extend.left);
  407. }
  408. }
  409. if (is.defined(extend.right)) {
  410. if (is.integer(extend.right) && extend.right >= 0) {
  411. this.options.extendRight = extend.right;
  412. } else {
  413. throw is.invalidParameterError('right', 'positive integer', extend.right);
  414. }
  415. }
  416. this._setBackgroundColourOption('extendBackground', extend.background);
  417. if (is.defined(extend.extendWith)) {
  418. if (is.string(extendWith[extend.extendWith])) {
  419. this.options.extendWith = extendWith[extend.extendWith];
  420. } else {
  421. throw is.invalidParameterError('extendWith', 'one of: background, copy, repeat, mirror', extend.extendWith);
  422. }
  423. }
  424. } else {
  425. throw is.invalidParameterError('extend', 'integer or object', extend);
  426. }
  427. return this;
  428. }
  429. /**
  430. * Extract/crop a region of the image.
  431. *
  432. * - Use `extract` before `resize` for pre-resize extraction.
  433. * - Use `extract` after `resize` for post-resize extraction.
  434. * - Use `extract` twice and `resize` once for extract-then-resize-then-extract in a fixed operation order.
  435. *
  436. * @example
  437. * sharp(input)
  438. * .extract({ left: left, top: top, width: width, height: height })
  439. * .toFile(output, function(err) {
  440. * // Extract a region of the input image, saving in the same format.
  441. * });
  442. * @example
  443. * sharp(input)
  444. * .extract({ left: leftOffsetPre, top: topOffsetPre, width: widthPre, height: heightPre })
  445. * .resize(width, height)
  446. * .extract({ left: leftOffsetPost, top: topOffsetPost, width: widthPost, height: heightPost })
  447. * .toFile(output, function(err) {
  448. * // Extract a region, resize, then extract from the resized image
  449. * });
  450. *
  451. * @param {Object} options - describes the region to extract using integral pixel values
  452. * @param {number} options.left - zero-indexed offset from left edge
  453. * @param {number} options.top - zero-indexed offset from top edge
  454. * @param {number} options.width - width of region to extract
  455. * @param {number} options.height - height of region to extract
  456. * @returns {Sharp}
  457. * @throws {Error} Invalid parameters
  458. */
  459. function extract (options) {
  460. const suffix = isResizeExpected(this.options) || this.options.widthPre !== -1 ? 'Post' : 'Pre';
  461. if (this.options[`width${suffix}`] !== -1) {
  462. this.options.debuglog('ignoring previous extract options');
  463. }
  464. ['left', 'top', 'width', 'height'].forEach(function (name) {
  465. const value = options[name];
  466. if (is.integer(value) && value >= 0) {
  467. this.options[name + (name === 'left' || name === 'top' ? 'Offset' : '') + suffix] = value;
  468. } else {
  469. throw is.invalidParameterError(name, 'integer', value);
  470. }
  471. }, this);
  472. // Ensure existing rotation occurs before pre-resize extraction
  473. if (isRotationExpected(this.options) && !isResizeExpected(this.options)) {
  474. if (this.options.widthPre === -1 || this.options.widthPost === -1) {
  475. this.options.rotateBeforePreExtract = true;
  476. }
  477. }
  478. return this;
  479. }
  480. /**
  481. * Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.
  482. *
  483. * Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels.
  484. *
  485. * If the result of this operation would trim an image to nothing then no change is made.
  486. *
  487. * The `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` properties.
  488. *
  489. * @example
  490. * // Trim pixels with a colour similar to that of the top-left pixel.
  491. * await sharp(input)
  492. * .trim()
  493. * .toFile(output);
  494. *
  495. * @example
  496. * // Trim pixels with the exact same colour as that of the top-left pixel.
  497. * await sharp(input)
  498. * .trim({
  499. * threshold: 0
  500. * })
  501. * .toFile(output);
  502. *
  503. * @example
  504. * // Assume input is line art and trim only pixels with a similar colour to red.
  505. * const output = await sharp(input)
  506. * .trim({
  507. * background: "#FF0000",
  508. * lineArt: true
  509. * })
  510. * .toBuffer();
  511. *
  512. * @example
  513. * // Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
  514. * const output = await sharp(input)
  515. * .trim({
  516. * background: "yellow",
  517. * threshold: 42,
  518. * })
  519. * .toBuffer();
  520. *
  521. * @param {Object} [options]
  522. * @param {string|Object} [options.background='top-left pixel'] - Background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel.
  523. * @param {number} [options.threshold=10] - Allowed difference from the above colour, a positive number.
  524. * @param {boolean} [options.lineArt=false] - Does the input more closely resemble line art (e.g. vector) rather than being photographic?
  525. * @returns {Sharp}
  526. * @throws {Error} Invalid parameters
  527. */
  528. function trim (options) {
  529. this.options.trimThreshold = 10;
  530. if (is.defined(options)) {
  531. if (is.object(options)) {
  532. if (is.defined(options.background)) {
  533. this._setBackgroundColourOption('trimBackground', options.background);
  534. }
  535. if (is.defined(options.threshold)) {
  536. if (is.number(options.threshold) && options.threshold >= 0) {
  537. this.options.trimThreshold = options.threshold;
  538. } else {
  539. throw is.invalidParameterError('threshold', 'positive number', options.threshold);
  540. }
  541. }
  542. if (is.defined(options.lineArt)) {
  543. this._setBooleanOption('trimLineArt', options.lineArt);
  544. }
  545. } else {
  546. throw is.invalidParameterError('trim', 'object', options);
  547. }
  548. }
  549. if (isRotationExpected(this.options)) {
  550. this.options.rotateBeforePreExtract = true;
  551. }
  552. return this;
  553. }
  554. /**
  555. * Decorate the Sharp prototype with resize-related functions.
  556. * @private
  557. */
  558. module.exports = function (Sharp) {
  559. Object.assign(Sharp.prototype, {
  560. resize,
  561. extend,
  562. extract,
  563. trim
  564. });
  565. // Class attributes
  566. Sharp.gravity = gravity;
  567. Sharp.strategy = strategy;
  568. Sharp.kernel = kernel;
  569. Sharp.fit = fit;
  570. Sharp.position = position;
  571. };