resize.js 20 KB

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