构造器
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 或原始像素图像数据,则可以将其流式传输到对象中。optionsObject ? 如果存在,则为具有可选属性的Object。options.failOnErrorBoolean?默认情况下,会暂停处理并在加载无效图像时引发错误。如果您希望“尽力而为”解码图像,即使数据已损坏或无效,也可以将该标志设置为false。(可选,默认true)options.limitInputPixels(number | boolean )不要处理像素数(宽x高)超过此限制的输入图像。假设包含在输入元数据中的图像尺寸是可以信任的。像素数整数,零或false以消除限制,为true时使用默认限制268402689(0x3FFF x 0x3FFF)。(可选,默认268402689)options.unlimitedBoolean 将此设置为true以删除有助于防止内存耗尽的安全功能(SVG、PNG)。(可选,默认false)options.sequentialReadBoolean 将此设置为true在可能的情况下使用顺序访问而不是随机访问。这样可以减少内存使用量,并可以提高某些系统的性能。(可选,默认false)options.densityNumber 表示为DPI在矢量图像范围为1〜100000(可选,默认72)options.pagesnumber 页数以提取多页输入(GIF,TIFF,PDF),使用-1为所有页面。(可选,默认1)options.pagenumber 从多个页面输入(GIF,TIFF,PDF)开始提取的页面编号,从零开始。(可选,默认0)options.subifdnumber subIFD(子图像文件目录)为 OME-TIFF 提取,默认为主图像。 (可选,默认-1)options.levelnumber 从多级输入(OpenSlide)中提取的数字 ,从零开始。(可选,默认0)options.animatedboolean 设置为true读取动画图像的所有帧/页面(等同于设置pages为-1)。(可选,默认false)options.rawobject ?描述原始像素输入图像数据。请参阅raw()中的像素顺序。options.raw.widthnumber ? 像素宽(整数)。options.raw.heightnumber ? 像素高(整数)。options.raw.channelsnumber ? 通道数(整数),介于 1 和 4 之间。options.raw.premultipliedBoolean ? 指定原始输入已经被预乘,设置为true以避免对图像进行锐利的预乘。 (可选,默认为false)
options.createobject ?描述要创建的新图像。options.create.widthnumber ? 像素宽(整数)。options.create.heightnumber ? 像素高(整数)。options.create.channelsnumber ? 通道数(整数), 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)? 生成的噪波中像素的标准偏差。
例子
// 压缩图片为宽300高200像素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 readableStream, 从只读流中读取图片// resize to 300 pixels wide, 压缩宽度为300像素// emit an 'info' event with calculated dimensions, 发出具有计算尺寸的“信息”事件// and finally write image data to writableStream, 最后将图像数据写入流var transformer = sharp().resize(300).on('info', function(info) {console.log('Image height is ' + info.height);});readableStream.pipe(transformer).pipe(writableStream);
// Create a blank 300x200 PNG image of semi-transluent red pixels, 创建一张300x200的半透明红色图片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, 将动画 GIF 转换为动画 WebPawait sharp('in.gif', { animated: true }).toFile('out.webp');
// Read a raw array of pixels and save it to a png 读取原始像素数组并将其保存到 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');
// Generate RGB Gaussian noise 生成 RGB 高斯噪声await sharp({create: {width: 300,height: 200,channels: 3,noise: {type: 'gaussian',mean: 128,sigma: 30}}}).toFile('noise.png');
- 无效参数引发错误
返回Sharp对象
克隆Clone
对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 completeconst fs = require("fs");const got = require("got");const sharpStream = sharp({failOnError: false});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#gotstreamurl-options](https://github.com/sindresorhus/got#gotstreamurl-options)got.stream("[https://www.example.com/some-file.jpg](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) {}});
返回 Sharp 对象
