Skip to content

图片操作

rotate

rotate([angle], [options]) ⇒ Sharp

旋转输出图片。

¥Rotate the output image.

提供的角度转换为有效的正度旋转。例如,-450 将产生 270 度旋转。

¥The provided angle is converted to a valid positive degree rotation. For example, -450 will produce a 270 degree rotation.

当旋转角度不是 90 的倍数时,可以使用 background 选项提供背景颜色。

¥When rotating by an angle other than a multiple of 90, the background colour can be provided with the background option.

为了向后兼容,如果未提供角度,将调用 .autoOrient()

¥For backwards compatibility, if no angle is provided, .autoOrient() will be called.

每个管道只能发生一次旋转(除了初始调用没有通过 EXIF 数据进行定位的参数)。同一管道中先前对 rotate 的调用将被忽略。

¥Only one rotation can occur per pipeline (aside from an initial call without arguments to orient via EXIF data). Previous calls to rotate in the same pipeline will be ignored.

多页图片只能旋转 180 度。

¥Multi-page images can only be rotated by 180 degrees.

旋转、调整大小和/或提取区域时,方法顺序很重要,例如 .rotate(x).extract(y) 将产生与 .extract(y).rotate(x) 不同的结果。

¥Method order is important when rotating, resizing and/or extracting regions, for example .rotate(x).extract(y) will produce a different result to .extract(y).rotate(x).

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

参数类型默认描述
[angle]numberauto旋转角度。
[options]Object如果存在,则为具有可选属性的对象。
[options.background]string | Object""#000000""color 模块解析以提取红色、绿色、蓝色和 alpha 的值。

示例

¥Example

const rotateThenResize = await sharp(input)
.rotate(90)
.resize({ width: 16, height: 8, fit: 'fill' })
.toBuffer();
const resizeThenRotate = await sharp(input)
.resize({ width: 16, height: 8, fit: 'fill' })
.rotate(90)
.toBuffer();

autoOrient

autoOrient() ⇒ Sharp

根据 EXIF Orientation 标签自动定向,然后删除该标签。支持镜像并且可以推断翻转操作的使用。

¥Auto-orient based on the EXIF Orientation tag, then remove the tag. Mirroring is supported and may infer the use of a flip operation.

无论调用顺序如何,在自动定位之后,逻辑上都会发生 rotate(angle)flip()flop() 的先前或后续使用。

¥Previous or subsequent use of rotate(angle) and either flip() or flop() will logically occur after auto-orientation, regardless of call order.

示例

¥Example

const output = await sharp(input).autoOrient().toBuffer();

示例

¥Example

const pipeline = sharp()
.autoOrient()
.resize(null, 200)
.toBuffer(function (err, outputBuffer, info) {
// outputBuffer contains 200px high JPEG image data,
// auto-oriented using EXIF Orientation tag
// info.width and info.height contain the dimensions of the resized image
});
readableStream.pipe(pipeline);

flip

flip([flip]) ⇒ Sharp

围绕 x 轴垂直(上下)镜像图片。这总是发生在旋转之前(如果有的话)。

¥Mirror the image vertically (up-down) about the x-axis. This always occurs before rotation, if any.

对于多页图片,此操作无法正常工作。

¥This operation does not work correctly with multi-page images.

参数类型默认
[flip]Booleantrue

示例

¥Example

const output = await sharp(input).flip().toBuffer();

flop

flop([flop]) ⇒ Sharp

围绕 y 轴水平(左右)镜像图片。这总是发生在旋转之前(如果有的话)。

¥Mirror the image horizontally (left-right) about the y-axis. This always occurs before rotation, if any.

参数类型默认
[flop]Booleantrue

示例

¥Example

const output = await sharp(input).flop().toBuffer();

affine

affine(matrix, [options]) ⇒ Sharp

对图片执行仿射变换。此操作将始终在调整大小、提取和旋转(如果有)之后发生。

¥Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.

你必须提供长度为 4 的数组或 2x2 仿射变换矩阵。默认情况下,新像素将填充黑色背景。你可以使用 background 选项提供背景颜色。还可以指定特定的插值器。将 interpolator 选项设置为 sharp.interpolators 对象的属性,例如 sharp.interpolators.nohalo

¥You must provide an array of length 4 or a 2x2 affine transformation matrix. By default, new pixels are filled with a black background. You can provide a background colour with the background option. A particular interpolator may also be specified. Set the interpolator option to an attribute of the sharp.interpolators Object e.g. sharp.interpolators.nohalo.

对于 2x2 矩阵,变换为:

¥In the case of a 2x2 matrix, the transform is:

  • X = matrix[0, 0] * (x + idx) + matrix[0, 1] * (y + idy) + odx

  • Y = matrix[1, 0] * (x + idx) + matrix[1, 1] * (y + idy) + ody

where:

  • x 和 y 是输入图片中的坐标。

    ¥x and y are the coordinates in input image.

  • X 和 Y 是输出图片中的坐标。

    ¥X and Y are the coordinates in output image.

  • (0,0) 是左上角。

    ¥(0,0) is the upper left corner.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

自从:0.27.0

¥Since: 0.27.0

参数类型默认描述
matrixArray.<Array.<number>> | Array.<number>仿射变换矩阵
[options]Object如果存在,则为具有可选属性的对象。
[options.background]String | Object”#000000”color 模块解析以提取红色、绿色、蓝色和 alpha 的值。
[options.idx]Number0输入水平偏移
[options.idy]Number0输入垂直偏移
[options.odx]Number0输出水平偏移
[options.ody]Number0输出垂直偏移
[options.interpolator]Stringsharp.interpolators.bicubicinterpolator

示例

¥Example

const pipeline = sharp()
.affine([[1, 0.3], [0.1, 0.7]], {
background: 'white',
interpolator: sharp.interpolators.nohalo
})
.toBuffer((err, outputBuffer, info) => {
// outputBuffer contains the transformed image
// info.width and info.height contain the new dimensions
});
inputStream
.pipe(pipeline);

sharpen

锐化([选项], [平坦], [锯齿状]) ⇒ Sharp

¥sharpen([options], [flat], [jagged]) ⇒ Sharp

锐化图片。

¥Sharpen the image.

当不带参数使用时,对输出图片执行快速、温和的锐化。

¥When used without parameters, performs a fast, mild sharpen of the output image.

当提供 sigma 时,会对 LAB 色彩空间中的 L 通道执行更慢、更准确的锐化。可以对 “flat” (m1) 和 “jagged” (m2) 区域的锐化级别进行细粒度控制。

¥When a sigma is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space. Fine-grained control over the level of sharpening in “flat” (m1) and “jagged” (m2) areas is available.

参见 libvips 锐化 操作。

¥See libvips sharpen operation.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

参数类型默认描述
[options]Object | number如果存在,是一个具有属性的对象
[options.sigma]number高斯掩模的西格玛,其中 sigma = 1 + radius / 2,介于 0.000001 和 10 之间
[options.m1]number1.0适用于 “flat” 区域的锐化级别,介于 0 到 1000000 之间
[options.m2]number2.0适用于 “jagged” 区域的锐化级别,介于 0 到 1000000 之间
[options.x1]number2.0”flat” 和 “jagged” 之间、0 到 1000000 之间的阈值
[options.y2]number10.0最大增亮量,介于 0 到 1000000 之间
[options.y3]number20.0最大变暗量,介于 0 到 1000000 之间
[flat]number(已弃用)参见 options.m1
[jagged]number(已弃用)参见 options.m2

示例

¥Example

const data = await sharp(input).sharpen().toBuffer();

示例

¥Example

const data = await sharp(input).sharpen({ sigma: 2 }).toBuffer();

示例

¥Example

const data = await sharp(input)
.sharpen({
sigma: 2,
m1: 0,
m2: 3,
x1: 3,
y2: 15,
y3: 15,
})
.toBuffer();

median

median([size]) ⇒ Sharp

应用中值滤波器。当不带参数使用时,默认窗口为 3x3。

¥Apply median filter. When used without parameters the default window is 3x3.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

参数类型默认描述
[size]number3方形掩模尺寸:尺寸×尺寸

示例

¥Example

const output = await sharp(input).median().toBuffer();

示例

¥Example

const output = await sharp(input).median(5).toBuffer();

blur

blur([options]) ⇒ Sharp

模糊图片。

¥Blur the image.

当不带参数使用时,执行快速 3x3 框模糊(相当于框线性滤镜)。

¥When used without parameters, performs a fast 3x3 box blur (equivalent to a box linear filter).

当提供 sigma 时,执行更慢、更准确的高斯模糊。

¥When a sigma is provided, performs a slower, more accurate Gaussian blur.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

参数类型默认描述
[options]Object | number | Boolean
[options.sigma]number0.3 到 1000 之间的值,表示高斯掩模的 sigma,其中 sigma = 1 + radius / 2
[options.precision]string“‘integer‘“操作的准确度应为以下之一:整数、浮点数、近似值。
[options.minAmplitude]number0.20.001 和 1 之间的值。较小的值将生成更大、更准确的蒙版。

示例

¥Example

const boxBlurred = await sharp(input)
.blur()
.toBuffer();

示例

¥Example

const gaussianBlurred = await sharp(input)
.blur(5)
.toBuffer();

dilate

dilate([width]) ⇒ Sharp

使用扩张形态运算符扩展前景对象。

¥Expand foreground objects using the dilate morphological operator.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

参数类型默认描述
[width]Number1扩张宽度(以像素为单位)。

示例

¥Example

const output = await sharp(input)
.dilate()
.toBuffer();

erode

erode([width]) ⇒ Sharp

使用侵蚀形态运算符缩小前景对象。

¥Shrink foreground objects using the erode morphological operator.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

参数类型默认描述
[width]Number1以像素为单位的侵蚀宽度。

示例

¥Example

const output = await sharp(input)
.erode()
.toBuffer();

flatten

flatten([options]) ⇒ Sharp

将 Alpha 透明度通道(如果有)与背景合并,然后删除 Alpha 通道。

¥Merge alpha transparency channel, if any, with a background, then remove the alpha channel.

另见 removeAlpha

¥See also removeAlpha.

参数类型默认描述
[options]Object
[options.background]string | Object”{r: 0, g: 0, b: 0}“背景颜色,由 color 模块解析,默认为黑色。

示例

¥Example

await sharp(rgbaInput)
.flatten({ background: '#F0A703' })
.toBuffer();

unflatten

unflatten()

确保图片具有 Alpha 通道,并且所有白色像素值都完全透明。

¥Ensure the image has an alpha channel with all white pixel values made fully transparent.

非白色像素的现有 Alpha 通道值保持不变。

¥Existing alpha channel values for non-white pixels remain unchanged.

此功能是实验性的,API 可能会更改。

¥This feature is experimental and the API may change.

自从:0.32.1 示例

¥Since: 0.32.1
Example

await sharp(rgbInput)
.unflatten()
.toBuffer();

示例

¥Example

await sharp(rgbInput)
.threshold(128, { grayscale: false }) // converter bright pixels to white
.unflatten()
.toBuffer();

gamma

gamma([gamma], [gammaOut]) ⇒ Sharp

通过以 1/gamma 倍减少编码(变暗)预调整大小,然后以 gamma 倍增加编码(变亮)后调整大小来应用伽玛校正。这可以提高非线性色彩空间中调整大小的图片的感知亮度。应用伽玛校正时,JPEG 和 WebP 输入图片将不会利用加载时收缩性能优化。

¥Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of 1/gamma then increasing the encoding (brighten) post-resize at a factor of gamma. This can improve the perceived brightness of a resized image in non-linear colour spaces. JPEG and WebP input images will not take advantage of the shrink-on-load performance optimisation when applying a gamma correction.

提供第二个参数以使用不同的输出伽马值,否则在两种情况下都使用第一个值。

¥Supply a second argument to use a different output gamma value, otherwise the first value is used in both cases.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

参数类型默认描述
[gamma]number2.2值介于 1.0 和 3.0 之间。
[gammaOut]number值介于 1.0 和 3.0 之间。(可选,默认与 gamma 相同)

negate

negate([options]) ⇒ Sharp

生成图片的 “negative”。

¥Produce the “negative” of the image.

参数类型默认描述
[options]Object
[options.alpha]Booleantrue是否取消任何 Alpha 通道

示例

¥Example

const output = await sharp(input)
.negate()
.toBuffer();

示例

¥Example

const output = await sharp(input)
.negate({ alpha: false })
.toBuffer();

normalise

normalise([options]) ⇒ Sharp

通过扩展输出图片的亮度以覆盖整个动态范围来增强输出图片的对比度。

¥Enhance output image contrast by stretching its luminance to cover a full dynamic range.

使用基于直方图的方法,采用 1% 到 99% 的默认范围,以降低对极端噪声的敏感度。

¥Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes.

低于 lower 百分位的亮度值将因剪裁为零而曝光不足。通过裁剪到最大像素值,高于 upper 百分位的亮度值将会曝光过度。

¥Luminance values below the lower percentile will be underexposed by clipping to zero. Luminance values above the upper percentile will be overexposed by clipping to the max pixel value.

参数类型默认描述
[options]Object
[options.lower]number1百分位,低于该百分位的亮度值将曝光不足。
[options.upper]number99百分位,高于该百分位的亮度值将会曝光过度。

示例

¥Example

const output = await sharp(input)
.normalise()
.toBuffer();

示例

¥Example

const output = await sharp(input)
.normalise({ lower: 0, upper: 100 })
.toBuffer();

normalize

normalize([options]) ⇒ Sharp

标准化的替代拼写。

¥Alternative spelling of normalise.

参数类型默认描述
[options]Object
[options.lower]number1百分位,低于该百分位的亮度值将曝光不足。
[options.upper]number99百分位,高于该百分位的亮度值将会曝光过度。

示例

¥Example

const output = await sharp(input)
.normalize()
.toBuffer();

clahe

clahe(options) ⇒ Sharp

执行对比度限制自适应直方图均衡 CLAHE

¥Perform contrast limiting adaptive histogram equalization CLAHE.

一般来说,这会通过显示较暗的细节来增强图片的清晰度。

¥This will, in general, enhance the clarity of the image by bringing out darker details.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

自从:0.28.3

¥Since: 0.28.3

参数类型默认描述
optionsObject
options.widthnumber搜索窗口的整体宽度(以像素为单位)。
options.heightnumber搜索窗口的整体高度(以像素为单位)。
[options.maxSlope]number3亮度的积分级别,介于 0 和 100 之间,其中 0 禁用对比度限制。

示例

¥Example

const output = await sharp(input)
.clahe({
width: 3,
height: 3,
})
.toBuffer();

convolve

convolve(kernel) ⇒ Sharp

将图片与指定的内核进行卷积。

¥Convolve the image with the specified kernel.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

参数类型默认描述
kernelObject
kernel.widthnumber内核的宽度(以像素为单位)。
kernel.heightnumber内核的高度(以像素为单位)。
kernel.kernelArray.<number>长度为 width*height 的数组,包含内核值。
[kernel.scale]numbersum内核的比例(以像素为单位)。
[kernel.offset]number0内核的偏移量(以像素为单位)。

示例

¥Example

sharp(input)
.convolve({
width: 3,
height: 3,
kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1]
})
.raw()
.toBuffer(function(err, data, info) {
// data contains the raw pixel data representing the convolution
// of the input image with the horizontal Sobel operator
});

threshold

threshold([threshold], [options]) ⇒ Sharp

任何大于或等于阈值的像素值将被设置为 255,否则将被设置为 0。

¥Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

参数类型默认描述
[threshold]number1280-255 范围内的值,表示应用阈值的级别。
[options]Object
[options.greyscale]Booleantrue转换为单通道灰度。
[options.grayscale]Booleantrue灰度的替代拼写。

boolean

布尔值(操作数,运算符,[选项])⇒ Sharp

¥boolean(operand, operator, [options]) ⇒ Sharp

对操作数图片执行按位布尔运算。

¥Perform a bitwise boolean operation with operand image.

此操作创建一个输出图片,其中每个像素都是输入图片的相应像素之间选定的按位布尔值 operation 的结果。

¥This operation creates an output image where each pixel is the result of the selected bitwise boolean operation between the corresponding pixels of the input images.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

参数类型描述
operandBuffer | string包含图片数据的缓冲区或包含图片文件路径的字符串。
operatorstringandoreor 之一执行按位运算,如 C 逻辑运算符 &、`and^` respectively.
[options]Object
[options.raw]Object描述使用原始像素数据时的操作数。
[options.raw.width]number
[options.raw.height]number
[options.raw.channels]number

linear

linear([a], [b]) ⇒ Sharp

将线性公式 a * 输入 + b 应用于图片以调整图片级别。

¥Apply the linear formula a * input + b to the image to adjust image levels.

当提供单个编号时,它将用于所有图片通道。当提供数字数组时,数组长度必须与通道数匹配。

¥When a single number is provided, it will be used for all image channels. When an array of numbers is provided, the array length must match the number of channels.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

参数类型默认描述
[a]number | Array.<number>[]multiplier
[b]number | Array.<number>[]offset

示例

¥Example

await sharp(input)
.linear(0.5, 2)
.toBuffer();

示例

¥Example

await sharp(rgbInput)
.linear(
[0.25, 0.5, 0.75],
[150, 100, 50]
)
.toBuffer();

recomb

recomb(inputMatrix) ⇒ Sharp

将图片与指定的矩阵重新组合。

¥Recombine the image with the specified matrix.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

自从:0.21.1

¥Since: 0.21.1

参数类型描述
inputMatrixArray.<Array.<number>>3x3 或 4x4 重组矩阵

示例

¥Example

sharp(input)
.recomb([
[0.3588, 0.7044, 0.1368],
[0.2990, 0.5870, 0.1140],
[0.2392, 0.4696, 0.0912],
])
.raw()
.toBuffer(function(err, data, info) {
// data contains the raw pixel data after applying the matrix
// With this example input, a sepia filter has been applied
});

modulate

modulate([options]) ⇒ Sharp

使用亮度、饱和度、色调旋转和亮度来变换图片。亮度和明度都与亮度有关,不同之处在于亮度是乘法,而明度是加法。

¥Transforms the image using brightness, saturation, hue rotation, and lightness. Brightness and lightness both operate on luminance, with the difference being that brightness is multiplicative whereas lightness is additive.

自从:0.22.1

¥Since: 0.22.1

参数类型描述
[options]Object
[options.brightness]number亮度倍增器
[options.saturation]number饱和度乘数
[options.hue]number色调旋转度数
[options.lightness]number亮度加数

示例

¥Example

// increase brightness by a factor of 2
const output = await sharp(input)
.modulate({
brightness: 2
})
.toBuffer();

示例

¥Example

// hue-rotate by 180 degrees
const output = await sharp(input)
.modulate({
hue: 180
})
.toBuffer();

示例

¥Example

// increase lightness by +50
const output = await sharp(input)
.modulate({
lightness: 50
})
.toBuffer();

示例

¥Example

// decrease brightness and saturation while also hue-rotating by 90 degrees
const output = await sharp(input)
.modulate({
brightness: 0.5,
saturation: 0.5,
hue: 90,
})
.toBuffer();