UNPKG

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