教程菜单 本页目录

构造函数

Sharp

Sharp

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

new

new Sharp([input], [options])

构造函数工厂用于创建 sharp 的实例,其他方法将链接到该实例。

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

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

实现 stream.Duplex 类。

当加载多页/帧动画图像时,这些图像将组合为垂直堆叠的“卫生纸卷”图像,其总高度为 [pageHeight] 乘以页数。

Throws

  • 错误 参数无效
参数类型默认描述
[input]Buffer | ArrayBuffer | Uint8Array | Uint8ClampedArray | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array | string如果存在,可以是包含 JPEG、PNG、WebP、AVIF、GIF 的 Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray, SVG 或 TIFF 图像数据,或包含原始像素图像数据的 TypedArray,或包含 JPEG、PNG、WebP、AVIF、GIF、SVG 或 TIFF 图像文件的文件系统路径的字符串。JPEG、PNG、WebP、AVIF、GIF、SVG、TIFF 或原始像素图像数据在不存在时可以流式传输到对象中。
[options]Object如果存在,则为具有可选属性的对象。
[options.failOn]string"'warning'"何时中止对无效像素数据的处理,以下之一(按敏感度从低到高排序):'无'、'截断'、'错误'、'警告'。级别越高,级别越低。无效元数据将始终中止。
[options.limitInputPixels]number | boolean268402689不要处理像素数(宽度 x 高度)超过此限制的输入图像。假设输入元数据中包含的图像尺寸是可信的。整数像素数,零或 false 表示删除限制,true 表示使用默认限制 268402689(0x3FFF x 0x3FFF)。
[options.unlimited]booleanfalse将其设置为 true 可删除有助于防止内存耗尽的安全功能(JPEG、PNG、SVG、HEIF)。
[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]number0从多级输入(OpenSlide)中提取的级别,从零开始。
[options.animated]booleanfalse设置为 true 可读取动画图像(GIF、WebP、TIFF)的所有帧/页面,相当于将页面设置为 -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 | Object由颜色模块解析以提取红色、绿色、蓝色和 alpha 的值。
[options.create.noise]Object描述要创建的噪声。
[options.create.noise.type]string生成的噪声类型,目前仅支持高斯。
[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]string字体可以使用的字体文件的绝对文件系统路径。
[options.text.width]number0要换行的整数像素数。比此宽度更宽的文本行将在单词边界处断开。
[options.text.height]number0最大整数像素高。定义后,dpi 将被忽略,文本将自动适应宽度和高度定义的像素分辨率。如果未指定宽度或将其设置为 0,将被忽略。
[options.text.align]string"'left'"多行文本的对齐样式(“左”、“中”、“居中”、“右”)。
[options.text.justify]booleanfalse将其设置为 true 以将对齐应用于文本。
[options.text.dpi]number72呈现文本的分辨率(大小)。如果指定了高度,则不起作用。
[options.text.rgba]booleanfalse将其设置为 true 以启用 RGBA 输出。这对于彩色表情符号渲染或支持 pango 标记功能(如 <span foreground="red">Red!</span>)非常有用。
[options.text.spacing]number0文本行高(以磅为单位)。如果未指定,将使用字体行高。
[options.text.wrap]string"'word'"提供宽度时的自动换行样式,可以是以下之一:'word'、'char'、'word-char'(首选 word,后备为 char)或'none'。

示例

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

示例

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

示例

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

示例

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

示例

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

示例

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

示例

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

示例

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

clone

clone() ⇒ Sharp

对 Sharp 实例进行“快照”,返回一个新实例。克隆的实例继承其父实例的输入。这允许多个输出流,因此多个处理管道可以共享单个输入流。

示例

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

示例

// 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) {}
  });
本页目录