调整图片大小
resize
调整大小([宽度], [高度], [选项]) ⇒
Sharp
¥resize([width], [height], [options]) ⇒
Sharp
将图片大小调整为 width
、height
或 width x height
。
¥Resize image to width
, height
or width x height
.
当同时提供 width
和 height
时,图片适合这些的可能方法是:
¥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.
当使用 cover
或 contain
配合时,默认位置为 centre
。其他选项有:
¥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
或centre
。¥
sharp.gravity
:north
,northeast
,east
,southeast
,south
,southwest
,west
,northwest
,center
orcentre
. -
sharp.strategy
:仅cover
,使用entropy
或attention
策略动态裁剪。¥
sharp.strategy
:cover
only, dynamically crop using either theentropy
orattention
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:
-
nearest
:使用 最近邻插值。¥
nearest
: Use nearest neighbour interpolation. -
linear
:使用 三角形过滤器。¥
linear
: Use a triangle filter. -
cubic
:使用 Catmull-Rom 样条线。¥
cubic
: Use a Catmull-Rom spline. -
mitchell
:使用 Mitchell-Netravali 样条。¥
mitchell
: Use a Mitchell-Netravali spline. -
lanczos2
:将 Lanczos 内核 与a=2
一起使用。¥
lanczos2
: Use a Lanczos kernel witha=2
. -
lanczos3
:使用带有a=3
(默认)的 Lanczos 内核。¥
lanczos3
: Use a Lanczos kernel witha=3
(the default).
当进行上采样时,这些内核会映射到 nearest
、linear
和 cubic
插值器。没有匹配的上采样插值器的下采样内核映射到 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 | 生成的图片应该有多少像素宽。使用 null 或 undefined 自动缩放宽度以匹配高度。 | |
[height] | number | 生成的图片应该有多少像素高。使用 null 或 undefined 自动缩放高度以匹配宽度。 | |
[options] | Object | ||
[options.width] | number | 指定 width 的另一种方法。如果两者都存在,则优先。 | |
[options.height] | number | 指定 height 的另一种方法。如果两者都存在,则优先。 | |
[options.fit] | String | ’cover’ | 如何调整/裁剪图片以适合目标尺寸(cover 、contain 、fill 、inside 或 outside 之一)。 |
[options.position] | String | ’centre’ | 当 fit 是 cover 或 contain 时要使用的位置、重力或策略。 |
[options.background] | String | Object | {r: 0, g: 0, b: 0, alpha: 1} | fit 为 contain 时的背景颜色,由 color 模块解析,默认为黑色,不透明。 |
[options.kernel] | String | ’lanczos3’ | 用于图片缩小的内核和用于上采样的推断插值器。使用 fastShrinkOnLoad 选项来控制内核与加载时收缩。 |
[options.withoutEnlargement] | Boolean | false | 如果宽度或高度已经小于目标尺寸,则不要放大,相当于 GraphicsMagick 的 > 几何选项。这可能会导致输出尺寸小于目标尺寸。 |
[options.withoutReduction] | Boolean | false | 如果宽度或高度已经大于目标尺寸,则不要缩小,相当于 GraphicsMagick 的 < 几何选项。这仍然可能导致作物达到目标尺寸。 |
[options.fastShrinkOnLoad] | Boolean | true | 充分利用 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 writableStreamreadableStream .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
参数 | 类型 | 默认 | 描述 |
---|---|---|---|
extend | number | Object | 添加到所有边缘或具有每边缘计数的对象的单个像素计数 | |
[extend.top] | number | 0 | |
[extend.left] | number | 0 | |
[extend.bottom] | number | 0 | |
[extend.right] | number | 0 | |
[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 edgesharp(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 bottomsharp(input) .extend({ bottom: 10, background: 'red' }) ...
示例
¥Example
// Extrude image by 8 pixels to the right, mirroring existing right hand edgesharp(input) .extend({ right: 8, background: 'mirror' }) ...
extract
extract(options) ⇒
Sharp
提取/裁剪图片的区域。
¥Extract/crop a region of the image.
-
在
resize
之前使用extract
进行预调整大小提取。¥Use
extract
beforeresize
for pre-resize extraction. -
在
resize
之后使用extract
进行调整大小后提取。¥Use
extract
afterresize
for post-resize extraction. -
使用
extract
两次和resize
一次,按照固定的操作顺序进行提取-然后调整大小-然后提取。¥Use
extract
twice andresize
once for extract-then-resize-then-extract in a fixed operation order.
抛出:
¥Throws:
-
Error
无效参数¥
Error
Invalid parameters
参数 | 类型 | 描述 |
---|---|---|
options | Object | 描述使用积分像素值提取的区域 |
options.left | number | 距左边缘的零索引偏移 |
options.top | number | 距顶部边缘的零索引偏移 |
options.width | number | 要提取的区域的宽度 |
options.height | number | 要提取的区域的高度 |
示例
¥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
响应对象将包含 trimOffsetLeft
和 trimOffsetTop
属性。
¥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] | number | 10 | 与上述颜色允许的差异,为正数。 |
[options.lineArt] | boolean | false | 输入是否更类似于线条艺术(例如矢量)而不是摄影? |
示例
¥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();