Skip to content

构造函数

Sharp

Sharp

触发:Sharp#event:infoSharp#event:warning

¥Emits: Sharp#event:info, Sharp#event:warning\

new

new Sharp([input], [options])

用于创建 sharp 实例的构造函数工厂,进一步的方法链接到该实例。

¥Constructor factory to create an instance of sharp, to which further methods are chained.

JPEG、PNG、WebP、GIF、AVIF 或 TIFF 格式的图片数据可以从此对象中流式传输。使用基于流的输出时,可从 info 事件获取派生属性。

¥JPEG, PNG, WebP, GIF, AVIF or TIFF format image data can be streamed out from this object. When using Stream based output, derived attributes are available from the info event.

处理过程中遇到的非关键问题将作为 warning 事件触发。

¥Non-critical problems encountered during processing are emitted as warning events.

实现 stream.Duplex 类。

¥Implements the stream.Duplex class.

当加载超过一页/帧的动画图片时,这些图片将组合为垂直堆叠的 “卫生纸” 图片,其中总高度为 pageHeight 乘以 pages 的数量。

¥When loading more than one page/frame of an animated image, these are combined as a vertically-stacked “toilet roll” image where the overall height is the pageHeight multiplied by the number of pages.

抛出:

¥Throws:

  • Error 无效参数

    ¥Error Invalid parameters

参数类型默认描述
[input]Buffer | ArrayBuffer | Uint8Array | Uint8ClampedArray | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array | string | Array如果存在,可以是包含 JPEG、PNG、WebP、AVIF、GIF、SVG 或 TIFF 图片数据的 Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray,或者包含原始像素图片数据的 TypedArray,或者包含 JPEG 文件系统路径的字符串, PNG、WebP、AVIF、GIF、SVG 或 TIFF 图片文件。可以提供输入数组,这些输入将连接在一起。JPEG、PNG、WebP、AVIF、GIF、SVG、TIFF 或原始像素图片数据(当不存在时)可以流式传输到对象中。
[options]Object如果存在,则为具有可选属性的对象。
[options.failOn]string“‘warning‘“何时中止无效像素数据的处理,其中之一(按敏感度顺序,从最小到最大):‘none’、‘truncated’、‘error’、‘warning’。较高的水平意味着较低的水平。无效的元数据将始终中止。
[options.limitInputPixels]number | boolean268402689请勿处理像素数(宽度 x 高度)超过此限制的输入图片。假设输入元数据中包含的图片尺寸是可信的。整数像素数,零或 false 表示删除限制,true 表示使用默认限制 268402689 (0x3FFF x 0x3FFF)。
[options.unlimited]booleanfalse将其设置为 true 可删除有助于防止内存耗尽的安全功能(JPEG、PNG、SVG、HEIF)。
[options.autoOrient]booleanfalse将其设置为 true 以旋转/翻转图片以匹配 EXIF Orientation(如果有)。
[options.sequentialRead]booleantrue将其设置为 false 以使用随机访问而不是顺序读取。某些操作会自动执行此操作。
[options.density]number72表示矢量图片 DPI 的数字,范围为 1 到 100000。
[options.ignoreIcc]numberfalse是否应忽略嵌入的 ICC 配置文件(如果有)。
[options.pages]number1为多页输入(GIF、WebP、TIFF)提取的页数,对所有页使用 -1。
[options.page]number0多页输入(GIF、WebP、TIFF)开始提取的页码,从零开始。
[options.subifd]number-1用于提取 OME-TIFF 的 subIFD(子图片文件目录),默认为主图片。
[options.level]number0level 从多级输入(OpenSlide)中提取,从零开始。
[options.pdfBackground]string | ObjectPDF 部分透明时使用的背景颜色。由 color 模块解析以提取红色、绿色、蓝色和 alpha 的值。需要使用全局安装的 libvips,该 libvips 编译时支持 PDFium、Poppler、ImageMagick 或 GraphicsMagick。
[options.animated]booleanfalse设置为 true 可读取动画图片(GIF、WebP、TIFF)的所有帧/页面,相当于设置 pages-1
[options.raw]Object描述原始像素输入图片数据。有关像素排序,请参阅 raw()
[options.raw.width]number整数像素宽。
[options.raw.height]number整数像素高。
[options.raw.channels]number整数通道数,介于 1 和 4 之间。
[options.raw.premultiplied]boolean指定原始输入已经预乘,设置为 true 以避免锐利预乘图片。(可选,默认 false
[options.create]Object描述要创建的新图片。
[options.create.width]number整数像素宽。
[options.create.height]number整数像素高。
[options.create.channels]number整数通道数,3 (RGB) 或 4 (RGBA)。
[options.create.background]string | Objectcolor 模块解析以提取红色、绿色、蓝色和 alpha 的值。
[options.create.noise]Object描述要创建的噪声。
[options.create.noise.type]string产生的噪声类型,目前仅支持 gaussian
[options.create.noise.mean]number生成噪声中的像素平均值。
[options.create.noise.sigma]number生成的噪声中像素的标准偏差。
[options.text]Object描述要创建的新文本图片。
[options.text.text]string要渲染为 UTF-8 字符串的文本。它可以包含 Pango 标记,例如 <i>Le</i>Monde
[options.text.font]string用于渲染的字体名称。
[options.text.fontfile]stringfont 可以使用的字体文件的绝对文件系统路径。
[options.text.width]number0自动换行的像素整数。比此宽的文本行将在字边界处断开。
[options.text.height]number0高像素的最大整数个数。定义后,dpi 将被忽略,文本将自动适应 widthheight 定义的像素分辨率。如果未指定 width 或设置为 0,则将被忽略。
[options.text.align]string“‘left‘“多行文本的对齐方式('left''centre''center''right')。
[options.text.justify]booleanfalse将其设置为 true 可以对文本应用对齐方式。
[options.text.dpi]number72渲染文本的分辨率(大小)。如果指定了 height,则不生效。
[options.text.rgba]booleanfalse将其设置为 true 以启用 RGBA 输出。这对于彩色表情符号渲染或支持 <span foreground="red">Red!</span> 等 pango 标记功能非常有用。
[options.text.spacing]number0文本行高(以磅为单位)。如果未指定,将使用字体行高。
[options.text.wrap]string“‘word‘“提供宽度时的自动换行样式,其中之一:‘word’、‘char’、‘word-char’(首选单词,后备至字符)或 ‘none’。
[options.join]Object描述应如何连接输入图片数组。
[options.join.across]number1水平连接的图片数量。
[options.join.animated]booleanfalse将其设置为 true 以将图片连接为动画图片。
[options.join.shim]number0连接的图片之间插入的像素数。
[options.join.background]string | Objectcolor 模块解析以提取红色、绿色、蓝色和 alpha 的值。
[options.join.halign]string“‘left‘“水平连接图片的水平对齐样式('left''centre''center''right')。
[options.join.valign]string“‘top‘“垂直连接图片的垂直对齐样式('top''centre''center''bottom')。

示例

¥Example

sharp('input.jpg')
.resize(300, 200)
.toFile('output.jpg', function(err) {
// output.jpg is a 300 pixels wide and 200 pixels high image
// containing a scaled and cropped version of input.jpg
});

示例

¥Example

// Read image data from remote URL,
// resize to 300 pixels wide,
// emit an 'info' event with calculated dimensions
// and finally write image data to writableStream
const { body } = fetch('https://...');
const readableStream = Readable.fromWeb(body);
const transformer = sharp()
.resize(300)
.on('info', ({ height }) => {
console.log(`Image height is ${height}`);
});
readableStream.pipe(transformer).pipe(writableStream);

示例

¥Example

// Create a blank 300x200 PNG image of semi-translucent red pixels
sharp({
create: {
width: 300,
height: 200,
channels: 4,
background: { r: 255, g: 0, b: 0, alpha: 0.5 }
}
})
.png()
.toBuffer()
.then( ... );

示例

¥Example

// Convert an animated GIF to an animated WebP
await sharp('in.gif', { animated: true }).toFile('out.webp');

示例

¥Example

// Read a raw array of pixels and save it to a png
const input = Uint8Array.from([255, 255, 255, 0, 0, 0]); // or Uint8ClampedArray
const image = sharp(input, {
// because the input does not contain its dimensions or how many channels it has
// we need to specify it in the constructor options
raw: {
width: 2,
height: 1,
channels: 3
}
});
await image.toFile('my-two-pixels.png');

示例

¥Example

// Generate RGB Gaussian noise
await sharp({
create: {
width: 300,
height: 200,
channels: 3,
noise: {
type: 'gaussian',
mean: 128,
sigma: 30
}
}
}).toFile('noise.png');

示例

¥Example

// Generate an image from text
await sharp({
text: {
text: 'Hello, world!',
width: 400, // max width
height: 300 // max height
}
}).toFile('text_bw.png');

示例

¥Example

// Generate an rgba image from text using pango markup and font
await sharp({
text: {
text: '<span foreground="red">Red!</span><span background="cyan">blue</span>',
font: 'sans',
rgba: true,
dpi: 300
}
}).toFile('text_rgba.png');

示例

¥Example

// Join four input images as a 2x2 grid with a 4 pixel gutter
const data = await sharp(
[image1, image2, image3, image4],
{ join: { across: 2, shim: 4 } }
).toBuffer();

示例

¥Example

// Generate a two-frame animated image from emoji
const images = ['😀', '😛'].map(text => ({
text: { text, width: 64, height: 64, channels: 4, rgba: true }
}));
await sharp(images, { join: { animated: true } }).toFile('out.gif');

clone

clone() ⇒ Sharp

获取 Sharp 实例的 “snapshot”,返回一个新实例。克隆实例继承其父实例的输入。这允许多个输出流以及多个处理管道共享单个输入流。

¥Take a “snapshot” of the Sharp instance, returning a new instance. Cloned instances inherit the input of their parent instance. This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream.

示例

¥Example

const pipeline = sharp().rotate();
pipeline.clone().resize(800, 600).pipe(firstWritableStream);
pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 }).pipe(secondWritableStream);
readableStream.pipe(pipeline);
// firstWritableStream receives auto-rotated, resized readableStream
// secondWritableStream receives auto-rotated, extracted region of readableStream

示例

¥Example

// Create a pipeline that will download an image, resize it and format it to different files
// Using Promises to know when the pipeline is complete
const fs = require("fs");
const got = require("got");
const sharpStream = sharp({ failOn: 'none' });
const promises = [];
promises.push(
sharpStream
.clone()
.jpeg({ quality: 100 })
.toFile("originalFile.jpg")
);
promises.push(
sharpStream
.clone()
.resize({ width: 500 })
.jpeg({ quality: 80 })
.toFile("optimized-500.jpg")
);
promises.push(
sharpStream
.clone()
.resize({ width: 500 })
.webp({ quality: 80 })
.toFile("optimized-500.webp")
);
// https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md
got.stream("https://www.example.com/some-file.jpg").pipe(sharpStream);
Promise.all(promises)
.then(res => { console.log("Done!", res); })
.catch(err => {
console.error("Error processing files, let's clean it up", err);
try {
fs.unlinkSync("originalFile.jpg");
fs.unlinkSync("optimized-500.jpg");
fs.unlinkSync("optimized-500.webp");
} catch (e) {}
});