Compare commits

..

29 Commits

Author SHA1 Message Date
Lovell Fuller
a2d3fa729f Release v0.28.2 2021-05-10 17:59:50 +01:00
Lovell Fuller
cb6811bc47 CI: FreeBSD skip notifications 2021-05-10 17:44:15 +01:00
Lovell Fuller
53c6e80869 Docs: refresh index 2021-05-10 16:03:40 +01:00
Lovell Fuller
e71dca586c Bump devDeps 2021-05-10 16:03:08 +01:00
Lovell Fuller
b3cd48db5f Docs: add section about cross-platform installation 2021-05-10 14:41:28 +01:00
Sebastian
476448b9d4 Install: allow cross-libc via sharp-install-force flag (#2692) 2021-05-10 09:55:20 +01:00
Lovell Fuller
070534df5b Docs: changelog for #2685 2021-05-03 19:48:15 +01:00
Michael Nutt
9a1e8ed574 Add premultiplied boolean flag for raw pixel data input (#2685) 2021-05-03 19:30:37 +01:00
Lovell Fuller
309918a878 Move lint-related tasks to dedicated script entry 2021-05-03 10:04:19 +01:00
Lovell Fuller
cac83b94c1 Bump deps and docs refresh 2021-05-03 10:01:43 +01:00
Lovell Fuller
9c06df08a1 Docs: changelog entry for #2687 2021-05-03 10:01:17 +01:00
Jacob
52e4543d31 Detect empty input and throw a helpful error (#2687) 2021-05-03 09:29:51 +01:00
Lovell Fuller
a688468378 CI: replace Node.js 15 with 16 2021-05-01 16:24:47 +01:00
Lovell Fuller
e1760d64fb Tests: updates so latest libvips master branch passes 2021-05-01 15:25:57 +01:00
Lovell Fuller
84d4e3cf8f Require specific semver functions, aids tree-shaking 2021-04-30 20:42:46 +01:00
Raj Rajhans
f8a76372ad Docs: rewrite sentence to avoid grammatical ambiguity (#2668) 2021-04-21 14:10:24 +01:00
Lovell Fuller
4237f5520f Allow withMetadata to set density #967 2021-04-17 13:46:54 +01:00
Lovell Fuller
8c0c01c702 Docs: changelog entry for #2664 2021-04-17 09:11:48 +01:00
msalettes
9c100830e0 Allow escaped proxy credentials (#2664) 2021-04-17 08:49:07 +01:00
Lovell Fuller
ed5d753b89 Skip shrink-on-load where one dimension <4px #2653 2021-04-07 21:26:16 +01:00
Timo Hausmann
d1ca756bd8 Docs: correct flatten example to use object instead of string (#2654) 2021-04-06 17:21:14 +01:00
Lovell Fuller
16cf9f0ef2 Release v0.28.1 2021-04-05 12:28:16 +01:00
Lovell Fuller
133f69d66c Bump prebuild-install (for sharp_local_prebuilds) 2021-04-05 12:26:28 +01:00
Lovell Fuller
bc60daff9e Allow EXIF metadata to be set/update #650 2021-04-05 11:39:53 +01:00
Lovell Fuller
43a085d1ae Add support for OME-TIFF subIFDs #2557 2021-04-02 08:04:21 +01:00
Lovell Fuller
8c33d0aa56 Allow ensureAlpha to set alpha transparency level #2634 2021-04-01 21:14:06 +01:00
Lovell Fuller
fe0767df13 Install: log errors with more obvious prefix 2021-04-01 16:20:58 +01:00
Lovell Fuller
08a25a0c8f Docs: add animated WebP example #2648 2021-04-01 16:04:46 +01:00
Lovell Fuller
cd410080bd Docs: remove reference to specific Lambda runtime 2021-03-29 20:16:07 +01:00
43 changed files with 972 additions and 450 deletions

View File

@@ -5,6 +5,7 @@ task:
name: FreeBSD 13.0
env:
IGNORE_OSVERSION: yes
skip_notifications: true
prerequisites_script:
- pkg update -f
- pkg upgrade -y

View File

@@ -22,7 +22,7 @@ jobs:
nodejs_version: 14
- os: ubuntu-20.04
container: centos:7
nodejs_version: 15
nodejs_version: 16
- os: ubuntu-20.04
container: node:10-alpine3.11
prebuild: true
@@ -33,7 +33,7 @@ jobs:
- os: ubuntu-20.04
container: node:14-alpine3.13
- os: ubuntu-20.04
container: node:15-alpine3.11
container: node:16-alpine3.11
- os: macos-10.15
nodejs_version: 10
prebuild: true
@@ -42,7 +42,7 @@ jobs:
- os: macos-10.15
nodejs_version: 14
- os: macos-10.15
nodejs_version: 15
nodejs_version: 16
- os: windows-2019
nodejs_version: 10
prebuild: true
@@ -51,7 +51,7 @@ jobs:
- os: windows-2019
nodejs_version: 14
- os: windows-2019
nodejs_version: 15
nodejs_version: 16
steps:
- name: Dependencies (Linux glibc)
if: contains(matrix.container, 'centos')

View File

@@ -43,7 +43,7 @@ jobs:
install: sudo docker exec sharp sh -c "npm install --build-from-source --unsafe-perm"
script: sudo docker exec sharp sh -c "npm test"
- name: "Linux ARM64v8 (Debian 11, glibc 2.29) - Node.js 15"
- name: "Linux ARM64v8 (Debian 11, glibc 2.29) - Node.js 16"
arch: arm64
os: linux
dist: bionic
@@ -53,7 +53,7 @@ jobs:
- sudo docker run -dit --name sharp --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp arm64v8/debian:bullseye
- sudo docker exec sharp sh -c "apt-get update && apt-get install -y build-essential git python3 curl"
- sudo docker exec sharp sh -c "curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -"
- sudo docker exec sharp sh -c "echo 'deb https://deb.nodesource.com/node_15.x sid main' >/etc/apt/sources.list.d/nodesource.list"
- sudo docker exec sharp sh -c "echo 'deb https://deb.nodesource.com/node_16.x sid main' >/etc/apt/sources.list.d/nodesource.list"
- sudo docker exec sharp sh -c "apt-get update && apt-get install -y nodejs"
install: sudo docker exec sharp sh -c "npm install --build-from-source --unsafe-perm"
script: sudo docker exec sharp sh -c "npm test"
@@ -92,14 +92,14 @@ jobs:
install: sudo docker exec sharp sh -c "npm install --build-from-source --unsafe-perm"
script: sudo docker exec sharp sh -c "npm test"
- name: "Linux ARM64v8 (Alpine 3.11, musl 1.1.24) - Node.js 15"
- name: "Linux ARM64v8 (Alpine 3.11, musl 1.1.24) - Node.js 16"
arch: arm64
os: linux
dist: focal
language: shell
before_install:
- sudo chown 0.0 ${PWD}
- sudo docker run -dit --name sharp --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp node:15-alpine3.11
- sudo docker run -dit --name sharp --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp node:16-alpine3.11
- sudo docker exec sharp sh -c "apk add build-base git python3 --update-cache"
install: sudo docker exec sharp sh -c "npm install --build-from-source --unsafe-perm"
script: sudo docker exec sharp sh -c "npm test"

View File

@@ -8,7 +8,7 @@ environment:
prebuild: true
- nodejs_version: "12"
- nodejs_version: "14"
- nodejs_version: "15"
- nodejs_version: "16"
install:
- ps: Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version)
- npm install --build-from-source

View File

@@ -18,23 +18,38 @@ Returns **Sharp**
## ensureAlpha
Ensure alpha channel, if missing. The added alpha channel will be fully opaque. This is a no-op if the image already has an alpha channel.
Ensure the output image has an alpha transparency channel.
If missing, the added alpha channel will have the specified
transparency level, defaulting to fully-opaque (1).
This is a no-op if the image already has an alpha channel.
### Parameters
* `alpha` **[number][1]** alpha transparency level (0=fully-transparent, 1=fully-opaque) (optional, default `1`)
### Examples
```javascript
sharp('rgb.jpg')
// rgba.png will be a 4 channel image with a fully-opaque alpha channel
await sharp('rgb.jpg')
.ensureAlpha()
.toFile('rgba.png', function(err, info) {
// rgba.png is a 4 channel image with a fully opaque alpha channel
});
.toFile('rgba.png')
```
```javascript
// rgba is a 4 channel image with a fully-transparent alpha channel
const rgba = await sharp(rgb)
.ensureAlpha(0)
.toBuffer();
```
* Throws **[Error][2]** Invalid alpha transparency level
Returns **Sharp**
**Meta**
- **since**: 0.21.2
* **since**: 0.21.2
## extractChannel
@@ -42,7 +57,7 @@ Extract a single channel from a multi-channel image.
### Parameters
- `channel` **([number][1] \| [string][2])** zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`.
* `channel` **([number][1] | [string][3])** zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`.
### Examples
@@ -56,7 +71,7 @@ sharp(input)
});
```
- Throws **[Error][3]** Invalid channel
* Throws **[Error][2]** Invalid channel
Returns **Sharp**
@@ -67,19 +82,20 @@ The meaning of the added channels depends on the output colourspace, set with `t
By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.
Channel ordering follows vips convention:
- sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha.
- CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha.
* sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha.
* CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha.
Buffers may be any of the image formats supported by sharp.
For raw pixel input, the `options` object should contain a `raw` attribute, which follows the format of the attribute of the same name in the `sharp()` constructor.
### Parameters
- `images` **([Array][4]&lt;([string][2] \| [Buffer][5])> | [string][2] \| [Buffer][5])** one or more images (file paths, Buffers).
- `options` **[Object][6]** image options, see `sharp()` constructor.
* `images` **([Array][4]<([string][3] | [Buffer][5])> | [string][3] | [Buffer][5])** one or more images (file paths, Buffers).
* `options` **[Object][6]** image options, see `sharp()` constructor.
<!---->
- Throws **[Error][3]** Invalid parameters
* Throws **[Error][2]** Invalid parameters
Returns **Sharp**
@@ -89,7 +105,7 @@ Perform a bitwise boolean operation on all input image channels (bands) to produ
### Parameters
- `boolOp` **[string][2]** one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.
* `boolOp` **[string][3]** one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.
### Examples
@@ -103,15 +119,15 @@ sharp('3-channel-rgb-input.png')
});
```
- Throws **[Error][3]** Invalid parameters
* Throws **[Error][2]** Invalid parameters
Returns **Sharp**
[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array

View File

@@ -7,10 +7,11 @@ An alpha channel may be present and will be unchanged by the operation.
### Parameters
- `rgb` **([string][1] \| [Object][2])** parsed by the [color][3] module to extract chroma values.
* `rgb` **([string][1] | [Object][2])** parsed by the [color][3] module to extract chroma values.
<!---->
- Throws **[Error][4]** Invalid parameter
* Throws **[Error][4]** Invalid parameter
Returns **Sharp**
@@ -25,7 +26,7 @@ An alpha channel may be present, and will be unchanged by the operation.
### Parameters
- `greyscale` **[Boolean][5]** (optional, default `true`)
* `greyscale` **[Boolean][5]** (optional, default `true`)
Returns **Sharp**
@@ -35,7 +36,7 @@ Alternative spelling of `greyscale`.
### Parameters
- `grayscale` **[Boolean][5]** (optional, default `true`)
* `grayscale` **[Boolean][5]** (optional, default `true`)
Returns **Sharp**
@@ -46,7 +47,7 @@ By default output image will be web-friendly sRGB, with additional channels inte
### Parameters
- `colourspace` **[string][1]?** output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...][6]
* `colourspace` **[string][1]?** output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...][6]
### Examples
@@ -57,7 +58,7 @@ await sharp(input)
.toFile('16-bpp.png')
```
- Throws **[Error][4]** Invalid parameters
* Throws **[Error][4]** Invalid parameters
Returns **Sharp**
@@ -67,10 +68,11 @@ Alternative spelling of `toColourspace`.
### Parameters
- `colorspace` **[string][1]?** output colorspace.
* `colorspace` **[string][1]?** output colorspace.
<!---->
- Throws **[Error][4]** Invalid parameters
* Throws **[Error][4]** Invalid parameters
Returns **Sharp**

View File

@@ -19,24 +19,28 @@ and [https://www.cairographics.org/operators/][2]
### Parameters
- `images` **[Array][3]&lt;[Object][4]>** Ordered list of images to composite
- `images[].input` **([Buffer][5] \| [String][6])?** Buffer containing image data, String containing the path to an image file, or Create object (see below)
- `images[].input.create` **[Object][4]?** describes a blank overlay to be created.
- `images[].input.create.width` **[Number][7]?**
- `images[].input.create.height` **[Number][7]?**
- `images[].input.create.channels` **[Number][7]?** 3-4
- `images[].input.create.background` **([String][6] \| [Object][4])?** parsed by the [color][8] module to extract values for red, green, blue and alpha.
- `images[].blend` **[String][6]** how to blend this image with the image below. (optional, default `'over'`)
- `images[].gravity` **[String][6]** gravity at which to place the overlay. (optional, default `'centre'`)
- `images[].top` **[Number][7]?** the pixel offset from the top edge.
- `images[].left` **[Number][7]?** the pixel offset from the left edge.
- `images[].tile` **[Boolean][9]** set to true to repeat the overlay image across the entire image with the given `gravity`. (optional, default `false`)
- `images[].premultiplied` **[Boolean][9]** set to true to avoid premultipling the image below. Equivalent to the `--premultiplied` vips option. (optional, default `false`)
- `images[].density` **[Number][7]** number representing the DPI for vector overlay image. (optional, default `72`)
- `images[].raw` **[Object][4]?** describes overlay when using raw pixel data.
- `images[].raw.width` **[Number][7]?**
- `images[].raw.height` **[Number][7]?**
- `images[].raw.channels` **[Number][7]?**
* `images` **[Array][3]<[Object][4]>** Ordered list of images to composite
* `images[].input` **([Buffer][5] | [String][6])?** Buffer containing image data, String containing the path to an image file, or Create object (see below)
* `images[].input.create` **[Object][4]?** describes a blank overlay to be created.
* `images[].input.create.width` **[Number][7]?**
* `images[].input.create.height` **[Number][7]?**
* `images[].input.create.channels` **[Number][7]?** 3-4
* `images[].input.create.background` **([String][6] | [Object][4])?** parsed by the [color][8] module to extract values for red, green, blue and alpha.
* `images[].blend` **[String][6]** how to blend this image with the image below. (optional, default `'over'`)
* `images[].gravity` **[String][6]** gravity at which to place the overlay. (optional, default `'centre'`)
* `images[].top` **[Number][7]?** the pixel offset from the top edge.
* `images[].left` **[Number][7]?** the pixel offset from the left edge.
* `images[].tile` **[Boolean][9]** set to true to repeat the overlay image across the entire image with the given `gravity`. (optional, default `false`)
* `images[].premultiplied` **[Boolean][9]** set to true to avoid premultipling the image below. Equivalent to the `--premultiplied` vips option. (optional, default `false`)
* `images[].density` **[Number][7]** number representing the DPI for vector overlay image. (optional, default `72`)
* `images[].raw` **[Object][4]?** describes overlay when using raw pixel data.
* `images[].raw.width` **[Number][7]?**
* `images[].raw.height` **[Number][7]?**
* `images[].raw.channels` **[Number][7]?**
### Examples
@@ -57,13 +61,13 @@ sharp('input.png')
});
```
- Throws **[Error][10]** Invalid parameters
* Throws **[Error][10]** Invalid parameters
Returns **Sharp**
**Meta**
- **since**: 0.22.0
* **since**: 0.22.0
[1]: https://libvips.github.io/libvips/API/current/libvips-conversion.html#VipsBlendMode

View File

@@ -13,36 +13,43 @@ Implements the [stream.Duplex][1] class.
### Parameters
- `input` **([Buffer][2] \| [Uint8Array][3] \| [Uint8ClampedArray][4] \| [string][5])?** if present, can be
a Buffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or 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][6]?** if present, is an Object with optional attributes.
- `options.failOnError` **[boolean][7]** by default halt processing and raise an error when loading invalid images.
Set this flag to `false` if you'd rather apply a "best effort" to decode images, even if the data is corrupt or invalid. (optional, default `true`)
- `options.limitInputPixels` **([number][8] \| [boolean][7])** 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.sequentialRead` **[boolean][7]** 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][8]** number representing the DPI for vector images in the range 1 to 100000. (optional, default `72`)
- `options.pages` **[number][8]** 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][8]** page number to start extracting from for multi-page input (GIF, WebP, AVIF, TIFF, PDF), zero based. (optional, default `0`)
- `options.level` **[number][8]** level to extract from a multi-level input (OpenSlide), zero based. (optional, default `0`)
- `options.animated` **[boolean][7]** Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). (optional, default `false`)
- `options.raw` **[Object][6]?** describes raw pixel input image data. See `raw()` for pixel ordering.
- `options.raw.width` **[number][8]?** integral number of pixels wide.
- `options.raw.height` **[number][8]?** integral number of pixels high.
- `options.raw.channels` **[number][8]?** integral number of channels, between 1 and 4.
- `options.create` **[Object][6]?** describes a new image to be created.
- `options.create.width` **[number][8]?** integral number of pixels wide.
- `options.create.height` **[number][8]?** integral number of pixels high.
- `options.create.channels` **[number][8]?** integral number of channels, either 3 (RGB) or 4 (RGBA).
- `options.create.background` **([string][5] \| [Object][6])?** parsed by the [color][9] module to extract values for red, green, blue and alpha.
- `options.create.noise` **[Object][6]?** describes a noise to be created.
- `options.create.noise.type` **[string][5]?** type of generated noise, currently only `gaussian` is supported.
- `options.create.noise.mean` **[number][8]?** mean of pixels in generated noise.
- `options.create.noise.sigma` **[number][8]?** standard deviation of pixels in generated noise.
* `input` **([Buffer][2] | [Uint8Array][3] | [Uint8ClampedArray][4] | [string][5])?** if present, can be
a Buffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or 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][6]?** if present, is an Object with optional attributes.
* `options.failOnError` **[boolean][7]** by default halt processing and raise an error when loading invalid images.
Set this flag to `false` if you'd rather apply a "best effort" to decode images, even if the data is corrupt or invalid. (optional, default `true`)
* `options.limitInputPixels` **([number][8] | [boolean][7])** 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.sequentialRead` **[boolean][7]** 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][8]** number representing the DPI for vector images in the range 1 to 100000. (optional, default `72`)
* `options.pages` **[number][8]** 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][8]** page number to start extracting from for multi-page input (GIF, WebP, AVIF, TIFF, PDF), zero based. (optional, default `0`)
* `options.subifd` **[number][8]** subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. (optional, default `-1`)
* `options.level` **[number][8]** level to extract from a multi-level input (OpenSlide), zero based. (optional, default `0`)
* `options.animated` **[boolean][7]** Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). (optional, default `false`)
* `options.raw` **[Object][6]?** describes raw pixel input image data. See `raw()` for pixel ordering.
* `options.raw.width` **[number][8]?** integral number of pixels wide.
* `options.raw.height` **[number][8]?** integral number of pixels high.
* `options.raw.channels` **[number][8]?** integral number of channels, between 1 and 4.
* `options.raw.premultiplied` **[boolean][7]?** specifies that the raw input has already been premultiplied, set to `true`
to avoid sharp premultiplying the image. (optional, default `false`)
* `options.create` **[Object][6]?** describes a new image to be created.
* `options.create.width` **[number][8]?** integral number of pixels wide.
* `options.create.height` **[number][8]?** integral number of pixels high.
* `options.create.channels` **[number][8]?** integral number of channels, either 3 (RGB) or 4 (RGBA).
* `options.create.background` **([string][5] | [Object][6])?** parsed by the [color][9] module to extract values for red, green, blue and alpha.
* `options.create.noise` **[Object][6]?** describes a noise to be created.
* `options.create.noise.type` **[string][5]?** type of generated noise, currently only `gaussian` is supported.
* `options.create.noise.mean` **[number][8]?** mean of pixels in generated noise.
* `options.create.noise.sigma` **[number][8]?** standard deviation of pixels in generated noise.
### Examples
@@ -119,7 +126,7 @@ await sharp({
}).toFile('noise.png');
```
- Throws **[Error][10]** Invalid parameters
* Throws **[Error][10]** Invalid parameters
Returns **[Sharp][11]**

View File

@@ -5,34 +5,35 @@
Fast access to (uncached) image metadata without decoding any compressed image data.
A `Promise` is returned when `callback` is not provided.
- `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg`
- `size`: Total size of image in bytes, for Stream and Buffer input only
- `width`: Number of pixels wide (EXIF orientation is not taken into consideration)
- `height`: Number of pixels high (EXIF orientation is not taken into consideration)
- `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...][1]
- `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK
- `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...][2]
- `density`: Number of pixels per inch (DPI), if present
- `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK
- `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan
- `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP
- `pageHeight`: Number of pixels high each page in a multi-page image will be.
- `loop`: Number of times to loop an animated image, zero refers to a continuous loop.
- `delay`: Delay in ms between each page in an animated image, provided as an array of integers.
- `pagePrimary`: Number of the primary page in a HEIF image
- `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide
- `hasProfile`: Boolean indicating the presence of an embedded ICC profile
- `hasAlpha`: Boolean indicating the presence of an alpha transparency channel
- `orientation`: Number value of the EXIF Orientation header, if present
- `exif`: Buffer containing raw EXIF data, if present
- `icc`: Buffer containing raw [ICC][3] profile data, if present
- `iptc`: Buffer containing raw IPTC data, if present
- `xmp`: Buffer containing raw XMP data, if present
- `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present
* `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg`
* `size`: Total size of image in bytes, for Stream and Buffer input only
* `width`: Number of pixels wide (EXIF orientation is not taken into consideration)
* `height`: Number of pixels high (EXIF orientation is not taken into consideration)
* `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...][1]
* `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK
* `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...][2]
* `density`: Number of pixels per inch (DPI), if present
* `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK
* `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan
* `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP
* `pageHeight`: Number of pixels high each page in a multi-page image will be.
* `loop`: Number of times to loop an animated image, zero refers to a continuous loop.
* `delay`: Delay in ms between each page in an animated image, provided as an array of integers.
* `pagePrimary`: Number of the primary page in a HEIF image
* `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide
* `subifds`: Number of Sub Image File Directories in an OME-TIFF image
* `hasProfile`: Boolean indicating the presence of an embedded ICC profile
* `hasAlpha`: Boolean indicating the presence of an alpha transparency channel
* `orientation`: Number value of the EXIF Orientation header, if present
* `exif`: Buffer containing raw EXIF data, if present
* `icc`: Buffer containing raw [ICC][3] profile data, if present
* `iptc`: Buffer containing raw IPTC data, if present
* `xmp`: Buffer containing raw XMP data, if present
* `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present
### Parameters
- `callback` **[Function][4]?** called with the arguments `(err, metadata)`
* `callback` **[Function][4]?** called with the arguments `(err, metadata)`
### Examples
@@ -51,32 +52,32 @@ image
});
```
Returns **([Promise][5]&lt;[Object][6]> | Sharp)**
Returns **([Promise][5]<[Object][6]> | Sharp)**
## stats
Access to pixel-derived image statistics for every channel in the image.
A `Promise` is returned when `callback` is not provided.
- `channels`: Array of channel statistics for each channel in the image. Each channel statistic contains
- `min` (minimum value in the channel)
- `max` (maximum value in the channel)
- `sum` (sum of all values in a channel)
- `squaresSum` (sum of squared values in a channel)
- `mean` (mean of the values in a channel)
- `stdev` (standard deviation for the values in a channel)
- `minX` (x-coordinate of one of the pixel where the minimum lies)
- `minY` (y-coordinate of one of the pixel where the minimum lies)
- `maxX` (x-coordinate of one of the pixel where the maximum lies)
- `maxY` (y-coordinate of one of the pixel where the maximum lies)
- `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque.
- `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any (experimental)
- `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any (experimental)
- `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram (experimental)
* `channels`: Array of channel statistics for each channel in the image. Each channel statistic contains
* `min` (minimum value in the channel)
* `max` (maximum value in the channel)
* `sum` (sum of all values in a channel)
* `squaresSum` (sum of squared values in a channel)
* `mean` (mean of the values in a channel)
* `stdev` (standard deviation for the values in a channel)
* `minX` (x-coordinate of one of the pixel where the minimum lies)
* `minY` (y-coordinate of one of the pixel where the minimum lies)
* `maxX` (x-coordinate of one of the pixel where the maximum lies)
* `maxY` (y-coordinate of one of the pixel where the maximum lies)
* `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque.
* `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any (experimental)
* `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any (experimental)
* `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram (experimental)
### Parameters
- `callback` **[Function][4]?** called with the arguments `(err, stats)`
* `callback` **[Function][4]?** called with the arguments `(err, stats)`
### Examples
@@ -94,7 +95,7 @@ const { entropy, sharpness, dominant } = await sharp(input).stats();
const { r, g, b } = dominant;
```
Returns **[Promise][5]&lt;[Object][6]>**
Returns **[Promise][5]<[Object][6]>**
[1]: https://libvips.github.io/libvips/API/current/VipsImage.html#VipsInterpretation

View File

@@ -21,9 +21,10 @@ for example `rotate(x).extract(y)` will produce a different result to `extract(y
### Parameters
- `angle` **[number][1]** angle of rotation. (optional, default `auto`)
- `options` **[Object][2]?** if present, is an Object with optional attributes.
- `options.background` **([string][3] \| [Object][2])** parsed by the [color][4] module to extract values for red, green, blue and alpha. (optional, default `"#000000"`)
* `angle` **[number][1]** angle of rotation. (optional, default `auto`)
* `options` **[Object][2]?** if present, is an Object with optional attributes.
* `options.background` **([string][3] | [Object][2])** parsed by the [color][4] module to extract values for red, green, blue and alpha. (optional, default `"#000000"`)
### Examples
@@ -39,7 +40,7 @@ const pipeline = sharp()
readableStream.pipe(pipeline);
```
- Throws **[Error][5]** Invalid parameters
* Throws **[Error][5]** Invalid parameters
Returns **Sharp**
@@ -50,7 +51,7 @@ The use of `flip` implies the removal of the EXIF `Orientation` tag, if any.
### Parameters
- `flip` **[Boolean][6]** (optional, default `true`)
* `flip` **[Boolean][6]** (optional, default `true`)
Returns **Sharp**
@@ -61,7 +62,7 @@ The use of `flop` implies the removal of the EXIF `Orientation` tag, if any.
### Parameters
- `flop` **[Boolean][6]** (optional, default `true`)
* `flop` **[Boolean][6]** (optional, default `true`)
Returns **Sharp**
@@ -75,25 +76,26 @@ A particular interpolator may also be specified. Set the `interpolator` option t
In the case of a 2x2 matrix, the transform is:
- X = `matrix[0, 0]` \* (x + `idx`) + `matrix[0, 1]` \* (y + `idy`) + `odx`
- Y = `matrix[1, 0]` \* (x + `idx`) + `matrix[1, 1]` \* (y + `idy`) + `ody`
* X = `matrix[0, 0]` \* (x + `idx`) + `matrix[0, 1]` \* (y + `idy`) + `odx`
* Y = `matrix[1, 0]` \* (x + `idx`) + `matrix[1, 1]` \* (y + `idy`) + `ody`
where:
- x and y are the coordinates in input image.
- X and Y are the coordinates in output image.
- (0,0) is the upper left corner.
* x and y are the coordinates in input image.
* X and Y are the coordinates in output image.
* (0,0) is the upper left corner.
### Parameters
- `matrix` **([Array][7]&lt;[Array][7]&lt;[number][1]>> | [Array][7]&lt;[number][1]>)** affine transformation matrix
- `options` **[Object][2]?** if present, is an Object with optional attributes.
- `options.background` **([String][3] \| [Object][2])** parsed by the [color][4] module to extract values for red, green, blue and alpha. (optional, default `"#000000"`)
- `options.idx` **[Number][1]** input horizontal offset (optional, default `0`)
- `options.idy` **[Number][1]** input vertical offset (optional, default `0`)
- `options.odx` **[Number][1]** output horizontal offset (optional, default `0`)
- `options.ody` **[Number][1]** output vertical offset (optional, default `0`)
- `options.interpolator` **[String][3]** interpolator (optional, default `sharp.interpolators.bicubic`)
* `matrix` **([Array][7]<[Array][7]<[number][1]>> | [Array][7]<[number][1]>)** affine transformation matrix
* `options` **[Object][2]?** if present, is an Object with optional attributes.
* `options.background` **([String][3] | [Object][2])** parsed by the [color][4] module to extract values for red, green, blue and alpha. (optional, default `"#000000"`)
* `options.idx` **[Number][1]** input horizontal offset (optional, default `0`)
* `options.idy` **[Number][1]** input vertical offset (optional, default `0`)
* `options.odx` **[Number][1]** output horizontal offset (optional, default `0`)
* `options.ody` **[Number][1]** output vertical offset (optional, default `0`)
* `options.interpolator` **[String][3]** interpolator (optional, default `sharp.interpolators.bicubic`)
### Examples
@@ -112,13 +114,13 @@ inputStream
.pipe(pipeline);
```
- Throws **[Error][5]** Invalid parameters
* Throws **[Error][5]** Invalid parameters
Returns **Sharp**
**Meta**
- **since**: 0.27.0
* **since**: 0.27.0
## sharpen
@@ -129,12 +131,13 @@ Separate control over the level of sharpening in "flat" and "jagged" areas is av
### Parameters
- `sigma` **[number][1]?** the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
- `flat` **[number][1]** the level of sharpening to apply to "flat" areas. (optional, default `1.0`)
- `jagged` **[number][1]** the level of sharpening to apply to "jagged" areas. (optional, default `2.0`)
* `sigma` **[number][1]?** the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
* `flat` **[number][1]** the level of sharpening to apply to "flat" areas. (optional, default `1.0`)
* `jagged` **[number][1]** the level of sharpening to apply to "jagged" areas. (optional, default `2.0`)
<!---->
- Throws **[Error][5]** Invalid parameters
* Throws **[Error][5]** Invalid parameters
Returns **Sharp**
@@ -145,10 +148,11 @@ When used without parameters the default window is 3x3.
### Parameters
- `size` **[number][1]** square mask size: size x size (optional, default `3`)
* `size` **[number][1]** square mask size: size x size (optional, default `3`)
<!---->
- Throws **[Error][5]** Invalid parameters
* Throws **[Error][5]** Invalid parameters
Returns **Sharp**
@@ -160,10 +164,11 @@ When a `sigma` is provided, performs a slower, more accurate Gaussian blur.
### Parameters
- `sigma` **[number][1]?** a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
* `sigma` **[number][1]?** a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
<!---->
- Throws **[Error][5]** Invalid parameters
* Throws **[Error][5]** Invalid parameters
Returns **Sharp**
@@ -173,14 +178,15 @@ Merge alpha transparency channel, if any, with a background, then remove the alp
### Parameters
- `options` **[Object][2]?**
- `options.background` **([string][3] \| [Object][2])** background colour, parsed by the [color][4] module, defaults to black. (optional, default `{r:0,g:0,b:0}`)
* `options` **[Object][2]?**
* `options.background` **([string][3] | [Object][2])** background colour, parsed by the [color][4] module, defaults to black. (optional, default `{r:0,g:0,b:0}`)
### Examples
```javascript
await sharp(rgbaInput)
.flatten('#F0A703')
.flatten({background: '#F0A703' })
.toBuffer();
```
@@ -198,11 +204,12 @@ Supply a second argument to use a different output gamma value, otherwise the fi
### Parameters
- `gamma` **[number][1]** value between 1.0 and 3.0. (optional, default `2.2`)
- `gammaOut` **[number][1]?** value between 1.0 and 3.0. (optional, defaults to same as `gamma`)
* `gamma` **[number][1]** value between 1.0 and 3.0. (optional, default `2.2`)
* `gammaOut` **[number][1]?** value between 1.0 and 3.0. (optional, defaults to same as `gamma`)
<!---->
- Throws **[Error][5]** Invalid parameters
* Throws **[Error][5]** Invalid parameters
Returns **Sharp**
@@ -212,7 +219,7 @@ Produce the "negative" of the image.
### Parameters
- `negate` **[Boolean][6]** (optional, default `true`)
* `negate` **[Boolean][6]** (optional, default `true`)
Returns **Sharp**
@@ -222,7 +229,7 @@ Enhance output image contrast by stretching its luminance to cover the full dyna
### Parameters
- `normalise` **[Boolean][6]** (optional, default `true`)
* `normalise` **[Boolean][6]** (optional, default `true`)
Returns **Sharp**
@@ -232,7 +239,7 @@ Alternative spelling of normalise.
### Parameters
- `normalize` **[Boolean][6]** (optional, default `true`)
* `normalize` **[Boolean][6]** (optional, default `true`)
Returns **Sharp**
@@ -242,12 +249,13 @@ Convolve the image with the specified kernel.
### Parameters
- `kernel` **[Object][2]**
- `kernel.width` **[number][1]** width of the kernel in pixels.
- `kernel.height` **[number][1]** width of the kernel in pixels.
- `kernel.kernel` **[Array][7]&lt;[number][1]>** Array of length `width*height` containing the kernel values.
- `kernel.scale` **[number][1]** the scale of the kernel in pixels. (optional, default `sum`)
- `kernel.offset` **[number][1]** the offset of the kernel in pixels. (optional, default `0`)
* `kernel` **[Object][2]**
* `kernel.width` **[number][1]** width of the kernel in pixels.
* `kernel.height` **[number][1]** width of the kernel in pixels.
* `kernel.kernel` **[Array][7]<[number][1]>** Array of length `width*height` containing the kernel values.
* `kernel.scale` **[number][1]** the scale of the kernel in pixels. (optional, default `sum`)
* `kernel.offset` **[number][1]** the offset of the kernel in pixels. (optional, default `0`)
### Examples
@@ -265,7 +273,7 @@ sharp(input)
});
```
- Throws **[Error][5]** Invalid parameters
* Throws **[Error][5]** Invalid parameters
Returns **Sharp**
@@ -275,13 +283,15 @@ Any pixel value greater than or equal to the threshold value will be set to 255,
### Parameters
- `threshold` **[number][1]** a value in the range 0-255 representing the level at which the threshold will be applied. (optional, default `128`)
- `options` **[Object][2]?**
- `options.greyscale` **[Boolean][6]** convert to single channel greyscale. (optional, default `true`)
- `options.grayscale` **[Boolean][6]** alternative spelling for greyscale. (optional, default `true`)
* `threshold` **[number][1]** a value in the range 0-255 representing the level at which the threshold will be applied. (optional, default `128`)
* `options` **[Object][2]?**
* `options.greyscale` **[Boolean][6]** convert to single channel greyscale. (optional, default `true`)
* `options.grayscale` **[Boolean][6]** alternative spelling for greyscale. (optional, default `true`)
- Throws **[Error][5]** Invalid parameters
<!---->
* Throws **[Error][5]** Invalid parameters
Returns **Sharp**
@@ -294,16 +304,19 @@ the selected bitwise boolean `operation` between the corresponding pixels of the
### Parameters
- `operand` **([Buffer][8] \| [string][3])** Buffer containing image data or string containing the path to an image file.
- `operator` **[string][3]** one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.
- `options` **[Object][2]?**
- `options.raw` **[Object][2]?** describes operand when using raw pixel data.
- `options.raw.width` **[number][1]?**
- `options.raw.height` **[number][1]?**
- `options.raw.channels` **[number][1]?**
* `operand` **([Buffer][8] | [string][3])** Buffer containing image data or string containing the path to an image file.
* `operator` **[string][3]** one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.
* `options` **[Object][2]?**
* `options.raw` **[Object][2]?** describes operand when using raw pixel data.
- Throws **[Error][5]** Invalid parameters
* `options.raw.width` **[number][1]?**
* `options.raw.height` **[number][1]?**
* `options.raw.channels` **[number][1]?**
<!---->
* Throws **[Error][5]** Invalid parameters
Returns **Sharp**
@@ -313,11 +326,12 @@ Apply the linear formula a \* input + b to the image (levels adjustment)
### Parameters
- `a` **[number][1]** multiplier (optional, default `1.0`)
- `b` **[number][1]** offset (optional, default `0.0`)
* `a` **[number][1]** multiplier (optional, default `1.0`)
* `b` **[number][1]** offset (optional, default `0.0`)
<!---->
- Throws **[Error][5]** Invalid parameters
* Throws **[Error][5]** Invalid parameters
Returns **Sharp**
@@ -327,7 +341,7 @@ Recomb the image with the specified matrix.
### Parameters
- `inputMatrix` **[Array][7]&lt;[Array][7]&lt;[number][1]>>** 3x3 Recombination matrix
* `inputMatrix` **[Array][7]<[Array][7]<[number][1]>>** 3x3 Recombination matrix
### Examples
@@ -345,13 +359,13 @@ sharp(input)
});
```
- Throws **[Error][5]** Invalid parameters
* Throws **[Error][5]** Invalid parameters
Returns **Sharp**
**Meta**
- **since**: 0.21.1
* **since**: 0.21.1
## modulate
@@ -359,10 +373,11 @@ Transforms the image using brightness, saturation and hue rotation.
### Parameters
- `options` **[Object][2]?**
- `options.brightness` **[number][1]?** Brightness multiplier
- `options.saturation` **[number][1]?** Saturation multiplier
- `options.hue` **[number][1]?** Degrees for hue rotation
* `options` **[Object][2]?**
* `options.brightness` **[number][1]?** Brightness multiplier
* `options.saturation` **[number][1]?** Saturation multiplier
* `options.hue` **[number][1]?** Degrees for hue rotation
### Examples
@@ -390,7 +405,7 @@ Returns **Sharp**
**Meta**
- **since**: 0.22.1
* **since**: 0.22.1
[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number

View File

@@ -15,8 +15,8 @@ A `Promise` is returned when `callback` is not provided.
### Parameters
- `fileOut` **[string][2]** the path to write the image data to.
- `callback` **[Function][3]?** called on completion with two arguments `(err, info)`.
* `fileOut` **[string][2]** the path to write the image data to.
* `callback` **[Function][3]?** called on completion with two arguments `(err, info)`.
`info` contains the output image `format`, `size` (bytes), `width`, `height`,
`channels` and `premultiplied` (indicating if premultiplication was used).
When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
@@ -35,9 +35,9 @@ sharp(input)
.catch(err => { ... });
```
- Throws **[Error][4]** Invalid parameters
* Throws **[Error][4]** Invalid parameters
Returns **[Promise][5]&lt;[Object][6]>** when no callback is provided
Returns **[Promise][5]<[Object][6]>** when no callback is provided
## toBuffer
@@ -51,19 +51,21 @@ See [withMetadata][1] for control over this.
`callback`, if present, gets three arguments `(err, data, info)` where:
- `err` is an error, if any.
- `data` is the output image data.
- `info` contains the output image `format`, `size` (bytes), `width`, `height`,
`channels` and `premultiplied` (indicating if premultiplication was used).
When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
* `err` is an error, if any.
* `data` is the output image data.
* `info` contains the output image `format`, `size` (bytes), `width`, `height`,
`channels` and `premultiplied` (indicating if premultiplication was used).
When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
A `Promise` is returned when `callback` is not provided.
### Parameters
- `options` **[Object][6]?**
- `options.resolveWithObject` **[boolean][7]?** Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`.
- `callback` **[Function][3]?**
* `options` **[Object][6]?**
* `options.resolveWithObject` **[boolean][7]?** Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`.
* `callback` **[Function][3]?**
### Examples
@@ -103,7 +105,7 @@ await sharp(pixelArray, { raw: { width, height, channels } })
.toFile('my-changed-image.jpg');
```
Returns **[Promise][5]&lt;[Buffer][8]>** when no callback is provided
Returns **[Promise][5]<[Buffer][8]>** when no callback is provided
## withMetadata
@@ -116,9 +118,12 @@ sRGB colour space and strip all metadata, including the removal of any ICC profi
### Parameters
- `options` **[Object][6]?**
- `options.orientation` **[number][9]?** value between 1 and 8, used to update the EXIF `Orientation` tag.
- `options.icc` **[string][2]?** filesystem path to output ICC profile, defaults to sRGB.
* `options` **[Object][6]?**
* `options.orientation` **[number][9]?** value between 1 and 8, used to update the EXIF `Orientation` tag.
* `options.icc` **[string][2]?** filesystem path to output ICC profile, defaults to sRGB.
* `options.exif` **[Object][6]<[Object][6]>** Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. (optional, default `{}`)
* `options.density` **[number][9]?** Number of pixels per inch (DPI).
### Examples
@@ -129,7 +134,26 @@ sharp('input.jpg')
.then(info => { ... });
```
- Throws **[Error][4]** Invalid parameters
```javascript
// Set "IFD0-Copyright" in output EXIF metadata
const data = await sharp(input)
.withMetadata({
exif: {
IFD0: {
Copyright: 'Wernham Hogg'
}
}
})
.toBuffer();
* @example
// Set output metadata to 96 DPI
const data = await sharp(input)
.withMetadata({ density: 96 })
.toBuffer();
```
* Throws **[Error][4]** Invalid parameters
Returns **Sharp**
@@ -139,8 +163,8 @@ Force output to a given format.
### Parameters
- `format` **([string][2] \| [Object][6])** as a string or an Object with an 'id' attribute
- `options` **[Object][6]** output options
* `format` **([string][2] | [Object][6])** as a string or an Object with an 'id' attribute
* `options` **[Object][6]** output options
### Examples
@@ -151,7 +175,7 @@ const data = await sharp(input)
.toBuffer();
```
- Throws **[Error][4]** unsupported format or options
* Throws **[Error][4]** unsupported format or options
Returns **Sharp**
@@ -161,20 +185,21 @@ Use these JPEG options for output image.
### Parameters
- `options` **[Object][6]?** output options
- `options.quality` **[number][9]** quality, integer 1-100 (optional, default `80`)
- `options.progressive` **[boolean][7]** use progressive (interlace) scan (optional, default `false`)
- `options.chromaSubsampling` **[string][2]** set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling (optional, default `'4:2:0'`)
- `options.optimiseCoding` **[boolean][7]** optimise Huffman coding tables (optional, default `true`)
- `options.optimizeCoding` **[boolean][7]** alternative spelling of optimiseCoding (optional, default `true`)
- `options.mozjpeg` **[boolean][7]** use mozjpeg defaults, equivalent to `{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }` (optional, default `false`)
- `options.trellisQuantisation` **[boolean][7]** apply trellis quantisation (optional, default `false`)
- `options.overshootDeringing` **[boolean][7]** apply overshoot deringing (optional, default `false`)
- `options.optimiseScans` **[boolean][7]** optimise progressive scans, forces progressive (optional, default `false`)
- `options.optimizeScans` **[boolean][7]** alternative spelling of optimiseScans (optional, default `false`)
- `options.quantisationTable` **[number][9]** quantization table to use, integer 0-8 (optional, default `0`)
- `options.quantizationTable` **[number][9]** alternative spelling of quantisationTable (optional, default `0`)
- `options.force` **[boolean][7]** force JPEG output, otherwise attempt to use input format (optional, default `true`)
* `options` **[Object][6]?** output options
* `options.quality` **[number][9]** quality, integer 1-100 (optional, default `80`)
* `options.progressive` **[boolean][7]** use progressive (interlace) scan (optional, default `false`)
* `options.chromaSubsampling` **[string][2]** set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling (optional, default `'4:2:0'`)
* `options.optimiseCoding` **[boolean][7]** optimise Huffman coding tables (optional, default `true`)
* `options.optimizeCoding` **[boolean][7]** alternative spelling of optimiseCoding (optional, default `true`)
* `options.mozjpeg` **[boolean][7]** use mozjpeg defaults, equivalent to `{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }` (optional, default `false`)
* `options.trellisQuantisation` **[boolean][7]** apply trellis quantisation (optional, default `false`)
* `options.overshootDeringing` **[boolean][7]** apply overshoot deringing (optional, default `false`)
* `options.optimiseScans` **[boolean][7]** optimise progressive scans, forces progressive (optional, default `false`)
* `options.optimizeScans` **[boolean][7]** alternative spelling of optimiseScans (optional, default `false`)
* `options.quantisationTable` **[number][9]** quantization table to use, integer 0-8 (optional, default `0`)
* `options.quantizationTable` **[number][9]** alternative spelling of quantisationTable (optional, default `0`)
* `options.force` **[boolean][7]** force JPEG output, otherwise attempt to use input format (optional, default `true`)
### Examples
@@ -195,7 +220,7 @@ const data = await sharp(input)
.toBuffer();
```
- Throws **[Error][4]** Invalid options
* Throws **[Error][4]** Invalid options
Returns **Sharp**
@@ -209,16 +234,17 @@ Set `palette` to `true` for slower, indexed PNG output.
### Parameters
- `options` **[Object][6]?**
- `options.progressive` **[boolean][7]** use progressive (interlace) scan (optional, default `false`)
- `options.compressionLevel` **[number][9]** zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest) (optional, default `6`)
- `options.adaptiveFiltering` **[boolean][7]** use adaptive row filtering (optional, default `false`)
- `options.palette` **[boolean][7]** quantise to a palette-based image with alpha transparency support (optional, default `false`)
- `options.quality` **[number][9]** use the lowest number of colours needed to achieve given quality, sets `palette` to `true` (optional, default `100`)
- `options.colours` **[number][9]** maximum number of palette entries, sets `palette` to `true` (optional, default `256`)
- `options.colors` **[number][9]** alternative spelling of `options.colours`, sets `palette` to `true` (optional, default `256`)
- `options.dither` **[number][9]** level of Floyd-Steinberg error diffusion, sets `palette` to `true` (optional, default `1.0`)
- `options.force` **[boolean][7]** force PNG output, otherwise attempt to use input format (optional, default `true`)
* `options` **[Object][6]?**
* `options.progressive` **[boolean][7]** use progressive (interlace) scan (optional, default `false`)
* `options.compressionLevel` **[number][9]** zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest) (optional, default `6`)
* `options.adaptiveFiltering` **[boolean][7]** use adaptive row filtering (optional, default `false`)
* `options.palette` **[boolean][7]** quantise to a palette-based image with alpha transparency support (optional, default `false`)
* `options.quality` **[number][9]** use the lowest number of colours needed to achieve given quality, sets `palette` to `true` (optional, default `100`)
* `options.colours` **[number][9]** maximum number of palette entries, sets `palette` to `true` (optional, default `256`)
* `options.colors` **[number][9]** alternative spelling of `options.colours`, sets `palette` to `true` (optional, default `256`)
* `options.dither` **[number][9]** level of Floyd-Steinberg error diffusion, sets `palette` to `true` (optional, default `1.0`)
* `options.force` **[boolean][7]** force PNG output, otherwise attempt to use input format (optional, default `true`)
### Examples
@@ -236,7 +262,7 @@ const data = await sharp(input)
.toBuffer();
```
- Throws **[Error][4]** Invalid options
* Throws **[Error][4]** Invalid options
Returns **Sharp**
@@ -246,17 +272,18 @@ Use these WebP options for output image.
### Parameters
- `options` **[Object][6]?** output options
- `options.quality` **[number][9]** quality, integer 1-100 (optional, default `80`)
- `options.alphaQuality` **[number][9]** quality of alpha layer, integer 0-100 (optional, default `100`)
- `options.lossless` **[boolean][7]** use lossless compression mode (optional, default `false`)
- `options.nearLossless` **[boolean][7]** use near_lossless compression mode (optional, default `false`)
- `options.smartSubsample` **[boolean][7]** use high quality chroma subsampling (optional, default `false`)
- `options.reductionEffort` **[number][9]** level of CPU effort to reduce file size, integer 0-6 (optional, default `4`)
- `options.pageHeight` **[number][9]?** page height for animated output
- `options.loop` **[number][9]** number of animation iterations, use 0 for infinite animation (optional, default `0`)
- `options.delay` **[Array][10]&lt;[number][9]>?** list of delays between animation frames (in milliseconds)
- `options.force` **[boolean][7]** force WebP output, otherwise attempt to use input format (optional, default `true`)
* `options` **[Object][6]?** output options
* `options.quality` **[number][9]** quality, integer 1-100 (optional, default `80`)
* `options.alphaQuality` **[number][9]** quality of alpha layer, integer 0-100 (optional, default `100`)
* `options.lossless` **[boolean][7]** use lossless compression mode (optional, default `false`)
* `options.nearLossless` **[boolean][7]** use near_lossless compression mode (optional, default `false`)
* `options.smartSubsample` **[boolean][7]** use high quality chroma subsampling (optional, default `false`)
* `options.reductionEffort` **[number][9]** level of CPU effort to reduce file size, integer 0-6 (optional, default `4`)
* `options.pageHeight` **[number][9]?** page height for animated output
* `options.loop` **[number][9]** number of animation iterations, use 0 for infinite animation (optional, default `0`)
* `options.delay` **[Array][10]<[number][9]>?** list of delays between animation frames (in milliseconds)
* `options.force` **[boolean][7]** force WebP output, otherwise attempt to use input format (optional, default `true`)
### Examples
@@ -267,7 +294,14 @@ const data = await sharp(input)
.toBuffer();
```
- Throws **[Error][4]** Invalid options
```javascript
// Optimise the file size of an animated WebP
const outputWebp = await sharp(inputWebp, { animated: true })
.webp({ reductionEffort: 6 })
.toBuffer();
```
* Throws **[Error][4]** Invalid options
Returns **Sharp**
@@ -281,14 +315,16 @@ The prebuilt binaries do not include this - see
### Parameters
- `options` **[Object][6]?** output options
- `options.pageHeight` **[number][9]?** page height for animated output
- `options.loop` **[number][9]** number of animation iterations, use 0 for infinite animation (optional, default `0`)
- `options.delay` **[Array][10]&lt;[number][9]>?** list of delays between animation frames (in milliseconds)
- `options.force` **[boolean][7]** force GIF output, otherwise attempt to use input format (optional, default `true`)
* `options` **[Object][6]?** output options
* `options.pageHeight` **[number][9]?** page height for animated output
* `options.loop` **[number][9]** number of animation iterations, use 0 for infinite animation (optional, default `0`)
* `options.delay` **[Array][10]<[number][9]>?** list of delays between animation frames (in milliseconds)
* `options.force` **[boolean][7]** force GIF output, otherwise attempt to use input format (optional, default `true`)
- Throws **[Error][4]** Invalid options
<!---->
* Throws **[Error][4]** Invalid options
Returns **Sharp**
@@ -298,18 +334,19 @@ Use these TIFF options for output image.
### Parameters
- `options` **[Object][6]?** output options
- `options.quality` **[number][9]** quality, integer 1-100 (optional, default `80`)
- `options.force` **[boolean][7]** force TIFF output, otherwise attempt to use input format (optional, default `true`)
- `options.compression` **[string][2]** compression options: lzw, deflate, jpeg, ccittfax4 (optional, default `'jpeg'`)
- `options.predictor` **[string][2]** compression predictor options: none, horizontal, float (optional, default `'horizontal'`)
- `options.pyramid` **[boolean][7]** write an image pyramid (optional, default `false`)
- `options.tile` **[boolean][7]** write a tiled tiff (optional, default `false`)
- `options.tileWidth` **[number][9]** horizontal tile size (optional, default `256`)
- `options.tileHeight` **[number][9]** vertical tile size (optional, default `256`)
- `options.xres` **[number][9]** horizontal resolution in pixels/mm (optional, default `1.0`)
- `options.yres` **[number][9]** vertical resolution in pixels/mm (optional, default `1.0`)
- `options.bitdepth` **[number][9]** reduce bitdepth to 1, 2 or 4 bit (optional, default `8`)
* `options` **[Object][6]?** output options
* `options.quality` **[number][9]** quality, integer 1-100 (optional, default `80`)
* `options.force` **[boolean][7]** force TIFF output, otherwise attempt to use input format (optional, default `true`)
* `options.compression` **[string][2]** compression options: lzw, deflate, jpeg, ccittfax4 (optional, default `'jpeg'`)
* `options.predictor` **[string][2]** compression predictor options: none, horizontal, float (optional, default `'horizontal'`)
* `options.pyramid` **[boolean][7]** write an image pyramid (optional, default `false`)
* `options.tile` **[boolean][7]** write a tiled tiff (optional, default `false`)
* `options.tileWidth` **[number][9]** horizontal tile size (optional, default `256`)
* `options.tileHeight` **[number][9]** vertical tile size (optional, default `256`)
* `options.xres` **[number][9]** horizontal resolution in pixels/mm (optional, default `1.0`)
* `options.yres` **[number][9]** vertical resolution in pixels/mm (optional, default `1.0`)
* `options.bitdepth` **[number][9]** reduce bitdepth to 1, 2 or 4 bit (optional, default `8`)
### Examples
@@ -324,7 +361,7 @@ sharp('input.svg')
.then(info => { ... });
```
- Throws **[Error][4]** Invalid options
* Throws **[Error][4]** Invalid options
Returns **Sharp**
@@ -337,20 +374,22 @@ most web browsers do not display these properly.
### Parameters
- `options` **[Object][6]?** output options
- `options.quality` **[number][9]** quality, integer 1-100 (optional, default `50`)
- `options.lossless` **[boolean][7]** use lossless compression (optional, default `false`)
- `options.speed` **[number][9]** CPU effort vs file size, 0 (slowest/smallest) to 8 (fastest/largest) (optional, default `5`)
- `options.chromaSubsampling` **[string][2]** set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling, requires libvips v8.11.0 (optional, default `'4:2:0'`)
* `options` **[Object][6]?** output options
* `options.quality` **[number][9]** quality, integer 1-100 (optional, default `50`)
* `options.lossless` **[boolean][7]** use lossless compression (optional, default `false`)
* `options.speed` **[number][9]** CPU effort vs file size, 0 (slowest/smallest) to 8 (fastest/largest) (optional, default `5`)
* `options.chromaSubsampling` **[string][2]** set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling, requires libvips v8.11.0 (optional, default `'4:2:0'`)
- Throws **[Error][4]** Invalid options
<!---->
* Throws **[Error][4]** Invalid options
Returns **Sharp**
**Meta**
- **since**: 0.27.0
* **since**: 0.27.0
## heif
@@ -361,21 +400,23 @@ globally-installed libvips compiled with support for libheif, libde265 and x265.
### Parameters
- `options` **[Object][6]?** output options
- `options.quality` **[number][9]** quality, integer 1-100 (optional, default `50`)
- `options.compression` **[string][2]** compression format: av1, hevc (optional, default `'av1'`)
- `options.lossless` **[boolean][7]** use lossless compression (optional, default `false`)
- `options.speed` **[number][9]** CPU effort vs file size, 0 (slowest/smallest) to 8 (fastest/largest) (optional, default `5`)
- `options.chromaSubsampling` **[string][2]** set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling, requires libvips v8.11.0 (optional, default `'4:2:0'`)
* `options` **[Object][6]?** output options
* `options.quality` **[number][9]** quality, integer 1-100 (optional, default `50`)
* `options.compression` **[string][2]** compression format: av1, hevc (optional, default `'av1'`)
* `options.lossless` **[boolean][7]** use lossless compression (optional, default `false`)
* `options.speed` **[number][9]** CPU effort vs file size, 0 (slowest/smallest) to 8 (fastest/largest) (optional, default `5`)
* `options.chromaSubsampling` **[string][2]** set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling, requires libvips v8.11.0 (optional, default `'4:2:0'`)
- Throws **[Error][4]** Invalid options
<!---->
* Throws **[Error][4]** Invalid options
Returns **Sharp**
**Meta**
- **since**: 0.23.0
* **since**: 0.23.0
## raw
@@ -414,18 +455,19 @@ Warning: multiple sharp instances concurrently producing tile output can expose
### Parameters
- `options` **[Object][6]?**
- `options.size` **[number][9]** tile size in pixels, a value between 1 and 8192. (optional, default `256`)
- `options.overlap` **[number][9]** tile overlap in pixels, a value between 0 and 8192. (optional, default `0`)
- `options.angle` **[number][9]** tile angle of rotation, must be a multiple of 90. (optional, default `0`)
- `options.background` **([string][2] \| [Object][6])** background colour, parsed by the [color][12] module, defaults to white without transparency. (optional, default `{r:255,g:255,b:255,alpha:1}`)
- `options.depth` **[string][2]?** how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout.
- `options.skipBlanks` **[number][9]** threshold to skip tile generation, a value 0 - 255 for 8-bit images or 0 - 65535 for 16-bit images (optional, default `-1`)
- `options.container` **[string][2]** tile container, with value `fs` (filesystem) or `zip` (compressed file). (optional, default `'fs'`)
- `options.layout` **[string][2]** filesystem layout, possible values are `dz`, `iiif`, `zoomify` or `google`. (optional, default `'dz'`)
- `options.centre` **[boolean][7]** centre image in tile. (optional, default `false`)
- `options.center` **[boolean][7]** alternative spelling of centre. (optional, default `false`)
- `options.id` **[string][2]** when `layout` is `iiif`, sets the `@id` attribute of `info.json` (optional, default `'https://example.com/iiif'`)
* `options` **[Object][6]?**
* `options.size` **[number][9]** tile size in pixels, a value between 1 and 8192. (optional, default `256`)
* `options.overlap` **[number][9]** tile overlap in pixels, a value between 0 and 8192. (optional, default `0`)
* `options.angle` **[number][9]** tile angle of rotation, must be a multiple of 90. (optional, default `0`)
* `options.background` **([string][2] | [Object][6])** background colour, parsed by the [color][12] module, defaults to white without transparency. (optional, default `{r:255,g:255,b:255,alpha:1}`)
* `options.depth` **[string][2]?** how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout.
* `options.skipBlanks` **[number][9]** threshold to skip tile generation, a value 0 - 255 for 8-bit images or 0 - 65535 for 16-bit images (optional, default `-1`)
* `options.container` **[string][2]** tile container, with value `fs` (filesystem) or `zip` (compressed file). (optional, default `'fs'`)
* `options.layout` **[string][2]** filesystem layout, possible values are `dz`, `iiif`, `zoomify` or `google`. (optional, default `'dz'`)
* `options.centre` **[boolean][7]** centre image in tile. (optional, default `false`)
* `options.center` **[boolean][7]** alternative spelling of centre. (optional, default `false`)
* `options.id` **[string][2]** when `layout` is `iiif`, sets the `@id` attribute of `info.json` (optional, default `'https://example.com/iiif'`)
### Examples
@@ -441,7 +483,7 @@ sharp('input.tiff')
});
```
- Throws **[Error][4]** Invalid parameters
* Throws **[Error][4]** Invalid parameters
Returns **Sharp**

View File

@@ -6,49 +6,50 @@ Resize image to `width`, `height` or `width x height`.
When both a `width` and `height` are provided, the possible methods by which the image should **fit** these are:
- `cover`: (default) Preserving aspect ratio, ensure the image covers both provided dimensions by cropping/clipping to fit.
- `contain`: Preserving aspect ratio, contain within both provided dimensions using "letterboxing" where necessary.
- `fill`: Ignore the aspect ratio of the input and stretch to both provided dimensions.
- `inside`: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified.
- `outside`: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified.
* `cover`: (default) Preserving aspect ratio, ensure the image covers both provided dimensions by cropping/clipping to fit.
* `contain`: Preserving aspect ratio, contain within both provided dimensions using "letterboxing" where necessary.
* `fill`: Ignore the aspect ratio of the input and stretch to both provided dimensions.
* `inside`: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified.
* `outside`: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified.
Some of these values are based on the [object-fit][1] CSS property.
When using a `fit` of `cover` or `contain`, the default **position** is `centre`. Other options are:
- `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`.
- `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`.
- `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy.
* `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`.
* `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`.
* `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy.
Some of these values are based on the [object-position][2] CSS property.
The experimental strategy-based approach resizes so one dimension is at its target length
then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.
- `entropy`: focus on the region with the highest [Shannon entropy][3].
- `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
* `entropy`: focus on the region with the highest [Shannon entropy][3].
* `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
Possible interpolation kernels are:
- `nearest`: Use [nearest neighbour interpolation][4].
- `cubic`: Use a [Catmull-Rom spline][5].
- `mitchell`: Use a [Mitchell-Netravali spline][6].
- `lanczos2`: Use a [Lanczos kernel][7] with `a=2`.
- `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
* `nearest`: Use [nearest neighbour interpolation][4].
* `cubic`: Use a [Catmull-Rom spline][5].
* `mitchell`: Use a [Mitchell-Netravali spline][6].
* `lanczos2`: Use a [Lanczos kernel][7] with `a=2`.
* `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
### Parameters
- `width` **[number][8]?** pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height.
- `height` **[number][8]?** pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width.
- `options` **[Object][9]?**
- `options.width` **[String][10]?** alternative means of specifying `width`. If both are present this take priority.
- `options.height` **[String][10]?** alternative means of specifying `height`. If both are present this take priority.
- `options.fit` **[String][10]** how the image should be resized to fit both provided dimensions, one of `cover`, `contain`, `fill`, `inside` or `outside`. (optional, default `'cover'`)
- `options.position` **[String][10]** position, gravity or strategy to use when `fit` is `cover` or `contain`. (optional, default `'centre'`)
- `options.background` **([String][10] \| [Object][9])** background colour when using a `fit` of `contain`, parsed by the [color][11] module, defaults to black without transparency. (optional, default `{r:0,g:0,b:0,alpha:1}`)
- `options.kernel` **[String][10]** the kernel to use for image reduction. (optional, default `'lanczos3'`)
- `options.withoutEnlargement` **[Boolean][12]** do not enlarge if the width _or_ height are already less than the specified dimensions, equivalent to GraphicsMagick's `>` geometry option. (optional, default `false`)
- `options.fastShrinkOnLoad` **[Boolean][12]** take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern on some images. (optional, default `true`)
* `width` **[number][8]?** pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height.
* `height` **[number][8]?** pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width.
* `options` **[Object][9]?**
* `options.width` **[String][10]?** alternative means of specifying `width`. If both are present this take priority.
* `options.height` **[String][10]?** alternative means of specifying `height`. If both are present this take priority.
* `options.fit` **[String][10]** how the image should be resized to fit both provided dimensions, one of `cover`, `contain`, `fill`, `inside` or `outside`. (optional, default `'cover'`)
* `options.position` **[String][10]** position, gravity or strategy to use when `fit` is `cover` or `contain`. (optional, default `'centre'`)
* `options.background` **([String][10] | [Object][9])** background colour when using a `fit` of `contain`, parsed by the [color][11] module, defaults to black without transparency. (optional, default `{r:0,g:0,b:0,alpha:1}`)
* `options.kernel` **[String][10]** the kernel to use for image reduction. (optional, default `'lanczos3'`)
* `options.withoutEnlargement` **[Boolean][12]** do not enlarge if the width *or* height are already less than the specified dimensions, equivalent to GraphicsMagick's `>` geometry option. (optional, default `false`)
* `options.fastShrinkOnLoad` **[Boolean][12]** take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern on some images. (optional, default `true`)
### Examples
@@ -125,7 +126,7 @@ const scaleByHalf = await sharp(input)
);
```
- Throws **[Error][13]** Invalid parameters
* Throws **[Error][13]** Invalid parameters
Returns **Sharp**
@@ -136,12 +137,13 @@ This operation will always occur after resizing and extraction, if any.
### Parameters
- `extend` **([number][8] \| [Object][9])** single pixel count to add to all edges or an Object with per-edge counts
- `extend.top` **[number][8]** (optional, default `0`)
- `extend.left` **[number][8]** (optional, default `0`)
- `extend.bottom` **[number][8]** (optional, default `0`)
- `extend.right` **[number][8]** (optional, default `0`)
- `extend.background` **([String][10] \| [Object][9])** background colour, parsed by the [color][11] module, defaults to black without transparency. (optional, default `{r:0,g:0,b:0,alpha:1}`)
* `extend` **([number][8] | [Object][9])** single pixel count to add to all edges or an Object with per-edge counts
* `extend.top` **[number][8]** (optional, default `0`)
* `extend.left` **[number][8]** (optional, default `0`)
* `extend.bottom` **[number][8]** (optional, default `0`)
* `extend.right` **[number][8]** (optional, default `0`)
* `extend.background` **([String][10] | [Object][9])** background colour, parsed by the [color][11] module, defaults to black without transparency. (optional, default `{r:0,g:0,b:0,alpha:1}`)
### Examples
@@ -170,7 +172,7 @@ sharp(input)
...
```
- Throws **[Error][13]** Invalid parameters
* Throws **[Error][13]** Invalid parameters
Returns **Sharp**
@@ -178,17 +180,18 @@ Returns **Sharp**
Extract/crop a region of the image.
- Use `extract` before `resize` for pre-resize extraction.
- Use `extract` after `resize` for post-resize extraction.
- Use `extract` before and after for both.
* Use `extract` before `resize` for pre-resize extraction.
* Use `extract` after `resize` for post-resize extraction.
* Use `extract` before and after for both.
### Parameters
- `options` **[Object][9]** describes the region to extract using integral pixel values
- `options.left` **[number][8]** zero-indexed offset from left edge
- `options.top` **[number][8]** zero-indexed offset from top edge
- `options.width` **[number][8]** width of region to extract
- `options.height` **[number][8]** height of region to extract
* `options` **[Object][9]** describes the region to extract using integral pixel values
* `options.left` **[number][8]** zero-indexed offset from left edge
* `options.top` **[number][8]** zero-indexed offset from top edge
* `options.width` **[number][8]** width of region to extract
* `options.height` **[number][8]** height of region to extract
### Examples
@@ -210,7 +213,7 @@ sharp(input)
});
```
- Throws **[Error][13]** Invalid parameters
* Throws **[Error][13]** Invalid parameters
Returns **Sharp**
@@ -224,10 +227,11 @@ will contain `trimOffsetLeft` and `trimOffsetTop` properties.
### Parameters
- `threshold` **[number][8]** the allowed difference from the top-left pixel, a number greater than zero. (optional, default `10`)
* `threshold` **[number][8]** the allowed difference from the top-left pixel, a number greater than zero. (optional, default `10`)
<!---->
- Throws **[Error][13]** Invalid parameters
* Throws **[Error][13]** Invalid parameters
Returns **Sharp**

View File

@@ -54,17 +54,18 @@ console.log(sharp.versions);
## cache
Gets or, when options are provided, sets the limits of _libvips'_ operation cache.
Gets or, when options are provided, sets the limits of *libvips'* operation cache.
Existing entries in the cache will be trimmed after any change in limits.
This method always returns cache statistics,
useful for determining how much working memory is required for a particular task.
### Parameters
- `options` **([Object][1] \| [boolean][10])** Object with the following attributes, or boolean where true uses default cache settings and false removes all caching (optional, default `true`)
- `options.memory` **[number][11]** is the maximum memory in MB to use for this cache (optional, default `50`)
- `options.files` **[number][11]** is the maximum number of files to hold open (optional, default `20`)
- `options.items` **[number][11]** is the maximum number of operations to cache (optional, default `100`)
* `options` **([Object][1] | [boolean][10])** Object with the following attributes, or boolean where true uses default cache settings and false removes all caching (optional, default `true`)
* `options.memory` **[number][11]** is the maximum memory in MB to use for this cache (optional, default `50`)
* `options.files` **[number][11]** is the maximum number of files to hold open (optional, default `20`)
* `options.items` **[number][11]** is the maximum number of operations to cache (optional, default `100`)
### Examples
@@ -83,7 +84,7 @@ Returns **[Object][1]**
## concurrency
Gets or, when a concurrency is provided, sets
the number of threads _libvips'_ should create to process each image.
the number of threads *libvips'* should create to process each image.
The default value is the number of CPU cores,
except when using glibc-based Linux without jemalloc,
@@ -98,7 +99,7 @@ This method always returns the current concurrency.
### Parameters
- `concurrency` **[number][11]?**
* `concurrency` **[number][11]?**
### Examples
@@ -114,8 +115,8 @@ Returns **[number][11]** concurrency
An EventEmitter that emits a `change` event when a task is either:
- queued, waiting for _libuv_ to provide a worker thread
- complete
* queued, waiting for *libuv* to provide a worker thread
* complete
### Examples
@@ -129,8 +130,8 @@ sharp.queue.on('change', function(queueLength) {
Provides access to internal task counters.
- queue is the number of tasks this module has queued waiting for _libuv_ to provide a worker thread from its pool.
- process is the number of resize tasks currently being processed.
* queue is the number of tasks this module has queued waiting for *libuv* to provide a worker thread from its pool.
* process is the number of resize tasks currently being processed.
### Examples
@@ -150,7 +151,7 @@ by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM N
### Parameters
- `simd` **[boolean][10]** (optional, default `true`)
* `simd` **[boolean][10]** (optional, default `true`)
### Examples

View File

@@ -4,6 +4,43 @@
Requires libvips v8.10.6
### v0.28.2 - 10th May 2021
* Allow `withMetadata` to set `density`.
[#967](https://github.com/lovell/sharp/issues/967)
* Skip shrink-on-load where one dimension <4px.
[#2653](https://github.com/lovell/sharp/issues/2653)
* Allow escaped proxy credentials.
[#2664](https://github.com/lovell/sharp/pull/2664)
[@msalettes](https://github.com/msalettes)
* Add `premultiplied` flag for raw pixel data input.
[#2685](https://github.com/lovell/sharp/pull/2685)
[@mnutt](https://github.com/mnutt)
* Detect empty input and throw a helpful error.
[#2687](https://github.com/lovell/sharp/pull/2687)
[@JakobJingleheimer](https://github.com/JakobJingleheimer)
* Add install-time flag to skip version compatibility checks.
[#2692](https://github.com/lovell/sharp/pull/2692)
[@xemle](https://github.com/xemle)
### v0.28.1 - 5th April 2021
* Ensure all installation errors are logged with a more obvious prefix.
* Allow `withMetadata` to set and update EXIF metadata.
[#650](https://github.com/lovell/sharp/issues/650)
* Add support for OME-TIFF Sub Image File Directories (subIFD).
[#2557](https://github.com/lovell/sharp/issues/2557)
* Allow `ensureAlpha` to set the alpha transparency level.
[#2634](https://github.com/lovell/sharp/issues/2634)
### v0.28.0 - 29th March 2021
* Prebuilt binaries now include mozjpeg and libimagequant (BSD 2-Clause).

View File

@@ -209,3 +209,6 @@ GitHub: https://github.com/beig
Name: Florian Busch
GitHub: https://github.com/florian-busch
Name: Matthieu Salettes
GitHub: https://github.com/msalettes

View File

@@ -19,7 +19,7 @@
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="https://pixel.plumbing/px/72x72/sharp-logo.svg">
<link rel="apple-touch-icon-precomposed" href="https://pixel.plumbing/px/57x57/sharp-logo.svg">
<link rel="author" href="/humans.txt" type="text/plain">
<link rel="preload" href="https://cdn.jsdelivr.net/gh/lovell/sharp@v0.28.0/docs/README.md" as="fetch" type="text/markdown" crossorigin>
<link rel="preload" href="https://cdn.jsdelivr.net/gh/lovell/sharp@v0.28.2/docs/README.md" as="fetch" type="text/markdown" crossorigin>
<link rel="preload" href="https://cdn.jsdelivr.net/gh/lovell/sharp@master/docs/image/sharp-logo.svg" as="image" type="image/svg+xml" crossorigin>
<link rel="dns-prefetch" href="https://pixel.plumbing">
<link rel="dns-prefetch" href="https://www.google-analytics.com">
@@ -139,7 +139,7 @@
docuteApiTitlePlugin,
docuteApiSearchPlugin
],
sourcePath: 'https://cdn.jsdelivr.net/gh/lovell/sharp@v0.28.0/docs',
sourcePath: 'https://cdn.jsdelivr.net/gh/lovell/sharp@v0.28.2/docs',
nav: [
{
title: 'Funding',

View File

@@ -49,6 +49,7 @@ The following platforms require compilation of both libvips and sharp from sourc
The architecture and platform of Node.js used for `npm install`
must be the same as the architecture and platform of Node.js used at runtime.
See the [cross-platform](#cross-platform) section if this is not the case.
When using npm v6 or earlier, the `npm install --unsafe-perm` flag must be used when installing as `root` or a `sudo` user.
@@ -70,6 +71,33 @@ When this new ARM64 CPU is made freely available
to open source projects via a CI service
then prebuilt sharp binaries can also be provided.
## Cross-platform
At `npm install` time, prebuilt binaries are automatically selected for the
current OS platform and CPU architecture, where available.
The target platform and/or architecture can be manually selected using the following flags.
```sh
npm install --platform=... --arch=... --arm-version=... sharp
```
* `--platform`: one of `linux`, `linuxmusl`, `darwin` or `win32`.
* `--arch`: one of `x64`, `ia32`, `arm` or `arm64`.
* `--arm-version`: one of `6`, `7` or `8` (`arm` defaults to `6`, `arm64` defaults to `8`).
* `--sharp-install-force`: skip version compatibility checks.
These values can also be set via environment variables,
`npm_config_platform`, `npm_config_arch`, `npm_config_arm_version`
and `SHARP_INSTALL_FORCE` respectively.
For example, if the target machine has a 64-bit ARM CPU and is running Alpine Linux,
use the following flags:
```sh
npm install --arch=arm64 --platform=linuxmusl sharp
```
## Custom libvips
To use a custom, globally-installed version of libvips instead of the provided binaries,
@@ -102,6 +130,10 @@ To install the prebuilt sharp binaries from a custom URL,
set the `sharp_binary_host` npm config option
or the `npm_config_sharp_binary_host` environment variable.
To install the prebuilt sharp binaries from a directory on the local filesystem,
set the `sharp_local_prebuilds` npm config option
or the `npm_config_sharp_local_prebuilds` environment variable.
To install the prebuilt libvips binaries from a custom URL,
set the `sharp_libvips_binary_host` npm config option
or the `npm_config_sharp_libvips_binary_host` environment variable.
@@ -119,7 +151,7 @@ See the Chinese mirror below for a further example.
## Chinese mirror
Alibaba provide a mirror site based in China containing binaries for both sharp and libvips.
A mirror site based in China, provided by Alibaba, contains binaries for both sharp and libvips.
To use this either set the following configuration:
@@ -178,8 +210,6 @@ to `false` when using the `yarn` package manager.
## AWS Lambda
Set the Lambda runtime to `nodejs12.x`.
The binaries in the `node_modules` directory of the
[deployment package](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-package.html)
must be for the Linux x64 platform.

File diff suppressed because one or more lines are too long

View File

@@ -7,7 +7,8 @@ const stream = require('stream');
const zlib = require('zlib');
const detectLibc = require('detect-libc');
const semver = require('semver');
const semverLessThan = require('semver/functions/lt');
const semverSatisfies = require('semver/functions/satisfies');
const simpleGet = require('simple-get');
const tarFs = require('tar-fs');
@@ -35,6 +36,7 @@ const { minimumLibvipsVersion, minimumLibvipsVersionLabelled } = libvips;
const distHost = process.env.npm_config_sharp_libvips_binary_host || 'https://github.com/lovell/sharp-libvips/releases/download';
const distBaseUrl = process.env.npm_config_sharp_dist_base_url || process.env.SHARP_DIST_BASE_URL || `${distHost}/v${minimumLibvipsVersionLabelled}/`;
const supportsBrotli = ('BrotliDecompress' in zlib);
const installationForced = !!(process.env.npm_config_sharp_install_force || process.env.SHARP_INSTALL_FORCE);
const fail = function (err) {
libvips.log(err);
@@ -46,6 +48,14 @@ const fail = function (err) {
process.exit(1);
};
const handleError = function (err) {
if (installationForced) {
libvips.log(`Installation warning: ${err.message}`);
} else {
throw err;
}
};
const extractTarball = function (tarPath, platformAndArch) {
const vendorPath = path.join(__dirname, '..', 'vendor');
libvips.mkdirSync(vendorPath);
@@ -95,20 +105,21 @@ try {
if (platformAndArch === 'freebsd-x64' || platformAndArch === 'openbsd-x64' || platformAndArch === 'sunos-x64') {
throw new Error(`BSD/SunOS systems require manual installation of libvips >= ${minimumLibvipsVersion}`);
}
if (detectLibc.family === detectLibc.GLIBC && detectLibc.version) {
if (semver.lt(`${detectLibc.version}.0`, `${minimumGlibcVersionByArch[arch]}.0`)) {
throw new Error(`Use with glibc ${detectLibc.version} requires manual installation of libvips >= ${minimumLibvipsVersion}`);
// Linux libc version check
if (detectLibc.family === detectLibc.GLIBC && detectLibc.version && minimumGlibcVersionByArch[arch]) {
if (semverLessThan(`${detectLibc.version}.0`, `${minimumGlibcVersionByArch[arch]}.0`)) {
handleError(new Error(`Use with glibc ${detectLibc.version} requires manual installation of libvips >= ${minimumLibvipsVersion}`));
}
}
if (detectLibc.family === detectLibc.MUSL && detectLibc.version) {
if (semver.lt(detectLibc.version, '1.1.24')) {
throw new Error(`Use with musl ${detectLibc.version} requires manual installation of libvips >= ${minimumLibvipsVersion}`);
if (semverLessThan(detectLibc.version, '1.1.24')) {
handleError(new Error(`Use with musl ${detectLibc.version} requires manual installation of libvips >= ${minimumLibvipsVersion}`));
}
}
// Node.js minimum version check
const supportedNodeVersion = process.env.npm_package_engines_node || require('../package.json').engines.node;
if (!semver.satisfies(process.versions.node, supportedNodeVersion)) {
throw new Error(`Expected Node.js version ${supportedNodeVersion} but found ${process.versions.node}`);
if (!semverSatisfies(process.versions.node, supportedNodeVersion)) {
handleError(new Error(`Expected Node.js version ${supportedNodeVersion} but found ${process.versions.node}`));
}
const extension = supportsBrotli ? 'br' : 'gz';
@@ -145,7 +156,9 @@ try {
tmpFileStream
.on('error', function (err) {
// Clean up temporary file
fs.unlinkSync(tarPathTemp);
try {
fs.unlinkSync(tarPathTemp);
} catch (e) {}
fail(err);
})
.on('close', function () {
@@ -157,7 +170,7 @@ try {
fs.copyFileSync(tarPathTemp, tarPathCache);
fs.unlinkSync(tarPathTemp);
}
extractTarball(tarPathCache);
extractTarball(tarPathCache, platformAndArch);
});
}
});

View File

@@ -25,7 +25,7 @@ module.exports = function () {
? tunnelAgent.httpsOverHttps
: tunnelAgent.httpsOverHttp;
const proxyAuth = proxy.username && proxy.password
? `${proxy.username}:${proxy.password}`
? `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`
: null;
return tunnel({
proxy: {

View File

@@ -30,21 +30,39 @@ function removeAlpha () {
}
/**
* Ensure alpha channel, if missing. The added alpha channel will be fully opaque. This is a no-op if the image already has an alpha channel.
* Ensure the output image has an alpha transparency channel.
* If missing, the added alpha channel will have the specified
* transparency level, defaulting to fully-opaque (1).
* This is a no-op if the image already has an alpha channel.
*
* @since 0.21.2
*
* @example
* sharp('rgb.jpg')
* // rgba.png will be a 4 channel image with a fully-opaque alpha channel
* await sharp('rgb.jpg')
* .ensureAlpha()
* .toFile('rgba.png', function(err, info) {
* // rgba.png is a 4 channel image with a fully opaque alpha channel
* });
* .toFile('rgba.png')
*
* @example
* // rgba is a 4 channel image with a fully-transparent alpha channel
* const rgba = await sharp(rgb)
* .ensureAlpha(0)
* .toBuffer();
*
* @param {number} [alpha=1] - alpha transparency level (0=fully-transparent, 1=fully-opaque)
* @returns {Sharp}
* @throws {Error} Invalid alpha transparency level
*/
function ensureAlpha () {
this.options.ensureAlpha = true;
function ensureAlpha (alpha) {
if (is.defined(alpha)) {
if (is.number(alpha) && is.inRange(alpha, 0, 1)) {
this.options.ensureAlpha = alpha;
} else {
throw is.invalidParameterError('alpha', 'number between 0 and 1', alpha);
}
} else {
this.options.ensureAlpha = 1;
}
return this;
}

View File

@@ -132,12 +132,15 @@ const debuglog = util.debuglog('sharp');
* @param {number} [options.density=72] - number representing the DPI for vector images in the range 1 to 100000.
* @param {number} [options.pages=1] - number of pages to extract for multi-page input (GIF, WebP, AVIF, TIFF, PDF), use -1 for all pages.
* @param {number} [options.page=0] - page number to start extracting from for multi-page input (GIF, WebP, AVIF, TIFF, PDF), zero based.
* @param {number} [options.subifd=-1] - subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image.
* @param {number} [options.level=0] - level to extract from a multi-level input (OpenSlide), zero based.
* @param {boolean} [options.animated=false] - Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`).
* @param {Object} [options.raw] - describes raw pixel input image data. See `raw()` for pixel ordering.
* @param {number} [options.raw.width] - integral number of pixels wide.
* @param {number} [options.raw.height] - integral number of pixels high.
* @param {number} [options.raw.channels] - integral number of channels, between 1 and 4.
* @param {boolean} [options.raw.premultiplied] - specifies that the raw input has already been premultiplied, set to `true`
* to avoid sharp premultiplying the image. (optional, default `false`)
* @param {Object} [options.create] - describes a new image to be created.
* @param {number} [options.create.width] - integral number of pixels wide.
* @param {number} [options.create.height] - integral number of pixels high.
@@ -221,7 +224,7 @@ const Sharp = function (input, options) {
joinChannelIn: [],
extractChannel: -1,
removeAlpha: false,
ensureAlpha: false,
ensureAlpha: -1,
colourspace: 'srgb',
composite: [],
// output
@@ -230,7 +233,9 @@ const Sharp = function (input, options) {
streamOut: false,
withMetadata: false,
withMetadataOrientation: -1,
withMetadataDensity: 0,
withMetadataIcc: '',
withMetadataStrs: {},
resolveWithObject: false,
// output format
jpegQuality: 80,

View File

@@ -9,9 +9,9 @@ const sharp = require('../build/Release/sharp.node');
* @private
*/
function _inputOptionsFromObject (obj) {
const { raw, density, limitInputPixels, sequentialRead, failOnError, animated, page, pages } = obj;
return [raw, density, limitInputPixels, sequentialRead, failOnError, animated, page, pages].some(is.defined)
? { raw, density, limitInputPixels, sequentialRead, failOnError, animated, page, pages }
const { raw, density, limitInputPixels, sequentialRead, failOnError, animated, page, pages, subifd } = obj;
return [raw, density, limitInputPixels, sequentialRead, failOnError, animated, page, pages, subifd].some(is.defined)
? { raw, density, limitInputPixels, sequentialRead, failOnError, animated, page, pages, subifd }
: undefined;
}
@@ -30,9 +30,15 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
inputDescriptor.file = input;
} else if (is.buffer(input)) {
// Buffer
if (input.length === 0) {
throw Error('Input Buffer is empty');
}
inputDescriptor.buffer = input;
} else if (is.uint8Array(input)) {
// Uint8Array or Uint8ClampedArray
if (input.length === 0) {
throw Error('Input Bit Array is empty');
}
inputDescriptor.buffer = Buffer.from(input.buffer);
} else if (is.plainObject(input) && !is.defined(inputOptions)) {
// Plain Object descriptor, e.g. create
@@ -97,6 +103,7 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
inputDescriptor.rawWidth = inputOptions.raw.width;
inputDescriptor.rawHeight = inputOptions.raw.height;
inputDescriptor.rawChannels = inputOptions.raw.channels;
inputDescriptor.rawPremultiplied = !!inputOptions.raw.premultiplied;
} else {
throw new Error('Expected width, height and channels for raw pixel input');
}
@@ -131,6 +138,14 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
throw is.invalidParameterError('level', 'integer between 0 and 256', inputOptions.level);
}
}
// Sub Image File Directory (TIFF)
if (is.defined(inputOptions.subifd)) {
if (is.integer(inputOptions.subifd) && is.inRange(inputOptions.subifd, -1, 100000)) {
inputDescriptor.subifd = inputOptions.subifd;
} else {
throw is.invalidParameterError('subifd', 'integer between -1 and 100000', inputOptions.subifd);
}
}
// Create new image
if (is.defined(inputOptions.create)) {
if (
@@ -255,6 +270,7 @@ function _isStreamInput () {
* - `delay`: Delay in ms between each page in an animated image, provided as an array of integers.
* - `pagePrimary`: Number of the primary page in a HEIF image
* - `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide
* - `subifds`: Number of Sub Image File Directories in an OME-TIFF image
* - `hasProfile`: Boolean indicating the presence of an embedded ICC profile
* - `hasAlpha`: Boolean indicating the presence of an alpha transparency channel
* - `orientation`: Number value of the EXIF Orientation header, if present

View File

@@ -4,13 +4,15 @@ const fs = require('fs');
const os = require('os');
const path = require('path');
const spawnSync = require('child_process').spawnSync;
const semver = require('semver');
const semverCoerce = require('semver/functions/coerce');
const semverGreaterThanOrEqualTo = require('semver/functions/gte');
const platform = require('./platform');
const env = process.env;
const minimumLibvipsVersionLabelled = env.npm_package_config_libvips || /* istanbul ignore next */
require('../package.json').config.libvips;
const minimumLibvipsVersion = semver.coerce(minimumLibvipsVersionLabelled).version;
const minimumLibvipsVersion = semverCoerce(minimumLibvipsVersionLabelled).version;
const spawnSyncOptions = {
encoding: 'utf8',
@@ -39,7 +41,7 @@ const cachePath = function () {
const log = function (item) {
if (item instanceof Error) {
console.error(`sharp: ${item.message}`);
console.error(`sharp: Installation error: ${item.message}`);
} else {
console.log(`sharp: ${item}`);
}
@@ -105,7 +107,7 @@ const useGlobalLibvips = function () {
}
const globalVipsVersion = globalLibvipsVersion();
return !!globalVipsVersion && /* istanbul ignore next */
semver.gte(globalVipsVersion, minimumLibvipsVersion);
semverGreaterThanOrEqualTo(globalVipsVersion, minimumLibvipsVersion);
};
module.exports = {

View File

@@ -272,7 +272,7 @@ function blur (sigma) {
*
* @example
* await sharp(rgbaInput)
* .flatten('#F0A703')
* .flatten({background: '#F0A703' })
* .toBuffer();
*
* @param {Object} [options]

View File

@@ -148,9 +148,29 @@ function toBuffer (options, callback) {
* .toFile('output-with-metadata.jpg')
* .then(info => { ... });
*
* @example
* // Set "IFD0-Copyright" in output EXIF metadata
* const data = await sharp(input)
* .withMetadata({
* exif: {
* IFD0: {
* Copyright: 'Wernham Hogg'
* }
* }
* })
* .toBuffer();
*
* * @example
* // Set output metadata to 96 DPI
* const data = await sharp(input)
* .withMetadata({ density: 96 })
* .toBuffer();
*
* @param {Object} [options]
* @param {number} [options.orientation] value between 1 and 8, used to update the EXIF `Orientation` tag.
* @param {string} [options.icc] filesystem path to output ICC profile, defaults to sRGB.
* @param {Object<Object>} [options.exif={}] Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.
* @param {number} [options.density] Number of pixels per inch (DPI).
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
@@ -164,6 +184,13 @@ function withMetadata (options) {
throw is.invalidParameterError('orientation', 'integer between 1 and 8', options.orientation);
}
}
if (is.defined(options.density)) {
if (is.number(options.density) && options.density > 0) {
this.options.withMetadataDensity = options.density;
} else {
throw is.invalidParameterError('density', 'positive number', options.density);
}
}
if (is.defined(options.icc)) {
if (is.string(options.icc)) {
this.options.withMetadataIcc = options.icc;
@@ -171,6 +198,25 @@ function withMetadata (options) {
throw is.invalidParameterError('icc', 'string filesystem path to ICC profile', options.icc);
}
}
if (is.defined(options.exif)) {
if (is.object(options.exif)) {
for (const [ifd, entries] of Object.entries(options.exif)) {
if (is.object(entries)) {
for (const [k, v] of Object.entries(entries)) {
if (is.string(v)) {
this.options.withMetadataStrs[`exif-${ifd.toLowerCase()}-${k}`] = v;
} else {
throw is.invalidParameterError(`exif.${ifd}.${k}`, 'string', v);
}
}
} else {
throw is.invalidParameterError(`exif.${ifd}`, 'object', entries);
}
}
} else {
throw is.invalidParameterError('exif', 'object', options.exif);
}
}
}
return this;
}
@@ -383,6 +429,12 @@ function png (options) {
* .webp({ lossless: true })
* .toBuffer();
*
* @example
* // Optimise the file size of an animated WebP
* const outputWebp = await sharp(inputWebp, { animated: true })
* .webp({ reductionEffort: 6 })
* .toBuffer();
*
* @param {Object} [options] - output options
* @param {number} [options.quality=80] - quality, integer 1-100
* @param {number} [options.alphaQuality=100] - quality of alpha layer, integer 0-100

View File

@@ -1,7 +1,7 @@
{
"name": "sharp",
"description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, AVIF and TIFF images",
"version": "0.28.0",
"version": "0.28.2",
"author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://github.com/lovell/sharp",
"contributors": [
@@ -74,12 +74,15 @@
"Christian Flintrup <chr@gigahost.dk>",
"Manan Jadhav <manan@motionden.com>",
"Leon Radley <leon@radley.se>",
"alza54 <alza54@thiocod.in>"
"alza54 <alza54@thiocod.in>",
"Jacob Smith <jacob@frende.me>",
"Michael Nutt <michael@nutt.im>"
],
"scripts": {
"install": "(node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)",
"clean": "rm -rf node_modules/ build/ vendor/ .nyc_output/ coverage/ test/fixtures/output.*",
"test": "semistandard && cpplint && npm run test-unit && npm run test-licensing",
"test": "npm run test-lint && npm run test-unit && npm run test-licensing",
"test-lint": "semistandard && cpplint",
"test-unit": "nyc --reporter=lcov --branches=99 mocha --slow=1000 --timeout=60000 ./test/unit/*.js",
"test-licensing": "license-checker --production --summary --onlyAllow=\"Apache-2.0;BSD;ISC;MIT\"",
"test-coverage": "./test/coverage/report.sh",
@@ -120,7 +123,7 @@
"color": "^3.1.3",
"detect-libc": "^1.0.3",
"node-addon-api": "^3.1.0",
"prebuild-install": "^6.0.1",
"prebuild-install": "^6.1.2",
"semver": "^7.3.5",
"simple-get": "^3.1.0",
"tar-fs": "^2.1.1",
@@ -130,12 +133,12 @@
"async": "^3.2.0",
"cc": "^3.0.1",
"decompress-zip": "^0.3.3",
"documentation": "^13.2.0",
"documentation": "^13.2.5",
"exif-reader": "^1.0.3",
"icc": "^2.0.0",
"license-checker": "^25.0.1",
"mocha": "^8.3.2",
"mock-fs": "^4.13.0",
"mocha": "^8.4.0",
"mock-fs": "^4.14.0",
"nyc": "^15.1.0",
"prebuild": "^10.0.1",
"rimraf": "^3.0.2",

View File

@@ -36,6 +36,9 @@ namespace sharp {
std::string AttrAsStr(Napi::Object obj, std::string attr) {
return obj.Get(attr).As<Napi::String>();
}
std::string AttrAsStr(Napi::Object obj, unsigned int const attr) {
return obj.Get(attr).As<Napi::String>();
}
uint32_t AttrAsUint32(Napi::Object obj, std::string attr) {
return obj.Get(attr).As<Napi::Number>().Uint32Value();
}
@@ -92,6 +95,7 @@ namespace sharp {
descriptor->rawChannels = AttrAsUint32(input, "rawChannels");
descriptor->rawWidth = AttrAsUint32(input, "rawWidth");
descriptor->rawHeight = AttrAsUint32(input, "rawHeight");
descriptor->rawPremultiplied = AttrAsBool(input, "rawPremultiplied");
}
// Multi-page input (GIF, TIFF, PDF)
if (HasAttr(input, "pages")) {
@@ -104,6 +108,10 @@ namespace sharp {
if (HasAttr(input, "level")) {
descriptor->level = AttrAsUint32(input, "level");
}
// subIFD (OME-TIFF)
if (HasAttr(input, "subifd")) {
descriptor->subifd = AttrAsInt32(input, "subifd");
}
// Create new image
if (HasAttr(input, "createChannels")) {
descriptor->createChannels = AttrAsUint32(input, "createChannels");
@@ -228,6 +236,7 @@ namespace sharp {
{ "VipsForeignLoadFits", ImageType::FITS },
{ "VipsForeignLoadOpenexr", ImageType::EXR },
{ "VipsForeignLoadVips", ImageType::VIPS },
{ "VipsForeignLoadVipsFile", ImageType::VIPS },
{ "VipsForeignLoadRaw", ImageType::RAW }
};
@@ -294,6 +303,9 @@ namespace sharp {
} else {
image.get_image()->Type = VIPS_INTERPRETATION_sRGB;
}
if (descriptor->rawPremultiplied) {
image = image.unpremultiply();
}
imageType = ImageType::RAW;
} else {
// Compressed data
@@ -319,6 +331,9 @@ namespace sharp {
if (imageType == ImageType::OPENSLIDE) {
option->set("level", descriptor->level);
}
if (imageType == ImageType::TIFF) {
option->set("subifd", descriptor->subifd);
}
image = VImage::new_from_buffer(descriptor->buffer, descriptor->bufferLength, nullptr, option);
if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) {
image = SetDensity(image, descriptor->density);
@@ -391,6 +406,9 @@ namespace sharp {
if (imageType == ImageType::OPENSLIDE) {
option->set("level", descriptor->level);
}
if (imageType == ImageType::TIFF) {
option->set("subifd", descriptor->subifd);
}
image = VImage::new_from_file(descriptor->file.data(), option);
if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) {
image = SetDensity(image, descriptor->density);
@@ -507,9 +525,8 @@ namespace sharp {
VImage SetDensity(VImage image, const double density) {
const double pixelsPerMm = density / 25.4;
VImage copy = image.copy();
copy.set("Xres", pixelsPerMm);
copy.set("Yres", pixelsPerMm);
copy.set(VIPS_META_RESOLUTION_UNIT, "in");
copy.get_image()->Xres = pixelsPerMm;
copy.get_image()->Yres = pixelsPerMm;
return copy;
}
@@ -799,10 +816,10 @@ namespace sharp {
/*
Ensures alpha channel, if missing.
*/
VImage EnsureAlpha(VImage image) {
VImage EnsureAlpha(VImage image, double const value) {
if (!HasAlpha(image)) {
std::vector<double> alpha;
alpha.push_back(sharp::MaximumImageAlpha(image.interpretation()));
alpha.push_back(value * sharp::MaximumImageAlpha(image.interpretation()));
image = image.bandjoin_const(alpha);
}
return image;

View File

@@ -57,9 +57,11 @@ namespace sharp {
int rawChannels;
int rawWidth;
int rawHeight;
bool rawPremultiplied;
int pages;
int page;
int level;
int subifd;
int createChannels;
int createWidth;
int createHeight;
@@ -79,9 +81,11 @@ namespace sharp {
rawChannels(0),
rawWidth(0),
rawHeight(0),
rawPremultiplied(false),
pages(1),
page(0),
level(0),
subifd(-1),
createChannels(0),
createWidth(0),
createHeight(0),
@@ -93,6 +97,7 @@ namespace sharp {
// Convenience methods to access the attributes of a Napi::Object
bool HasAttr(Napi::Object obj, std::string attr);
std::string AttrAsStr(Napi::Object obj, std::string attr);
std::string AttrAsStr(Napi::Object obj, unsigned int const attr);
uint32_t AttrAsUint32(Napi::Object obj, std::string attr);
int32_t AttrAsInt32(Napi::Object obj, std::string attr);
int32_t AttrAsInt32(Napi::Object obj, unsigned int const attr);
@@ -296,7 +301,7 @@ namespace sharp {
/*
Ensures alpha channel, if missing.
*/
VImage EnsureAlpha(VImage image);
VImage EnsureAlpha(VImage image, double const value);
} // namespace sharp

View File

@@ -86,6 +86,9 @@ class MetadataWorker : public Napi::AsyncWorker {
baton->levels.push_back(std::pair<int, int>(width, height));
}
}
if (image.get_typeof(VIPS_META_N_SUBIFDS) == G_TYPE_INT) {
baton->subifds = image.get_int(VIPS_META_N_SUBIFDS);
}
baton->hasProfile = sharp::HasProfile(image);
// Derived attributes
baton->hasAlpha = sharp::HasAlpha(image);
@@ -203,6 +206,9 @@ class MetadataWorker : public Napi::AsyncWorker {
}
info.Set("levels", levels);
}
if (baton->subifds > 0) {
info.Set("subifds", baton->subifds);
}
info.Set("hasProfile", baton->hasProfile);
info.Set("hasAlpha", baton->hasAlpha);
if (baton->orientation > 0) {

View File

@@ -41,6 +41,7 @@ struct MetadataBaton {
int pagePrimary;
std::string compression;
std::vector<std::pair<int, int>> levels;
int subifds;
bool hasProfile;
bool hasAlpha;
int orientation;
@@ -68,6 +69,7 @@ struct MetadataBaton {
pageHeight(0),
loop(-1),
pagePrimary(-1),
subifds(0),
hasProfile(false),
hasAlpha(false),
orientation(0),

View File

@@ -226,7 +226,8 @@ class PipelineWorker : public Napi::AsyncWorker {
if (
xshrink == yshrink && xshrink >= 2 * shrink_on_load_factor &&
(inputImageType == sharp::ImageType::JPEG || inputImageType == sharp::ImageType::WEBP) &&
baton->gamma == 0 && baton->topOffsetPre == -1 && baton->trimThreshold == 0.0
baton->gamma == 0 && baton->topOffsetPre == -1 && baton->trimThreshold == 0.0 &&
image.width() > 3 && image.height() > 3
) {
if (xshrink >= 8 * shrink_on_load_factor) {
xfactor = xfactor / 8;
@@ -346,7 +347,7 @@ class PipelineWorker : public Napi::AsyncWorker {
bool const shouldModulate = baton->brightness != 1.0 || baton->saturation != 1.0 || baton->hue != 0.0;
if (shouldComposite && !sharp::HasAlpha(image)) {
image = sharp::EnsureAlpha(image);
image = sharp::EnsureAlpha(image, 1);
}
bool const shouldPremultiplyAlpha = sharp::HasAlpha(image) &&
@@ -594,7 +595,7 @@ class PipelineWorker : public Napi::AsyncWorker {
// Ensure image to composite is sRGB with premultiplied alpha
compositeImage = compositeImage.colourspace(VIPS_INTERPRETATION_sRGB);
if (!sharp::HasAlpha(compositeImage)) {
compositeImage = sharp::EnsureAlpha(compositeImage);
compositeImage = sharp::EnsureAlpha(compositeImage, 1);
}
if (!composite->premultiplied) compositeImage = compositeImage.premultiply();
// Calculate position
@@ -691,8 +692,8 @@ class PipelineWorker : public Napi::AsyncWorker {
}
// Ensure alpha channel, if missing
if (baton->ensureAlpha) {
image = sharp::EnsureAlpha(image);
if (baton->ensureAlpha != -1) {
image = sharp::EnsureAlpha(image, baton->ensureAlpha);
}
// Convert image to sRGB, if not already
@@ -717,11 +718,21 @@ class PipelineWorker : public Napi::AsyncWorker {
->set("input_profile", "srgb")
->set("intent", VIPS_INTENT_PERCEPTUAL));
}
// Override EXIF Orientation tag
if (baton->withMetadata && baton->withMetadataOrientation != -1) {
image = sharp::SetExifOrientation(image, baton->withMetadataOrientation);
}
// Override pixel density
if (baton->withMetadataDensity > 0) {
image = sharp::SetDensity(image, baton->withMetadataDensity);
}
// Metadata key/value pairs, e.g. EXIF
if (!baton->withMetadataStrs.empty()) {
image = image.copy();
for (const auto& s : baton->withMetadataStrs) {
image.set(s.first.data(), s.second.data());
}
}
// Number of channels used in output image
baton->channels = image.bands();
@@ -1341,7 +1352,7 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
baton->affineInterpolator = vips::VInterpolate::new_from_name(sharp::AttrAsStr(options, "affineInterpolator").data());
baton->removeAlpha = sharp::AttrAsBool(options, "removeAlpha");
baton->ensureAlpha = sharp::AttrAsBool(options, "ensureAlpha");
baton->ensureAlpha = sharp::AttrAsDouble(options, "ensureAlpha");
if (options.Has("boolean")) {
baton->boolean = sharp::CreateInputDescriptor(options.Get("boolean").As<Napi::Object>());
baton->booleanOp = sharp::GetBooleanOperation(sharp::AttrAsStr(options, "booleanOp"));
@@ -1378,7 +1389,14 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
baton->fileOut = sharp::AttrAsStr(options, "fileOut");
baton->withMetadata = sharp::AttrAsBool(options, "withMetadata");
baton->withMetadataOrientation = sharp::AttrAsUint32(options, "withMetadataOrientation");
baton->withMetadataDensity = sharp::AttrAsDouble(options, "withMetadataDensity");
baton->withMetadataIcc = sharp::AttrAsStr(options, "withMetadataIcc");
Napi::Object mdStrs = options.Get("withMetadataStrs").As<Napi::Object>();
Napi::Array mdStrKeys = mdStrs.GetPropertyNames();
for (unsigned int i = 0; i < mdStrKeys.Length(); i++) {
std::string k = sharp::AttrAsStr(mdStrKeys, i);
baton->withMetadataStrs.insert(std::make_pair(k, sharp::AttrAsStr(mdStrs, k)));
}
// Format-specific
baton->jpegQuality = sharp::AttrAsUint32(options, "jpegQuality");
baton->jpegProgressive = sharp::AttrAsBool(options, "jpegProgressive");

View File

@@ -18,6 +18,7 @@
#include <memory>
#include <string>
#include <vector>
#include <unordered_map>
#include <napi.h>
#include <vips/vips8>
@@ -167,7 +168,9 @@ struct PipelineBaton {
std::string err;
bool withMetadata;
int withMetadataOrientation;
double withMetadataDensity;
std::string withMetadataIcc;
std::unordered_map<std::string, std::string> withMetadataStrs;
std::unique_ptr<double[]> convKernel;
int convKernelWidth;
int convKernelHeight;
@@ -178,7 +181,7 @@ struct PipelineBaton {
VipsOperationBoolean bandBoolOp;
int extractChannel;
bool removeAlpha;
bool ensureAlpha;
double ensureAlpha;
VipsInterpretation colourspace;
int pageHeight;
std::vector<int> delay;
@@ -288,6 +291,7 @@ struct PipelineBaton {
heifLossless(false),
withMetadata(false),
withMetadataOrientation(-1),
withMetadataDensity(0.0),
convKernelWidth(0),
convKernelHeight(0),
convKernelScale(0.0),
@@ -297,7 +301,7 @@ struct PipelineBaton {
bandBoolOp(VIPS_OPERATION_BOOLEAN_LAST),
extractChannel(-1),
removeAlpha(false),
ensureAlpha(false),
ensureAlpha(-1.0),
colourspace(VIPS_INTERPRETATION_LAST),
pageHeight(0),
delay{-1},

View File

@@ -90,6 +90,7 @@ module.exports = {
inputPngEmbed: getPath('embedgravitybird.png'), // Released to sharp under a CC BY 4.0
inputPngRGBWithAlpha: getPath('2569067123_aca715a2ee_o.png'), // http://www.flickr.com/photos/grizdave/2569067123/ (same as inputJpg)
inputPngImageInAlpha: getPath('image-in-alpha.png'), // https://github.com/lovell/sharp/issues/1597
inputPngSolidAlpha: getPath('with-alpha.png'), // https://github.com/lovell/sharp/issues/1599
inputWebP: getPath('4.webp'), // http://www.gstatic.com/webp/gallery/4.webp
inputWebPWithTransparency: getPath('5_webp_a.webp'), // http://www.gstatic.com/webp/gallery3/5_webp_a.webp

BIN
test/fixtures/with-alpha.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -19,6 +19,17 @@ describe('HTTP agent', function () {
assert.strictEqual(443, proxy.defaultPort);
});
it('HTTPS proxy with auth from HTTPS_PROXY using credentials containing special characters', function () {
process.env.HTTPS_PROXY = 'https://user,:pass=@secure:123';
const proxy = agent();
delete process.env.HTTPS_PROXY;
assert.strictEqual('object', typeof proxy);
assert.strictEqual('secure', proxy.options.proxy.host);
assert.strictEqual(123, proxy.options.proxy.port);
assert.strictEqual('user,:pass=', proxy.options.proxy.proxyAuth);
assert.strictEqual(443, proxy.defaultPort);
});
it('HTTP proxy without auth from npm_config_proxy', function () {
process.env.npm_config_proxy = 'http://plaintext:456';
const proxy = agent();

View File

@@ -155,4 +155,27 @@ describe('Alpha transparency', function () {
});
}));
});
it('Valid ensureAlpha value used for alpha channel', async () => {
const background = { r: 255, g: 0, b: 0 };
const [r, g, b, alpha] = await sharp({
create: {
width: 8,
height: 8,
channels: 3,
background
}
})
.ensureAlpha(0.5)
.raw()
.toBuffer();
assert.deepStrictEqual({ r, g, b, alpha }, { ...background, alpha: 127 });
});
it('Invalid ensureAlpha value throws', async () => {
assert.throws(() => {
sharp().ensureAlpha('fail');
});
});
});

View File

@@ -335,17 +335,6 @@ describe('Input/output', function () {
});
});
it('Fail when input is empty Buffer', function (done) {
sharp(Buffer.alloc(0)).toBuffer().then(function () {
assert(false);
done();
}).catch(function (err) {
assert(err instanceof Error);
assert.strictEqual('Input buffer contains unsupported image format', err.message);
done();
});
});
it('Fail when input is invalid Buffer', function (done) {
sharp(Buffer.from([0x1, 0x2, 0x3, 0x4])).toBuffer().then(function () {
assert(false);
@@ -718,6 +707,19 @@ describe('Input/output', function () {
sharp({ level: -1 });
}, /Expected integer between 0 and 256 for level but received -1 of type number/);
});
it('Valid subifd property', function () {
sharp({ subifd: 1 });
});
it('Invalid subifd property (string) throws', function () {
assert.throws(function () {
sharp({ subifd: '1' });
}, /Expected integer between -1 and 100000 for subifd but received 1 of type string/);
});
it('Invalid subifd property (float) throws', function () {
assert.throws(function () {
sharp({ subifd: 1.2 });
}, /Expected integer between -1 and 100000 for subifd but received 1.2 of type number/);
});
});
describe('create new image', function () {

View File

@@ -125,7 +125,7 @@ describe('libvips binaries', function () {
it('logs an error message', function (done) {
console.error = function (msg) {
assert.strictEqual(msg, 'sharp: problem');
assert.strictEqual(msg, 'sharp: Installation error: problem');
done();
};
libvips.log(new Error('problem'));

View File

@@ -240,40 +240,38 @@ describe('Image metadata', function () {
})
);
it('GIF via giflib', function (done) {
it('GIF', function (done) {
sharp(fixtures.inputGif).metadata(function (err, metadata) {
if (err) throw err;
assert.strictEqual('gif', metadata.format);
assert.strictEqual('undefined', typeof metadata.size);
assert.strictEqual(800, metadata.width);
assert.strictEqual(533, metadata.height);
assert.strictEqual(3, metadata.channels);
assert.strictEqual(true, [3, 4].includes(metadata.channels)); // libvips 8.11.0 = 4
assert.strictEqual('uchar', metadata.depth);
assert.strictEqual('undefined', typeof metadata.density);
assert.strictEqual('undefined', typeof metadata.chromaSubsampling);
assert.strictEqual(false, metadata.isProgressive);
assert.strictEqual(false, metadata.hasProfile);
assert.strictEqual(false, metadata.hasAlpha);
assert.strictEqual('undefined', typeof metadata.orientation);
assert.strictEqual('undefined', typeof metadata.exif);
assert.strictEqual('undefined', typeof metadata.icc);
done();
});
});
it('GIF grey+alpha via giflib', function (done) {
it('GIF grey+alpha', function (done) {
sharp(fixtures.inputGifGreyPlusAlpha).metadata(function (err, metadata) {
if (err) throw err;
assert.strictEqual('gif', metadata.format);
assert.strictEqual('undefined', typeof metadata.size);
assert.strictEqual(2, metadata.width);
assert.strictEqual(1, metadata.height);
assert.strictEqual(2, metadata.channels);
assert.strictEqual(true, [2, 4].includes(metadata.channels)); // libvips 8.11.0 = 4
assert.strictEqual('uchar', metadata.depth);
assert.strictEqual('undefined', typeof metadata.density);
assert.strictEqual('undefined', typeof metadata.chromaSubsampling);
assert.strictEqual(false, metadata.isProgressive);
assert.strictEqual(false, metadata.hasProfile);
assert.strictEqual(true, metadata.hasAlpha);
assert.strictEqual('undefined', typeof metadata.orientation);
assert.strictEqual('undefined', typeof metadata.exif);
assert.strictEqual('undefined', typeof metadata.icc);
@@ -322,7 +320,7 @@ describe('Image metadata', function () {
assert.strictEqual(isProgressive, false);
assert.strictEqual(pages, 10);
assert.strictEqual(pageHeight, 285);
assert.strictEqual(loop, 3);
assert.strictEqual(true, [2, 3].includes(loop)); // libvips 8.11.0 = 2
assert.deepStrictEqual(delay, [...Array(9).fill(3000), 15000]);
assert.strictEqual(hasProfile, false);
assert.strictEqual(hasAlpha, true);
@@ -599,6 +597,68 @@ describe('Image metadata', function () {
});
});
it('Add EXIF metadata to JPEG', async () => {
const data = await sharp({
create: {
width: 8,
height: 8,
channels: 3,
background: 'red'
}
})
.jpeg()
.withMetadata({
exif: {
IFD0: { Software: 'sharp' },
IFD2: { ExposureTime: '0.2' }
}
})
.toBuffer();
const { exif } = await sharp(data).metadata();
const parsedExif = exifReader(exif);
assert.strictEqual(parsedExif.image.Software, 'sharp');
assert.strictEqual(parsedExif.exif.ExposureTime, 0.2);
});
it('Set density of JPEG', async () => {
const data = await sharp({
create: {
width: 8,
height: 8,
channels: 3,
background: 'red'
}
})
.withMetadata({
density: 300
})
.jpeg()
.toBuffer();
const { density } = await sharp(data).metadata();
assert.strictEqual(density, 300);
});
it('Set density of PNG', async () => {
const data = await sharp({
create: {
width: 8,
height: 8,
channels: 3,
background: 'red'
}
})
.withMetadata({
density: 96
})
.png()
.toBuffer();
const { density } = await sharp(data).metadata();
assert.strictEqual(density, 96);
});
it('chromaSubsampling 4:4:4:4 CMYK JPEG', function () {
return sharp(fixtures.inputJpgWithCmykProfile)
.metadata()
@@ -712,10 +772,35 @@ describe('Image metadata', function () {
sharp().withMetadata({ orientation: 9 });
});
});
it('Non-numeric density', function () {
assert.throws(function () {
sharp().withMetadata({ density: '1' });
});
});
it('Negative density', function () {
assert.throws(function () {
sharp().withMetadata({ density: -1 });
});
});
it('Non string icc', function () {
assert.throws(function () {
sharp().withMetadata({ icc: true });
});
});
it('Non object exif', function () {
assert.throws(function () {
sharp().withMetadata({ exif: false });
});
});
it('Non string value in object exif', function () {
assert.throws(function () {
sharp().withMetadata({ exif: { ifd0: false } });
});
});
it('Non string value in nested object exif', function () {
assert.throws(function () {
sharp().withMetadata({ exif: { ifd0: { fail: false } } });
});
});
});
});

View File

@@ -32,23 +32,21 @@ describe('Platform-detection', function () {
delete process.env.npm_config_arch;
});
it('Can detect ARM version via process.config', function () {
process.env.npm_config_arch = 'arm';
const armVersion = process.config.variables.arm_version;
process.config.variables.arm_version = 'test';
assert.strictEqual('armvtest', platform().split('-')[1]);
process.config.variables.arm_version = armVersion;
delete process.env.npm_config_arch;
});
if (process.config.variables.arm_version) {
it('Can detect ARM version via process.config', function () {
process.env.npm_config_arch = 'arm';
assert.strictEqual(`armv${process.config.variables.arm_version}`, platform().split('-')[1]);
delete process.env.npm_config_arch;
});
}
it('Defaults to ARMv6 for 32-bit', function () {
process.env.npm_config_arch = 'arm';
const armVersion = process.config.variables.arm_version;
delete process.config.variables.arm_version;
assert.strictEqual('armv6', platform().split('-')[1]);
process.config.variables.arm_version = armVersion;
delete process.env.npm_config_arch;
});
if (!process.config.variables.arm_version) {
it('Defaults to ARMv6 for 32-bit', function () {
process.env.npm_config_arch = 'arm';
assert.strictEqual('armv6', platform().split('-')[1]);
delete process.env.npm_config_arch;
});
}
it('Defaults to ARMv8 for 64-bit', function () {
process.env.npm_config_arch = 'arm64';

View File

@@ -7,6 +7,18 @@ const fixtures = require('../fixtures');
describe('Raw pixel data', function () {
describe('Raw pixel input', function () {
it('Empty data', function () {
assert.throws(function () {
sharp(Buffer.from(''));
}, /empty/);
assert.throws(function () {
sharp(new Uint8Array(0));
}, /empty/);
assert.throws(function () {
sharp(new Uint8ClampedArray(0));
}, /empty/);
});
it('Missing options', function () {
assert.throws(function () {
sharp({ raw: {} });
@@ -95,6 +107,52 @@ describe('Raw pixel data', function () {
});
});
it('RGBA premultiplied', function (done) {
// Convert to raw pixel data
sharp(fixtures.inputPngSolidAlpha)
.resize(256)
.raw()
.toBuffer(function (err, data, info) {
if (err) throw err;
assert.strictEqual(256, info.width);
assert.strictEqual(192, info.height);
assert.strictEqual(4, info.channels);
const originalData = Buffer.from(data);
// Premultiply image data
for (let i = 0; i < data.length; i += 4) {
const alpha = data[i + 3];
const norm = alpha / 255;
if (alpha < 255) {
data[i] = Math.round(data[i] * norm);
data[i + 1] = Math.round(data[i + 1] * norm);
data[i + 2] = Math.round(data[i + 2] * norm);
}
}
// Convert back to PNG
sharp(data, {
raw: {
width: info.width,
height: info.height,
channels: info.channels,
premultiplied: true
}
})
.raw()
.toBuffer(function (err, data, info) {
if (err) throw err;
assert.strictEqual(256, info.width);
assert.strictEqual(192, info.height);
assert.strictEqual(4, info.channels);
assert.equal(data.compare(originalData), 0, 'output buffer matches unpremultiplied input buffer');
done();
});
});
});
it('JPEG to raw Stream and back again', function (done) {
const width = 32;
const height = 24;

View File

@@ -605,6 +605,26 @@ describe('Resize dimensions', function () {
});
});
it('Skip shrink-on-load where one dimension <4px', async () => {
const jpeg = await sharp({
create: {
width: 100,
height: 3,
channels: 3,
background: 'red'
}
})
.jpeg()
.toBuffer();
const { info } = await sharp(jpeg)
.resize(8)
.toBuffer({ resolveWithObject: true });
assert.strictEqual(info.width, 8);
assert.strictEqual(info.height, 1);
});
it('unknown kernel throws', function () {
assert.throws(function () {
sharp().resize(null, null, { kernel: 'unknown' });