11 KiB
resize
Resize image to width
, height
or width x height
.
When both a width
and height
are provided, the possible methods by which the image should fit these are:
cover
: (default) Preserving aspect ratio, ensure the image covers both provided dimensions by cropping/clipping to fit.contain
: Preserving aspect ratio, contain within both provided dimensions using "letterboxing" where necessary.fill
: Ignore the aspect ratio of the input and stretch to both provided dimensions.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.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.
Some of these values are based on the object-fit CSS property.
When using a fit of cover
or contain
, the default position is centre
. Other options are:
sharp.position
:top
,right top
,right
,right bottom
,bottom
,left bottom
,left
,left top
.sharp.gravity
:north
,northeast
,east
,southeast
,south
,southwest
,west
,northwest
,center
orcentre
.sharp.strategy
:cover
only, dynamically crop using either theentropy
orattention
strategy.
Some of these values are based on the object-position CSS property.
The experimental strategy-based approach resizes so one dimension is at its target length then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.
entropy
: focus on the region with the highest Shannon entropy.attention
: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
Possible interpolation kernels are:
nearest
: Use nearest neighbour interpolation.cubic
: Use a Catmull-Rom spline.mitchell
: Use a Mitchell-Netravali spline.lanczos2
: Use a Lanczos kernel witha=2
.lanczos3
: Use a Lanczos kernel witha=3
(the default).
Only one resize can occur per pipeline.
Previous calls to resize
in the same pipeline will be ignored.
Parameters
-
width
number? pixels wide the resultant image should be. Usenull
orundefined
to auto-scale the width to match the height. -
height
number? pixels high the resultant image should be. Usenull
orundefined
to auto-scale the height to match the width. -
options
Object?options.width
String? alternative means of specifyingwidth
. If both are present this takes priority.options.height
String? alternative means of specifyingheight
. If both are present this takes priority.options.fit
String how the image should be resized to fit both provided dimensions, one ofcover
,contain
,fill
,inside
oroutside
. (optional, default'cover'
)options.position
String position, gravity or strategy to use whenfit
iscover
orcontain
. (optional, default'centre'
)options.background
(String | Object) background colour whenfit
iscontain
, parsed by the color module, defaults to black without transparency. (optional, default{r:0,g:0,b:0,alpha:1}
)options.kernel
String the kernel to use for image reduction. (optional, default'lanczos3'
)options.withoutEnlargement
Boolean do not enlarge if the width or height are already less than the specified dimensions, equivalent to GraphicsMagick's>
geometry option. (optional, defaultfalse
)options.withoutReduction
Boolean do not reduce if the width or height are already greater than the specified dimensions, equivalent to GraphicsMagick's<
geometry option. (optional, defaultfalse
)options.fastShrinkOnLoad
Boolean take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern on some images. (optional, defaulttrue
)
Examples
sharp(input)
.resize({ width: 100 })
.toBuffer()
.then(data => {
// 100 pixels wide, auto-scaled height
});
sharp(input)
.resize({ height: 100 })
.toBuffer()
.then(data => {
// 100 pixels high, auto-scaled width
});
sharp(input)
.resize(200, 300, {
kernel: sharp.kernel.nearest,
fit: 'contain',
position: 'right top',
background: { r: 255, g: 255, b: 255, alpha: 0.5 }
})
.toFile('output.png')
.then(() => {
// output.png is a 200 pixels wide and 300 pixels high image
// containing a nearest-neighbour scaled version
// contained within the north-east corner of a semi-transparent white canvas
});
const transformer = sharp()
.resize({
width: 200,
height: 200,
fit: sharp.fit.cover,
position: sharp.strategy.entropy
});
// Read image data from readableStream
// Write 200px square auto-cropped image data to writableStream
readableStream
.pipe(transformer)
.pipe(writableStream);
sharp(input)
.resize(200, 200, {
fit: sharp.fit.inside,
withoutEnlargement: true
})
.toFormat('jpeg')
.toBuffer()
.then(function(outputBuffer) {
// outputBuffer contains JPEG image data
// no wider and no higher than 200 pixels
// and no larger than the input image
});
sharp(input)
.resize(200, 200, {
fit: sharp.fit.outside,
withoutReduction: true
})
.toFormat('jpeg')
.toBuffer()
.then(function(outputBuffer) {
// outputBuffer contains JPEG image data
// of at least 200 pixels wide and 200 pixels high while maintaining aspect ratio
// and no smaller than the input image
});
const scaleByHalf = await sharp(input)
.metadata()
.then(({ width }) => sharp(input)
.resize(Math.round(width * 0.5))
.toBuffer()
);
- Throws Error Invalid parameters
Returns Sharp
extend
Extends/pads the edges of the image with the provided background colour. This operation will always occur after resizing and extraction, if any.
Parameters
-
extend
(number | Object) single pixel count to add to all edges or an Object with per-edge countsextend.top
number (optional, default0
)extend.left
number (optional, default0
)extend.bottom
number (optional, default0
)extend.right
number (optional, default0
)extend.background
(String | Object) background colour, parsed by the color module, defaults to black without transparency. (optional, default{r:0,g:0,b:0,alpha:1}
)
Examples
// Resize to 140 pixels wide, then add 10 transparent pixels
// to the top, left and right edges and 20 to the bottom edge
sharp(input)
.resize(140)
.extend({
top: 10,
bottom: 20,
left: 10,
right: 10,
background: { r: 0, g: 0, b: 0, alpha: 0 }
})
...
// Add a row of 10 red pixels to the bottom
sharp(input)
.extend({
bottom: 10,
background: 'red'
})
...
- Throws Error Invalid parameters
Returns Sharp
extract
Extract/crop a region of the image.
- Use
extract
beforeresize
for pre-resize extraction. - Use
extract
afterresize
for post-resize extraction. - Use
extract
before and after for both.
Parameters
-
options
Object describes the region to extract using integral pixel values
Examples
sharp(input)
.extract({ left: left, top: top, width: width, height: height })
.toFile(output, function(err) {
// Extract a region of the input image, saving in the same format.
});
sharp(input)
.extract({ left: leftOffsetPre, top: topOffsetPre, width: widthPre, height: heightPre })
.resize(width, height)
.extract({ left: leftOffsetPost, top: topOffsetPost, width: widthPost, height: heightPost })
.toFile(output, function(err) {
// Extract a region, resize, then extract from the resized image
});
- Throws Error Invalid parameters
Returns Sharp
trim
Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.
Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels.
If the result of this operation would trim an image to nothing then no change is made.
The info
response Object, obtained from callback of .toFile()
or .toBuffer()
,
will contain trimOffsetLeft
and trimOffsetTop
properties.
Parameters
-
trim
(string | number | Object) the specific background colour to trim, the threshold for doing so or an Object with both.
Examples
// Trim pixels with a colour similar to that of the top-left pixel.
sharp(input)
.trim()
.toFile(output, function(err, info) {
...
});
// Trim pixels with the exact same colour as that of the top-left pixel.
sharp(input)
.trim(0)
.toFile(output, function(err, info) {
...
});
// Trim only pixels with a similar colour to red.
sharp(input)
.trim("#FF0000")
.toFile(output, function(err, info) {
...
});
// Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
sharp(input)
.trim({
background: "yellow",
threshold: 42,
})
.toFile(output, function(err, info) {
...
});
- Throws Error Invalid parameters
Returns Sharp