Skip to content

调整图片大小

resize

调整大小([宽度], [高度], [选项]) ⇒ Sharp

¥resize([width], [height], [options]) ⇒ Sharp

将图片大小调整为 widthheightwidth x height

¥Resize image to width, height or width x height.

当同时提供 widthheight 时,图片适合这些的可能方法是:

¥When both a width and height are provided, the possible methods by which the image should fit these are:

  • cover:(默认)保持纵横比,尝试通过裁剪/剪辑来确保图片覆盖所提供的两个尺寸。

    ¥cover: (default) Preserving aspect ratio, attempt to ensure the image covers both provided dimensions by cropping/clipping to fit.

  • contain:保留纵横比,必要时使用 “letterboxing” 包含在两个提供的尺寸内。

    ¥contain: Preserving aspect ratio, contain within both provided dimensions using “letterboxing” where necessary.

  • fill:忽略输入的纵横比并拉伸到两个提供的尺寸。

    ¥fill: Ignore the aspect ratio of the input and stretch to both provided dimensions.

  • inside:保留纵横比,将图片大小调整为尽可能大,同时确保其尺寸小于或等于指定的尺寸。

    ¥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:保留纵横比,将图片大小调整为尽可能小,同时确保其尺寸大于或等于指定的尺寸。

    ¥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.

其中一些值基于 object-fit CSS 属性。

¥Some of these values are based on the object-fit CSS property.

Examples of various values for the fit property when resizing

当使用 covercontain 配合时,默认位置为 centre。其他选项有:

¥When using a fit of cover or contain, the default position is centre. Other options are:

  • sharp.positiontopright toprightright bottombottomleft bottomleftleft top

  • sharp.gravitynorthnortheasteastsoutheastsouthsouthwestwestnorthwestcentercentre

    ¥sharp.gravity: north, northeast, east, southeast, south, southwest, west, northwest, center or centre.

  • sharp.strategy:仅 cover,使用 entropyattention 策略动态裁剪。

    ¥sharp.strategy: cover only, dynamically crop using either the entropy or attention strategy.

其中一些值基于 object-position CSS 属性。

¥Some of these values are based on the object-position CSS property.

基于策略的方法最初会调整大小,使一个维度处于其目标长度,然后反复对边缘区域进行排序,根据所选策略丢弃得分最低的边缘。

¥The strategy-based approach initially 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:重点关注 香农熵 最高的区域。

    ¥entropy: focus on the region with the highest Shannon entropy.

  • attention:重点关注亮度频率、色彩饱和度和肤色最高的区域。

    ¥attention: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.

可能的缩小内核是:

¥Possible downsizing kernels are:

当进行上采样时,这些内核会映射到 nearestlinearcubic 插值器。没有匹配的上采样插值器的下采样内核映射到 cubic

¥When upsampling, these kernels map to nearest, linear and cubic interpolators. Downsampling kernels without a matching upsampling interpolator map to cubic.

每个管道只能进行一次大小调整。同一管道中先前对 resize 的调用将被忽略。

¥Only one resize can occur per pipeline. Previous calls to resize in the same pipeline will be ignored.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

参数类型默认描述
[width]number生成的图片应该有多少像素宽。使用 nullundefined 自动缩放宽度以匹配高度。
[height]number生成的图片应该有多少像素高。使用 nullundefined 自动缩放高度以匹配宽度。
[options]Object
[options.width]number指定 width 的另一种方法。如果两者都存在,则优先。
[options.height]number指定 height 的另一种方法。如果两者都存在,则优先。
[options.fit]String’cover’如何调整/裁剪图片以适合目标尺寸(covercontainfillinsideoutside 之一)。
[options.position]String’centre’fitcovercontain 时要使用的位置、重力或策略。
[options.background]String | Object{r: 0, g: 0, b: 0, alpha: 1}fitcontain 时的背景颜色,由 color 模块解析,默认为黑色,不透明。
[options.kernel]String’lanczos3’用于图片缩小的内核和用于上采样的推断插值器。使用 fastShrinkOnLoad 选项来控制内核与加载时收缩。
[options.withoutEnlargement]Booleanfalse如果宽度或高度已经小于目标尺寸,则不要放大,相当于 GraphicsMagick 的 > 几何选项。这可能会导致输出尺寸小于目标尺寸。
[options.withoutReduction]Booleanfalse如果宽度或高度已经大于目标尺寸,则不要缩小,相当于 GraphicsMagick 的 < 几何选项。这仍然可能导致作物达到目标尺寸。
[options.fastShrinkOnLoad]Booleantrue充分利用 JPEG 和 WebP 加载时收缩功能,该功能可能会导致轻微的莫尔条纹或自动缩放尺寸的舍入。

示例

¥Example

sharp(input)
.resize({ width: 100 })
.toBuffer()
.then(data => {
// 100 pixels wide, auto-scaled height
});

示例

¥Example

sharp(input)
.resize({ height: 100 })
.toBuffer()
.then(data => {
// 100 pixels high, auto-scaled width
});

示例

¥Example

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
});

示例

¥Example

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);

示例

¥Example

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
});

示例

¥Example

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
});

示例

¥Example

const scaleByHalf = await sharp(input)
.metadata()
.then(({ width }) => sharp(input)
.resize(Math.round(width * 0.5))
.toBuffer()
);

extend

extend(extend) ⇒ Sharp

使用提供的背景颜色或从图片派生的像素扩展/填充/挤出图片的一个或多个边缘。此操作将始终在调整大小和提取后发生(如果有)。

¥Extend / pad / extrude one or more edges of the image with either the provided background colour or pixels derived from the image. This operation will always occur after resizing and extraction, if any.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

参数类型默认描述
extendnumber | Object添加到所有边缘或具有每边缘计数的对象的单个像素计数
[extend.top]number0
[extend.left]number0
[extend.bottom]number0
[extend.right]number0
[extend.extendWith]String’background’使用此方法填充新像素,其中之一:背景、复制、重复、镜像。
[extend.background]String | Object{r: 0, g: 0, b: 0, alpha: 1}背景颜色,由 color 模块解析,默认为黑色,不透明。

示例

¥Example

// 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 }
})
...

示例

¥Example

// Add a row of 10 red pixels to the bottom
sharp(input)
.extend({
bottom: 10,
background: 'red'
})
...

示例

¥Example

// Extrude image by 8 pixels to the right, mirroring existing right hand edge
sharp(input)
.extend({
right: 8,
background: 'mirror'
})
...

extract

extract(options) ⇒ Sharp

提取/裁剪图片的区域。

¥Extract/crop a region of the image.

  • resize 之前使用 extract 进行预调整大小提取。

    ¥Use extract before resize for pre-resize extraction.

  • resize 之后使用 extract 进行调整大小后提取。

    ¥Use extract after resize for post-resize extraction.

  • 使用 extract 两次和 resize 一次,按照固定的操作顺序进行提取-然后调整大小-然后提取。

    ¥Use extract twice and resize once for extract-then-resize-then-extract in a fixed operation order.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

参数类型描述
optionsObject描述使用积分像素值提取的区域
options.leftnumber距左边缘的零索引偏移
options.topnumber距顶部边缘的零索引偏移
options.widthnumber要提取的区域的宽度
options.heightnumber要提取的区域的高度

示例

¥Example

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.
});

示例

¥Example

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
});

trim

trim([options]) ⇒ Sharp

修剪所有边缘中包含与给定背景颜色相似的值的像素,该背景颜色默认为左上角像素的颜色。

¥Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.

具有 Alpha 通道的图片将使用 Alpha 和非 Alpha 通道的组合边界框。

¥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.

info 响应对象将包含 trimOffsetLefttrimOffsetTop 属性。

¥The info response Object will contain trimOffsetLeft and trimOffsetTop properties.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

参数类型默认描述
[options]Object
[options.background]string | Object“‘top-left pixel‘“背景颜色由 color 模块解析,默认为左上角像素的颜色。
[options.threshold]number10与上述颜色允许的差异,为正数。
[options.lineArt]booleanfalse输入是否更类似于线条艺术(例如矢量)而不是摄影?

示例

¥Example

// Trim pixels with a colour similar to that of the top-left pixel.
await sharp(input)
.trim()
.toFile(output);

示例

¥Example

// Trim pixels with the exact same colour as that of the top-left pixel.
await sharp(input)
.trim({
threshold: 0
})
.toFile(output);

示例

¥Example

// Assume input is line art and trim only pixels with a similar colour to red.
const output = await sharp(input)
.trim({
background: "#FF0000",
lineArt: true
})
.toBuffer();

示例

¥Example

// Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
const output = await sharp(input)
.trim({
background: "yellow",
threshold: 42,
})
.toBuffer();