教程菜单 本页目录

调整图像大小

resize

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

将图像大小调整为宽度高度宽度 x 高度

当同时提供宽度高度时,图像应采用以下可能方法适应这些尺寸:

  • cover: (默认)保留纵横比,尝试通过裁剪/剪辑来确保图像覆盖提供的两个尺寸以适应。
  • contain: 保留宽高比,在必要时使用“信箱”包含在提供的两个尺寸内。
  • fill: 忽略输入的宽高比并拉伸到提供的两个尺寸。
  • inside: 保留宽高比,将图像调整为尽可能大,同时确保其尺寸小于或等于指定的两个尺寸。
  • outside: 保留宽高比,将图像调整为尽可能小,同时确保其尺寸大于或等于指定的两个尺寸。

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

当使用covercontain的适配时,默认位置为centre。其他选项包括:

  • 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 or centre.
  • sharp.strategy: 仅限 [cover],使用 [entropy] 或 [attention] 策略动态裁剪。

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

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

  • entropy: 关注香农熵最高的区域。
  • attention: 重点关注亮度频率、色彩饱和度和肤色存在度最高的区域。

可能的缩小内核包括:

  • nearest: 使用最近邻插值。
  • linear: 使用三角形滤波器。
  • cubic: 使用 Catmull-Rom 样条。
  • mitchell: 使用 Mitchell-Netravali 样条。
  • lanczos2: 使用 a=2 的 Lanczos 内核。
  • lanczos3: 使用 a=3(默认值)的 Lanczos 内核。

在上采样时,这些内核会映射到最近的线性立方插值器。没有匹配上采样插值器的下采样内核会映射到立方

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

Throws:

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

示例

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

extend

extend(extend) ⇒ Sharp

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

Throws:

  • 错误 参数无效
参数类型默认描述
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}背景颜色,由颜色模块解析,默认为黑色,不透明。

示例

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

示例

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

extract

extract(options) ⇒ Sharp

提取/裁剪图像的某个区域。

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

Throws:

  • 错误无效参数
参数类型描述
optionsObject描述使用整数像素提取的区域值
options.leftnumber从左边缘开始的零索引偏移量
options.topnumber从上边缘开始的零索引偏移量
options.widthnumber区域宽度提取
options.heightnumber要提取的区域的高度

示例

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

trim

trim([options]) ⇒ Sharp

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

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

如果此操作的结果将图像修剪为空白,则不会进行任何更改。

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

Throws:

  • 错误无效参数
参数类型默认描述
[options]Object
[options.background]string | Object"'top-left pixel'"背景颜色,通过颜色解析 模块,默认为左上角像素。
[options.threshold]number10允许与上述颜色有差异,为正数。
[options.lineArt]booleanfalse输入是否更接近线条艺术(例如矢量)而不是照片?

示例

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

示例

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

示例

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

示例

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