构造函数
Sharp
Emits: Sharp#event:info, Sharp#event:warning
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.
投掷:
错误参数无效
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| [input] | 缓冲区 |数组缓冲区 |Uint8数组 |Uint8Clamped数组 |Int8数组 |Uint16数组 |整16数组 |Uint32数组 |整数组 |float32数组 |float64数组 |字符串 |数组 |
如果存在,可以是包含 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’。更高的级别包含更低的级别。无效的元数据总是会中止处理。对不受信任的输入建议使用默认的 ‘warning’ 级别。 |
| [options.limitInputPixels] | 数字 |布尔 |
268402689 |
不要处理像素数(宽度 x 高度)超过此限制的输入图片。假设输入元数据中包含的图片尺寸是可信的。像素数为整数,零或假以消除限制,真以启用默认限制268402689(0x3FFF x 0x3FFF)。 |
| [options.limitInputChannels] | 数字 |布尔 |
5 |
请勿处理通道数超过此限制的输入图片。假设图片元数据可信。整数通道数,0或false以消除限制,true以使用默认限制5。 |
| [options.unlimited] | boolean |
false |
将此设置为 true 以移除帮助防止内存耗尽的安全功能(JPEG、PNG、SVG、HEIF)。 |
| [options.autoOrient] | boolean |
false |
设置为 true 以根据 EXIF 的 Orientation(如果有的话)旋转/翻转图片。 |
| [options.sequentialRead] | boolean |
true |
将此设置为 false 以使用随机访问而不是顺序读取。有些操作会自动执行此操作。 |
| [options.density] | 数字 |
72 |
用于渲染 SVG 和 PDF 图片的 DPI,范围是 1 到 100000。 |
| [options.ignoreIcc] | number |
false |
是否应该忽略嵌入的 ICC 配置文件(如果有的话)。 |
| [options.pages] | 数字 |
1 |
要从多页输入(GIF、WebP、TIFF)中提取的页数,使用 -1 表示全部页。 |
| [options.page] | number |
0 |
对于多页输入(GIF、WebP、TIFF),从哪一页开始提取,页码从零开始。 |
| [options.animated] | 布尔值 |
false |
设置为 true 以读取动画图片(GIF、WebP、TIFF)的所有帧/页面,相当于将 pages 设置为 -1。 |
| [options.raw] | 对象 |
描述原始像素输入图片数据。像素顺序请参见 raw() |
|
| [options.raw.width] | number |
宽度的整数像素数。 | |
| [options.raw.height] | number |
高度的整数像素数。 | |
| [options.raw.channels] | 数字 |
通道的整数数量,介于1到4之间。 | |
| [options.raw.premultiplied] | boolean |
指定原始输入是否已经预乘,如果设置为 true 可以避免对图片进行重复锐化预乘。(可选,默认 false) |
|
| [options.raw.pageHeight] | number |
动态图片每页/每帧的像素高度,必须是 raw.height 的整数倍。 |
|
| [options.create] | Object |
描述要创建的新图片。 | |
| [options.create.width] | number |
宽度的整数像素数。 | |
| [options.create.height] | number |
高度的整数像素数。 | |
| [options.create.channels] | 数字 |
通道的整数数量,可以是 3(RGB)或 4(RGBA)。 | |
| [options.create.background] | 字符串 |对象 |
通过[color](https://www.npmjs.org/package/color)模块解析,提取红、绿、蓝和阿尔法的值。| | |
| [options.create.pageHeight] | number |
动态图片每页/每帧的像素高度,必须是 create.height 的整数倍。 |
|
| [options.create.noise] | Object |
描述要创建的噪音。 | |
| [options.create.noise.type] | 字符串 |
生成噪声的类型,目前只支持 gaussian。 |
|
| [options.create.noise.mean] | number |
128 |
生成噪点中像素的平均值。 |
| [options.create.noise.sigma] | number |
30 |
生成噪点时像素值的标准差。 |
| [options.text] | 对象 |
描述将要创建的新文本图片。 | |
| [options.text.text] | 字符串 |
要作为 UTF-8 字符串渲染的文本。它可以包含 Pango 标记,例如 <i>Le</i>Monde。 |
|
| [options.text.font] | string |
用于渲染的字体名称。 | |
| [options.text.fontfile] | 字符串 |
font 可以使用的字体文件的绝对文件系统路径。 |
|
| [options.text.width] | 数字 |
0 |
用于换行的像素整数。当文本行超过此宽度时,会在单词边界处换行。 |
| [options.text.height] | 数字 |
0 |
最大整数像素高度。定义后,dpi 将被忽略,文本会自动适应由 width 和 height 定义的像素分辨率。如果未指定 width 或设置为 0,则会被忽略。 |
| [options.text.align] | string |
"‘left’" |
多行文本的对齐样式 ('left', 'centre', 'center', 'right')。 |
| [options.text.justify] | 布尔值 |
false |
将此设置为 true 以对文本应用对齐。 |
| [options.text.dpi] | 数字 |
72 |
渲染文本的分辨率(大小)。如果指定了 height,则不会生效。 |
| [options.text.rgba] | boolean |
false |
将其设置为 true 以启用 RGBA 输出。这对于彩色表情符号渲染或支持像 <span foreground="red">Red!</span> 这样的 pango 标记功能很有用。 |
| [options.text.spacing] | 数字 |
0 |
文本行高(以点为单位)。如果未指定,将使用字体的默认行高。 |
| [options.text.wrap] | 字符串 |
"'word'" |
当提供宽度时的文字换行样式,可以是:‘word’(优先单词)、‘char’(按字符)、‘word-char’(优先单词,失败则按字符)或’none’(无换行)。 |
| [options.join] | Object |
描述输入图片数组应如何合并。 | |
| [options.join.across] | 数字 |
1 |
要横向合并的图片数量。 |
| [options.join.animated] | boolean |
false |
将此设置为 true 以将图片合成为动画图片。 |
| [options.join.shim] | 数字 |
0 |
在合并的图片之间插入的像素数。 |
| [options.join.background] | 字符串 |对象 |
由[color](https://www.npmjs.org/package/color)模块解析,提取红、绿、蓝和alpha的值。| | |
| [options.join.halign] | 字符串 |
"‘left’" |
水平排列的图片的水平对齐样式('left'、'centre'、'center'、'right')。 |
| [options.join.valign] | 字符串 |
"‘top’" |
垂直拼接图片的垂直对齐样式 ('top', 'centre', 'center', 'bottom')。 |
| [options.tiff] | Object |
描述 TIFF 特定选项。 | |
| [options.tiff.subifd] | 数字 |
-1 |
要从 OME-TIFF 提取的子图片文件目录,默认为主图片。 |
| [options.svg] | 对象 |
描述特定于 SVG 的选项。 | |
| [options.svg.stylesheet] | 字符串 |
SVG 输入的自定义 CSS,会在 CSS 层叠中以用户来源应用。 | |
| [options.svg.highBitdepth] | boolean |
false |
设置为 true 以使用每通道 32 位(128 位总计)而不是每通道 8 位(32 位总计)RGBA 来渲染 SVG 输入。 |
| [options.pdf] | Object |
描述 PDF 特定选项。需要使用全局安装并编译支持 PDFium、Poppler、ImageMagick 或 GraphicsMagick 的 libvips。 | |
| [options.pdf.background] | 字符串 |对象 |
当PDF部分透明时使用的背景色。通过[color](https://www.npmjs.org/package/color)模块解析以提取红、绿、蓝和Alpha的数值。| | |
| [options.openSlide] | 对象 |
描述 OpenSlide 特定选项。需要使用全局安装并支持 OpenSlide 的 libvips。 | |
| [options.openSlide.level] | number |
0 |
从多级输入中提取的级别,基于零的索引。 |
| [options.jp2] | 对象 |
描述 JPEG 2000 的特定选项。需要使用支持 OpenJPEG 的全局安装 libvips。 | |
| [options.jp2.oneshot] | 布尔值 |
false |
设置为 true 以一次性解码平铺的 JPEG 2000 图片,提高兼容性。 |
示例
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 writableStreamconst { body } = await 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
// Web Streams API, requires Node.js >= 24.15.0import { Duplex } from 'node:stream';
const { body } = await fetch('https://...');const transformer = Duplex.toWeb( sharp().resize(300), { readableType: 'bytes' });body.pipeThrough(transformer).pipeTo(writable);Example
// Create a blank 300x200 PNG image of semi-translucent red pixelssharp({ 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 WebPawait sharp('in.gif', { animated: true }).toFile('out.webp');Example
// Read a raw array of pixels and save it to a pngconst input = Uint8Array.from([255, 255, 255, 0, 0, 0]); // or Uint8ClampedArrayconst 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 noiseawait sharp({ create: { width: 300, height: 200, channels: 3, noise: { type: 'gaussian', mean: 128, sigma: 30 } }}).toFile('noise.png');Example
// Generate an image from textawait 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 fontawait 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 gutterconst data = await sharp( [image1, image2, image3, image4], { join: { across: 2, shim: 4 } }).toBuffer();Example
// Generate a two-frame animated image from emojiconst images = ['😀', '😛'].map(text => ({ text: { text, width: 64, height: 64, channels: 4, rgba: true }}));await sharp(images, { join: { animated: true } }).toFile('out.gif');clone() ⇒
Sharp
获取 Sharp 实例的“快照”,返回一个新的实例。克隆的实例会继承其父实例的输入。这允许多个输出流以及多个处理管道共享同一个输入流。
🌐 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.
示例
// firstWritableStream receives auto-rotated, resized readableStream// secondWritableStream receives auto-rotated, extracted region of readableStream
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);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 sharpStream = sharp();
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"));
const res = await fetch("https://www.example.com/some-file.jpg")Readable.fromWeb(res.body).pipe(sharpStream);await Promise.all(promises);