mirror of
https://github.com/lovell/sharp.git
synced 2025-07-09 10:30:15 +02:00
270 lines
12 KiB
Markdown
270 lines
12 KiB
Markdown
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
|
|
|
|
## Sharp
|
|
|
|
Constructor factory to create an instance of `sharp`, to which further methods are chained.
|
|
|
|
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.
|
|
|
|
Non-critical problems encountered during processing are emitted as `warning` events.
|
|
|
|
Implements the [stream.Duplex][1] class.
|
|
|
|
### Parameters
|
|
|
|
* `input` **([Buffer][2] | [Uint8Array][3] | [Uint8ClampedArray][4] | [Int8Array][5] | [Uint16Array][6] | [Int16Array][7] | [Uint32Array][8] | [Int32Array][9] | [Float32Array][10] | [Float64Array][11] | [string][12])?** if present, can be
|
|
a Buffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or
|
|
a TypedArray containing raw pixel image data, or
|
|
a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file.
|
|
JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present.
|
|
* `options` **[Object][13]?** if present, is an Object with optional attributes.
|
|
|
|
* `options.failOn` **[string][12]** when to abort processing of invalid pixel data, one of (in order of sensitivity): 'none' (least), 'truncated', 'error' or 'warning' (most), highers level imply lower levels, invalid metadata will always abort. (optional, default `'warning'`)
|
|
* `options.limitInputPixels` **([number][14] | [boolean][15])** Do not process input images where the number of pixels
|
|
(width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted.
|
|
An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). (optional, default `268402689`)
|
|
* `options.unlimited` **[boolean][15]** Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). (optional, default `false`)
|
|
* `options.sequentialRead` **[boolean][15]** Set this to `true` to use sequential rather than random access where possible.
|
|
This can reduce memory usage and might improve performance on some systems. (optional, default `false`)
|
|
* `options.density` **[number][14]** number representing the DPI for vector images in the range 1 to 100000. (optional, default `72`)
|
|
* `options.pages` **[number][14]** number of pages to extract for multi-page input (GIF, WebP, AVIF, TIFF, PDF), use -1 for all pages. (optional, default `1`)
|
|
* `options.page` **[number][14]** page number to start extracting from for multi-page input (GIF, WebP, AVIF, TIFF, PDF), zero based. (optional, default `0`)
|
|
* `options.subifd` **[number][14]** subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. (optional, default `-1`)
|
|
* `options.level` **[number][14]** level to extract from a multi-level input (OpenSlide), zero based. (optional, default `0`)
|
|
* `options.animated` **[boolean][15]** Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). (optional, default `false`)
|
|
* `options.raw` **[Object][13]?** describes raw pixel input image data. See `raw()` for pixel ordering.
|
|
|
|
* `options.raw.width` **[number][14]?** integral number of pixels wide.
|
|
* `options.raw.height` **[number][14]?** integral number of pixels high.
|
|
* `options.raw.channels` **[number][14]?** integral number of channels, between 1 and 4.
|
|
* `options.raw.premultiplied` **[boolean][15]?** specifies that the raw input has already been premultiplied, set to `true`
|
|
to avoid sharp premultiplying the image. (optional, default `false`)
|
|
* `options.create` **[Object][13]?** describes a new image to be created.
|
|
|
|
* `options.create.width` **[number][14]?** integral number of pixels wide.
|
|
* `options.create.height` **[number][14]?** integral number of pixels high.
|
|
* `options.create.channels` **[number][14]?** integral number of channels, either 3 (RGB) or 4 (RGBA).
|
|
* `options.create.background` **([string][12] | [Object][13])?** parsed by the [color][16] module to extract values for red, green, blue and alpha.
|
|
* `options.create.noise` **[Object][13]?** describes a noise to be created.
|
|
|
|
* `options.create.noise.type` **[string][12]?** type of generated noise, currently only `gaussian` is supported.
|
|
* `options.create.noise.mean` **[number][14]?** mean of pixels in generated noise.
|
|
* `options.create.noise.sigma` **[number][14]?** standard deviation of pixels in generated noise.
|
|
* `options.text` **[Object][13]?** describes a new text image to be created.
|
|
|
|
* `options.text.text` **[string][12]?** text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.
|
|
* `options.text.font` **[string][12]?** font name to render with.
|
|
* `options.text.fontfile` **[string][12]?** absolute filesystem path to a font file that can be used by `font`.
|
|
* `options.text.width` **[number][14]** integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. (optional, default `0`)
|
|
* `options.text.height` **[number][14]** integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. (optional, default `0`)
|
|
* `options.text.align` **[string][12]** text alignment (`'left'`, `'centre'`, `'center'`, `'right'`). (optional, default `'left'`)
|
|
* `options.text.justify` **[boolean][15]** set this to true to apply justification to the text. (optional, default `false`)
|
|
* `options.text.dpi` **[number][14]** the resolution (size) at which to render the text. Does not take effect if `height` is specified. (optional, default `72`)
|
|
* `options.text.rgba` **[boolean][15]** set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`. (optional, default `false`)
|
|
* `options.text.spacing` **[number][14]** text line height in points. Will use the font line height if none is specified. (optional, default `0`)
|
|
|
|
### Examples
|
|
|
|
```javascript
|
|
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
|
|
});
|
|
```
|
|
|
|
```javascript
|
|
// Read image data from readableStream,
|
|
// resize to 300 pixels wide,
|
|
// 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);
|
|
```
|
|
|
|
```javascript
|
|
// Create a blank 300x200 PNG image of semi-transluent red pixels
|
|
sharp({
|
|
create: {
|
|
width: 300,
|
|
height: 200,
|
|
channels: 4,
|
|
background: { r: 255, g: 0, b: 0, alpha: 0.5 }
|
|
}
|
|
})
|
|
.png()
|
|
.toBuffer()
|
|
.then( ... );
|
|
```
|
|
|
|
```javascript
|
|
// Convert an animated GIF to an animated WebP
|
|
await sharp('in.gif', { animated: true }).toFile('out.webp');
|
|
```
|
|
|
|
```javascript
|
|
// 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');
|
|
```
|
|
|
|
```javascript
|
|
// Generate RGB Gaussian noise
|
|
await sharp({
|
|
create: {
|
|
width: 300,
|
|
height: 200,
|
|
channels: 3,
|
|
noise: {
|
|
type: 'gaussian',
|
|
mean: 128,
|
|
sigma: 30
|
|
}
|
|
}
|
|
}).toFile('noise.png');
|
|
```
|
|
|
|
```javascript
|
|
// Generate an image from text
|
|
await sharp({
|
|
text: {
|
|
text: 'Hello, world!',
|
|
width: 400, // max width
|
|
height: 300 // max height
|
|
}
|
|
}).toFile('text_bw.png');
|
|
```
|
|
|
|
```javascript
|
|
// 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');
|
|
```
|
|
|
|
* Throws **[Error][17]** Invalid parameters
|
|
|
|
Returns **[Sharp][18]** 
|
|
|
|
## clone
|
|
|
|
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.
|
|
|
|
### Examples
|
|
|
|
```javascript
|
|
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
|
|
```
|
|
|
|
```javascript
|
|
// 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) {}
|
|
});
|
|
```
|
|
|
|
Returns **[Sharp][18]** 
|
|
|
|
[1]: http://nodejs.org/api/stream.html#stream_class_stream_duplex
|
|
|
|
[2]: https://nodejs.org/api/buffer.html
|
|
|
|
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array
|
|
|
|
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray
|
|
|
|
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Int8Array
|
|
|
|
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array
|
|
|
|
[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Int16Array
|
|
|
|
[8]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array
|
|
|
|
[9]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Int32Array
|
|
|
|
[10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Float32Array
|
|
|
|
[11]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Float64Array
|
|
|
|
[12]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
|
|
|
|
[13]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
|
|
|
|
[14]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
|
|
|
|
[15]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
|
|
|
|
[16]: https://www.npmjs.org/package/color
|
|
|
|
[17]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
|
|
|
|
[18]: #sharp
|