构造器

Sharp

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

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

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

实现了stream.Duplex 类。

参数

  • input (Buffer | Uint8Array | Uint8ClampedArray | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array | string )? 如果存在,可以是包含 JPEG、PNG、WebP、AVIF、GIF、SVG 或 TIFF 图像数据的 Buffer / Uint8Array / Uint8ClampedArray,或包含原始像素图像数据的 TypedArray,或包含 JPEG、PNG、WebP、AVIF、GIF、SVG 的文件系统路径字符串, 或 TIFF 图像文件。 JPEG、PNG、WebP、AVIF、GIF、SVG、TIFF 或原始像素图像数据,则可以将其流式传输到对象中。
  • options Object 如果存在,则为具有可选属性的Object。
    • options.failOnError Boolean?默认情况下,会暂停处理并在加载无效图像时引发错误。如果您希望“尽力而为”解码图像,即使数据已损坏或无效,也可以将该标志设置为false。(可选,默认true
    • options.limitInputPixels number | boolean 不要处理像素数(宽x高)超过此限制的输入图像。假设包含在输入元数据中的图像尺寸是可以信任的。像素数整数,零或false以消除限制,为true时使用默认限制268402689(0x3FFF x 0x3FFF)。(可选,默认268402689
    • options.unlimited Boolean 将此设置为 true 以删除有助于防止内存耗尽的安全功能(SVG、PNG)。(可选,默认false
    • options.sequentialRead Boolean 将此设置为true在可能的情况下使用顺序访问而不是随机访问。这样可以减少内存使用量,并可以提高某些系统的性能。(可选,默认false
    • options.density Number 表示为DPI在矢量图像范围为1〜100000(可选,默认72
    • options.pages number 页数以提取多页输入(GIF,TIFF,PDF),使用-1为所有页面。(可选,默认1
    • options.page number 从多个页面输入(GIF,TIFF,PDF)开始提取的页面编号,从零开始。(可选,默认0
    • options.subifd number subIFD(子图像文件目录)为 OME-TIFF 提取,默认为主图像。 (可选,默认 -1
    • options.level number 从多级输入(OpenSlide)中提取的数字 ,从零开始。(可选,默认0
    • options.animated boolean 设置为true读取动画图像的所有帧/页面(等同于设置pages-1)。(可选,默认false
    • 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)?由颜色color 模块解析以提取红色,绿色,蓝色和Alpha的值。
      • options.create.noise (object)? 描述要创建的噪音。
        • options.create.noise.type (string)? 生成的噪波类型,目前仅支持高斯(gaussian)
        • options.create.noise.mean (number)? 生成的噪波中的像素平均值。
        • options.create.noise.sigma (number)? 生成的噪波中像素的标准偏差。

例子

  1. // 压缩图片为宽300高200像素
  2. sharp('input.jpg')
  3. .resize(300, 200)
  4. .toFile('output.jpg', function(err) {
  5. // output.jpg is a 300 pixels wide and 200 pixels high image
  6. // containing a scaled and cropped version of input.jpg
  7. });
  1. // Read image data from readableStream, 从只读流中读取图片
  2. // resize to 300 pixels wide, 压缩宽度为300像素
  3. // emit an 'info' event with calculated dimensions, 发出具有计算尺寸的“信息”事件
  4. // and finally write image data to writableStream, 最后将图像数据写入流
  5. var transformer = sharp()
  6. .resize(300)
  7. .on('info', function(info) {
  8. console.log('Image height is ' + info.height);
  9. });
  10. readableStream.pipe(transformer).pipe(writableStream);
  1. // Create a blank 300x200 PNG image of semi-transluent red pixels, 创建一张300x200的半透明红色图片
  2. sharp({
  3. create: {
  4. width: 300,
  5. height: 200,
  6. channels: 4,
  7. background: { r: 255, g: 0, b: 0, alpha: 0.5 }
  8. }
  9. })
  10. .png()
  11. .toBuffer()
  12. .then( ... );
  1. // Convert an animated GIF to an animated WebP, 将动画 GIF 转换为动画 WebP
  2. await sharp('in.gif', { animated: true }).toFile('out.webp');
  1. // Read a raw array of pixels and save it to a png 读取原始像素数组并将其保存到 png
  2. const input = Uint8Array.from([255, 255, 255, 0, 0, 0]); // or Uint8ClampedArray
  3. const image = sharp(input, {
  4. // because the input does not contain its dimensions or how many channels it has 因为输入不包含它的尺寸或它有多少通道
  5. // we need to specify it in the constructor options 我们需要在构造函数选项中指定它
  6. raw: {
  7. width: 2,
  8. height: 1,
  9. channels: 3
  10. }
  11. });
  12. await image.toFile('my-two-pixels.png');
  1. // Generate RGB Gaussian noise 生成 RGB 高斯噪声
  2. await sharp({
  3. create: {
  4. width: 300,
  5. height: 200,
  6. channels: 3,
  7. noise: {
  8. type: 'gaussian',
  9. mean: 128,
  10. sigma: 30
  11. }
  12. }
  13. }).toFile('noise.png');

返回Sharp对象

克隆Clone

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

例子

  1. const pipeline = sharp().rotate();
  2. pipeline.clone().resize(800, 600).pipe(firstWritableStream);
  3. pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 }).pipe(secondWritableStream);
  4. readableStream.pipe(pipeline);
  5. // firstWritableStream receives auto-rotated, resized readableStream
  6. // secondWritableStream receives auto-rotated, extracted region of readableStream
  1. // Create a pipeline that will download an image, resize it and format it to different files
  2. // Using Promises to know when the pipeline is complete
  3. const fs = require("fs");
  4. const got = require("got");
  5. const sharpStream = sharp({
  6. failOnError: false
  7. });
  8. const promises = [];
  9. promises.push(
  10. sharpStream
  11. .clone()
  12. .jpeg({ quality: 100 })
  13. .toFile("originalFile.jpg")
  14. );
  15. promises.push(
  16. sharpStream
  17. .clone()
  18. .resize({ width: 500 })
  19. .jpeg({ quality: 80 })
  20. .toFile("optimized-500.jpg")
  21. );
  22. promises.push(
  23. sharpStream
  24. .clone()
  25. .resize({ width: 500 })
  26. .webp({ quality: 80 })
  27. .toFile("optimized-500.webp")
  28. );
  29. // [https://github.com/sindresorhus/got#gotstreamurl-options](https://github.com/sindresorhus/got#gotstreamurl-options)
  30. got.stream("[https://www.example.com/some-file.jpg](https://www.example.com/some-file.jpg)").pipe(sharpStream);
  31. Promise.all(promises)
  32. .then(res => { console.log("Done!", res); })
  33. .catch(err => {
  34. console.error("Error processing files, let's clean it up", err);
  35. try {
  36. fs.unlinkSync("originalFile.jpg");
  37. fs.unlinkSync("optimized-500.jpg");
  38. fs.unlinkSync("optimized-500.webp");
  39. } catch (e) {}
  40. });

返回 Sharp 对象