Compare commits

...

142 Commits

Author SHA1 Message Date
Lovell Fuller
92f21451c1 Upgrade to sharp-libvips v1.2.0 2025-07-08 21:58:53 +01:00
Lovell Fuller
2cd2f8430a Upgrade to libvips v8.17.1 2025-07-08 08:36:44 +01:00
Lovell Fuller
8ee8d273ee Provide XMP as a string, as well as a Buffer, where possible 2025-07-04 15:56:09 +01:00
Thibaut Patel
4e3f3792ad Add keepXmp and withXmp for control over output XMP metadata #4416 2025-07-04 15:20:32 +01:00
Lovell Fuller
df5454e7dc Add support for RAW digicam input, requires custom libvips+libraw 2025-06-30 12:14:06 +01:00
Lovell Fuller
32cf6be1b8 Docs: update benchmark results ahead of v0.34.3 2025-06-26 14:49:36 +01:00
Lovell Fuller
96dfd400b2 Tests: update benchmark environment 2025-06-26 11:16:54 +01:00
Lovell Fuller
1422798c1d Upgrade to sharp-libvips v1.2.0-rc.3 2025-06-24 13:11:12 +01:00
Lovell Fuller
e26d4e9d5b Add pageHeight param to create/new for animated input #3236 2025-06-21 11:33:52 +01:00
Lovell Fuller
852c7f8663 Clean up internal naming of format-specific input options 2025-06-17 13:24:55 +01:00
Lovell Fuller
e286e2bff9 Build format-specific input options in a single function 2025-06-17 10:15:40 +01:00
Kleis Auke Wolthuizen
76995deefa
Ensure SVG scale-on-load optimisation uses newly exposed params (#4415)
Follow-up to commit c4b1d80.
2025-06-16 15:45:19 +01:00
Lovell Fuller
e688c53659 Docs: expand info about parallelism and concurrency control #4411 2025-06-16 12:02:09 +01:00
Lovell Fuller
c4b1d80c35 Expose stylesheet and highBitdepth SVG input params 2025-06-16 11:11:02 +01:00
Lovell Fuller
f92540f134 Nest format-specific constructor params (deprecate at top-level)
- `subifd` -> `tiff.subifd`
- `level` -> `openSlide.level`
- `pdfBackground` -> `pdf.background`
2025-06-16 07:51:36 +01:00
Lovell Fuller
8c53d499f7 Expose keepDuplicateFrames GIF output parameter 2025-06-15 15:39:01 +01:00
Lovell Fuller
9392b8702b Add Magic Kernel Sharp (no relation) to resizing kernels 2025-06-15 12:53:10 +01:00
Lovell Fuller
8669fbc936 Prerelease v0.34.3-rc.0 2025-06-14 21:49:24 +01:00
Lovell Fuller
cab02463ec Remove prebuild dependency
Every CI build task tagged with 'package' now populates and
publishes the relevant npm/platform directory as an artefact.
These are aggregated by a fan-in release task at the end to
create a complete npm workspace zipfile. If the commit is
tagged, a release is created and the npm workspace attached.
2025-06-14 17:49:17 +01:00
Lovell Fuller
5374b036f3 CI: Switch ARM64 from CircleCI to GitHub Actions 2025-06-13 14:08:19 +01:00
Kleis Auke Wolthuizen
327a6d2083
Docs: update link to concurrency API (#4414) 2025-06-13 10:48:32 +01:00
Michael B. Klein
751f9992c4 Expose JPEG 2000 oneshot decoder option #4262
Requires libvips compiled with support for JP2 images

Co-authored-by: Kleis Auke Wolthuizen <github@kleisauke.nl>
2025-06-13 08:46:36 +01:00
Lovell Fuller
01f6cbbaee Upgrade to sharp-libvips v1.2.0-rc.2 2025-06-12 14:59:13 +01:00
Lovell Fuller
99be893dd4 Upgrade to libvips v8.17.0
CI: Use more recent, non-deprecated Windows runners

Bump devDeps
2025-06-12 11:27:26 +01:00
Kleis Auke Wolthuizen
4d1f7e051d
Support composite op with non-sRGB pipeline colourspace (#4412) 2025-06-12 10:32:24 +01:00
Kleis Auke Wolthuizen
91f1b58f31
Tests: Regenerate expected fixtures ahead of libvips v8.17.0 (#4402) 2025-06-08 23:31:07 +01:00
Lovell Fuller
6d04b7c1fa Release v0.34.2 2025-05-20 14:36:42 +01:00
Harshal Bhakta
d4b30b7392 Docs: Update pnpm settings documentation URLs 2025-05-20 13:57:15 +01:00
Lovell Fuller
7f03502003 Docs: upgrade to latest Astro Starlight 2025-05-20 12:57:28 +01:00
Lovell Fuller
63b0a11b5b Tests: remove a possible race condition 2025-05-19 23:21:55 +01:00
Lovell Fuller
c4d6aec48c Docs: Highlight that Windows ARM64 support is experimental 2025-05-19 22:04:08 +01:00
Lovell Fuller
e75ae970ed Ensure PDF scale-on-load optimisation uses background #4398 2025-05-16 14:38:00 +01:00
Lovell Fuller
956d72ddc0 Prerelease v0.34.2-rc.0 2025-05-14 12:37:15 +01:00
Lovell Fuller
00e66efbee Bump deps 2025-05-14 12:37:08 +01:00
Kleis Auke Wolthuizen
db3a4528eb Simplify 94481a9 2025-05-13 19:22:36 +01:00
Kleis Auke Wolthuizen
d36fd5064d Prefer use of bandjoin_const() and list-initialization 2025-05-13 19:22:36 +01:00
Kleis Auke Wolthuizen
8e17c6f518 Prefer use of vips_interpretation_max_alpha()
This also ensures we handle scRGB correctly, see:
e9c5a31552
2025-05-13 19:22:36 +01:00
Lovell Fuller
94481a967e Ensure fit=contain resizing supports multiple alpha channels #4382 2025-05-13 14:31:51 +01:00
Lovell Fuller
32872ef840 TypeScript: ensure metadata response matches reality #4383 2025-05-13 14:26:25 +01:00
Lovell Fuller
7c7f960b60 Ensure support for wide-char filenames on Windows #4391 2025-05-13 08:53:37 +01:00
Kleis Auke Wolthuizen
0b5f131df8
Improve install error help text for ppc64le architecture (#4392) 2025-05-11 08:44:15 +01:00
Hans
e922ef7450 Add support for prebuilt Windows ARM64 binaries #4375 2025-05-10 14:29:25 +01:00
Lovell Fuller
73bec629cf Docs: website already hosts images, no need to use jsdelivr 2025-05-05 13:20:49 +01:00
Lovell Fuller
758d7e63cc Docs: changelog entry for #4387 2025-05-05 13:19:10 +01:00
Stephen Tse
eba3e9aeb2
TypeScript: Add smartDeblock definition to WebpOptions (#4387) 2025-05-05 13:15:50 +01:00
Lovell Fuller
701143afb3 Ensure animated GIF to WebP conversion retains loop #3394 2025-04-23 15:43:58 +01:00
Steven D'Onfro
38b6f44611
TypeScript: Add missing properties for animated images (#4369) 2025-04-12 11:38:24 +01:00
Lovell Fuller
5b5dfbad77 Ensure pdfBackground constructor property is used #4207
Slightly refactor the way background colours are set
2025-04-09 22:21:14 +01:00
Kleis Auke Wolthuizen
a642767329
Docs: update path to api-resize-fit.svg (#4368) 2025-04-08 10:15:29 +01:00
Lovell Fuller
5cae1abe8f Release v0.34.1 2025-04-07 20:51:11 +01:00
Lovell Fuller
66ffc48707 Changelog entry for #4362 2025-04-07 13:35:40 +01:00
Steven
3c7dbb8fba
fix(types): update autoOrient type to include undefined (#4362)
This PR fixes the following error:

```
node_modules/.pnpm/sharp@0.34.0/node_modules/sharp/lib/index.d.ts(1590,15): error TS2430: Interface 'OverlayOptions' incorrectly extends interface 'SharpOptions'.
  Types of property 'autoOrient' are incompatible.
    Type 'boolean | undefined' is not assignable to type 'boolean'.
      Type 'undefined' is not assignable to type 'boolean'.
```
2025-04-04 21:53:46 +01:00
Lovell Fuller
a9e191328f Prevent glib assertions and checks #4351 2025-04-04 15:42:34 +01:00
Lovell Fuller
7323dbee98 Docs: update path to logo 2025-04-04 15:35:46 +01:00
Lovell Fuller
d7a771ca7a Docs: update path to logo 2025-04-04 15:33:34 +01:00
Lovell Fuller
7d0585fad1 Docs: remove outdated redirects/rewrites 2025-04-04 15:30:07 +01:00
Lovell Fuller
ddc1eb8c4c Release v0.34.0 (part 2 - see c26e67c) 2025-04-04 14:38:27 +01:00
Lovell Fuller
c26e67cc5b Release v0.34.0 2025-04-04 13:44:11 +01:00
Lovell Fuller
a00ee26d17 Prevent glib assertions and checks #4351 2025-04-04 12:41:33 +01:00
Lovell Fuller
6dfb60cda2 Prevent prebuilt Linux sharp binaries from exporting symbols
The prebuilt Linux libvips binaries already do this
2025-04-04 09:49:37 +01:00
Lovell Fuller
dbb7606129 Prerelease v0.34.0-rc.1 2025-04-03 15:29:32 +01:00
Quentin Pinçon
031c808aa5 Expose erode and dilate operations #4243 2025-03-27 13:17:19 +00:00
Lovell Fuller
03e1b19764 Allow wide-gamut HEIF output at higher bitdepths #4344 2025-03-21 17:01:20 +00:00
Lovell Fuller
3e41f8b65e Non-animated GIF output defaults to no-loop #3394 2025-03-21 09:36:25 +00:00
Lovell Fuller
3fd818c4b5 Prevent use of linux-x64 binaries with v1 microarchitecture 2025-03-19 19:54:53 +00:00
Lovell Fuller
d419aba76d Docs: add note about electron-forge and Webpack combo 2025-03-19 09:19:47 +00:00
Lovell Fuller
3fb1091114 Docs: bump Astro 2025-03-19 09:19:18 +00:00
Kleis Auke Wolthuizen
2035492fd9
Ensure Yarn PnP hash calculation works with pre-releases (#4347) 2025-03-16 22:05:52 +00:00
Lovell Fuller
5ee83d13e2 Prerelease v0.34.0-rc.0 2025-03-16 08:47:07 +00:00
Lovell Fuller
0d04e9dba3 Docs: update perf test results 2025-03-15 23:39:11 +00:00
Lovell Fuller
f3a4f060c6 Test: appease linter - see 3c177af 2025-03-14 12:17:37 +00:00
Lovell Fuller
3c177af594 Test: update perf test dependencies to latest
Drop squoosh as it does not support Node.js 20+
2025-03-14 11:13:30 +00:00
Lovell Fuller
9d40a64120 Fix small memory leak in new join feature - see 5ab9168 2025-03-13 14:08:00 +00:00
Lovell Fuller
fda06a62b0 CI: Upgrade emscripten SDK version to match upstream 2025-03-13 08:21:37 +00:00
Lovell Fuller
75a135eabe Upgrade to libvips v8.16.1 (prerelease) 2025-03-13 08:11:35 +00:00
Lovell Fuller
c9850afe67 Docs: add note about silencing pnpm warnings 2025-03-07 12:53:11 +00:00
Lovell Fuller
a619f29313 Docs: add note about pnpm install script permission 2025-03-02 15:47:26 +00:00
Kleis Auke Wolthuizen
9b88547f12
CI: Upgrade uraimo/run-on-arch-action to v3 (#4340)
Upgrade `uraimo/run-on-arch-action` to v3, which includes QEMU 9.2.2
from `tonistiigi/binfmt:latest` that fixes the current CI failure on
ppc64le - see:
https://github.com/uraimo/run-on-arch-action/issues/160
https://github.com/tonistiigi/binfmt/issues/215#issuecomment-2689340770
and https://gitlab.com/qemu-project/qemu/-/issues/1913.
2025-02-28 17:16:39 +00:00
Lovell Fuller
8e3ec0fc61 CI: Ensure emulated archs use latest qemu-user-static package 2025-02-23 10:06:42 +00:00
Lovell Fuller
edad89c531 Ensure removeAlpha removes all alpha channels #2266 2025-02-20 09:26:52 +00:00
Lovell Fuller
9d01dd20bf TypeScript: ensure definition of sharp.versions matches reality 2025-02-10 17:37:54 +00:00
Lovell Fuller
5ab9168813 Add support for input array to join or animate #1580 2025-02-07 13:53:27 +00:00
florentzabera
67ff930535 Add support for RGBE Radiance input, requires global libvips #4316 2025-01-21 21:06:19 +00:00
Lovell Fuller
ae5ba702a4 Bump/pin devDeps
See https://github.com/mafintosh/tar-fs/issues/113
2025-01-17 12:14:14 +00:00
Lovell Fuller
63f0ab5e20 Docs: add comment with source to all auto-generated pages 2025-01-17 12:12:43 +00:00
Lovell Fuller
eeac8d4656 Docs: migrate to Astro Starlight 2025-01-17 11:53:26 +00:00
Don Denton
14c83e1f4c Add autoOrient operation and constructor option #4144 2025-01-17 11:09:59 +00:00
Lovell Fuller
b7ff2645c4 Docs: highlight possibly breaking changes in next release 2025-01-06 11:23:25 +00:00
Lovell Fuller
79ac524262 Bump devDeps 2025-01-06 11:22:40 +00:00
Kleis Auke Wolthuizen
92083ea64c
Docs: prebuilt binaries support tile-based output (#4305)
Except when targeting WebAssembly.
2024-12-28 11:51:50 +00:00
Lovell Fuller
82dc859a49 Docs: clarify composite operation ordering #4288 2024-12-05 12:36:52 +00:00
Steven
bee1fbaa34
Tests: use of SIMD is the default behaviour (#4282) 2024-11-23 22:52:12 +00:00
Ymihere03
eba82a8ba5 Docs: separate electron installation into builder and forge sections 2024-11-18 13:09:55 +00:00
Lovell Fuller
06b08bf10f Support info.size on wide-char systems via upgrade to C++17 #3943 2024-11-04 20:18:23 +00:00
Lovell Fuller
7bdf419eb1 Upgrade to libvips v8.16.0 2024-11-04 18:10:35 +00:00
Lovell Fuller
04e7f58cea Ensure background metadata can be parsed #4090 2024-11-02 13:03:58 +00:00
Lovell Fuller
3796dd8a87 Expose new libvips/libjxl features (animation, EXIF)
Requires libvips compiled with support for libjxl
2024-10-29 15:04:14 +00:00
Lovell Fuller
8afec170ed Expose WebP smartDeblock output option 2024-10-29 14:41:58 +00:00
Lovell Fuller
3154af776e Add isPalette and bitsPerSample metadata, deprecate paletteBitDepth 2024-10-29 09:11:19 +00:00
Lovell Fuller
6480a94181 Upgrade to libvips v8.16.0-rc2
CI: Add Node.js 22
Bump devDeps
Pin node-addon-api to prevent C++17 for now
2024-10-28 10:29:22 +00:00
Lovell Fuller
9582b5036f Upgrade to libvips v8.16.0-rc1 2024-10-14 14:21:23 +01:00
David Vaness
1533bf995a TypeScript: Ensure channel counts use the correct range #4197 2024-10-13 13:37:43 +01:00
Lovell Fuller
a53d7cb6bf Upgrade to libvips v8.15.5-rc1 2024-10-09 14:43:14 +01:00
Lovell Fuller
b249357732 Docs: improve colour vs color consistency
API supports both, docs prefer colour
2024-09-06 13:40:34 +01:00
Lovell Fuller
807d9241bd Bump/replace devDeps
Add required 'module' JSDoc tag to all exports
2024-09-06 13:17:33 +01:00
Lovell Fuller
9bfaca2857 Docs: changelog and credit #4203 #4207 2024-09-06 12:59:58 +01:00
sumitd2
c26b77683a
Improve support for ppc64le architecture (#4203)
Includes CI and arch-specific npm package
2024-09-06 12:45:47 +01:00
Caleb Meredith
7ee54810d4
Add pdfBackground constructor property (#4207) 2024-09-06 12:31:43 +01:00
Lovell Fuller
fc32e0bd3f Release v0.33.5 2024-08-16 13:29:19 +01:00
Lovell Fuller
0546e48467 Docs: changelog entry for #4191 2024-08-14 16:03:08 +01:00
David Vaness
ab65b7a0f1
TypeScript: chromaSubsampling can be undefined (#4191) 2024-08-14 12:59:10 +01:00
Lovell Fuller
2474bd4163 Prerelease v0.33.5-rc.1 2024-08-14 08:49:14 +01:00
Lovell Fuller
ff2e689d35 Remove yarn v1 specifics from help text 2024-08-14 08:48:12 +01:00
Lovell Fuller
6327f13717 CI: Add yarn v1 to packaging tests 2024-08-13 18:39:54 +01:00
Lovell Fuller
f1e69a218e Prerelease v0.33.5-rc.0 2024-08-13 15:42:49 +01:00
Lovell Fuller
3c14dbb21e Minimise use of engines property to improve yarn v1 support 2024-08-13 09:37:00 +01:00
Lovell Fuller
82cebc31d0 Upgrade to libvips v8.15.3 for Linux ARMv6
Previous version erroneously targetted ARMv7
2024-08-13 08:54:05 +01:00
Lovell Fuller
ad36fa0605 Ensure emnapiInit function is exported
Prevents latest emscripten optimising it away
2024-08-12 16:27:33 +01:00
Lovell Fuller
de42667767 Upgrade to libvips v8.15.3 2024-08-12 13:19:10 +01:00
Lovell Fuller
2eb03b0049 Ensure keepIccProfile avoids ICC transform #4186 2024-08-11 09:44:53 +01:00
Lovell Fuller
f7ed9b7fb6 Tests: reduce flakiness of withIccProfile warning check 2024-07-24 08:02:16 +01:00
Lovell Fuller
7fbb988180 Bump deps 2024-07-24 07:59:55 +01:00
Lovell Fuller
490210fc60 Docs: changelog for #4172 2024-07-23 11:37:30 +01:00
Marcos Casagrande
735fee74db
Expose optional minAmplitude parameter of blur operation (#4172) 2024-07-23 11:31:11 +01:00
Lovell Fuller
67a5854b89 Docs: remove duplicate contributor 2024-07-20 20:02:11 +01:00
Lovell Fuller
f128ebdbd4 Tests: assertSimilar support for Promise and callback 2024-07-20 15:10:04 +01:00
Lovell Fuller
2672de2480 Docs: changelog and credit for #4168 2024-07-20 14:04:53 +01:00
Marcos Casagrande
67a4592756
Expose optional precision parameter of blur operation (#4168) 2024-07-20 13:53:23 +01:00
Lovell Fuller
10c6f474d9 Docs: changelog and credit for #4157 2024-07-18 18:29:38 +01:00
Nathan Keynes
d642108be2
Expose PNG metadata comments (#4157) 2024-07-18 18:08:03 +01:00
Lovell Fuller
c2a024101b CI: Upgrade Python to at least 3.8
- Latest node-gyp requires 3.8
- Python 3.7 is EOL
- Minimum glibc requirement for linux-arm will now be 2.31
  (Pi OS 'Legacy' provides Debian 11 with glibc 2.31)
2024-07-17 09:12:50 +01:00
Lovell Fuller
2f0bbebfc9 Refactor conv op to use slightly safer std::vector
Inspired by similar change to recomb op in commit 60c5c50
2024-07-05 21:34:24 +01:00
Denice
60c5c5083d Add support to recomb operation for 4x4 matrices 2024-07-05 15:31:51 +01:00
Lovell Fuller
eab7dc1b49 Bump devDeps 2024-07-01 10:16:15 +01:00
Lovell Fuller
5c7f37a0e0 Issue template: request people try newer npm first 2024-07-01 10:16:02 +01:00
Lovell Fuller
ae06f46914 Ensure sharp.format.heif is AVIF-only for prebuilt binaries 2024-06-19 09:40:02 +01:00
Lovell Fuller
9c05ea8dd2 Add pageHeight and pages to anim output response #3411 2024-06-17 16:32:49 +01:00
Don Denton
472aaf3311
Tests: ensure combination of flip and flop is covered (#4123) 2024-06-04 21:34:18 +01:00
Richard Hillmann
56fae3eda1 Ensure SHARP_FORCE_GLOBAL_LIBVIPS option works correctly #4111
Allows the install/check script to inject a logger function,
keeping its use within binding.gyp free of additional output.

Co-authored-by: Lovell Fuller <github@lovell.info>
2024-05-24 17:45:39 +01:00
Lovell Fuller
cc96c21e42 CI: Upgrade to macOS 12 (as 11 will be removed soon) 2024-05-21 11:40:11 +01:00
Lovell Fuller
1d344888ec Bump dep: emnapi 2024-05-21 11:39:41 +01:00
Lovell Fuller
bee235ee76 Docs: fix CSP 2024-05-21 11:39:08 +01:00
256 changed files with 4091 additions and 2063 deletions

View File

@ -1,105 +0,0 @@
version: 2.1
workflows:
build:
jobs:
- linux-arm64-glibc-node-18:
filters:
tags:
only: /^v.*/
- linux-arm64-musl-node-18:
filters:
tags:
only: /^v.*/
- linux-arm64-glibc-node-20:
filters:
tags:
only: /^v.*/
- linux-arm64-musl-node-20:
filters:
tags:
only: /^v.*/
jobs:
linux-arm64-glibc-node-18:
resource_class: arm.medium
machine:
image: ubuntu-2204:current
steps:
- checkout
- run: |
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 fonts-noto-core"
sudo docker exec sharp sh -c "mkdir -p /etc/apt/keyrings"
sudo docker exec sharp sh -c "curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg"
sudo docker exec sharp sh -c "echo 'deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_18.x nodistro main' | tee /etc/apt/sources.list.d/nodesource.list"
sudo docker exec sharp sh -c "apt-get update && apt-get install -y nodejs"
- run: sudo docker exec sharp sh -c "npm install --build-from-source"
- run: sudo docker exec sharp sh -c "npm test"
- run: |
sudo docker exec sharp sh -c "npm run package-from-local-build"
sudo docker exec sharp sh -c "npm pkg set \"optionalDependencies.@img/sharp-linux-arm64=file:./npm/linux-arm64\""
sudo docker exec sharp sh -c "npm run clean"
sudo docker exec sharp sh -c "npm install --ignore-scripts"
sudo docker exec sharp sh -c "npm test"
- run: "[[ -n $CIRCLE_TAG ]] && sudo docker exec --env prebuild_upload sharp sh -c \"cd src && ln -s ../package.json && npx prebuild --upload=$prebuild_upload\" || true"
linux-arm64-glibc-node-20:
resource_class: arm.medium
machine:
image: ubuntu-2204:current
steps:
- checkout
- run: |
sudo docker run -dit --name 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 fonts-noto-core"
sudo docker exec sharp sh -c "mkdir -p /etc/apt/keyrings"
sudo docker exec sharp sh -c "curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg"
sudo docker exec sharp sh -c "echo 'deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_20.x nodistro main' | tee /etc/apt/sources.list.d/nodesource.list"
sudo docker exec sharp sh -c "apt-get update && apt-get install -y nodejs"
sudo docker exec sharp sh -c "mkdir -p /mnt/sharp"
sudo docker cp . sharp:/mnt/sharp/.
- run: sudo docker exec sharp sh -c "npm install --build-from-source"
- run: sudo docker exec sharp sh -c "npm test"
- run: |
sudo docker exec sharp sh -c "npm run package-from-local-build"
sudo docker exec sharp sh -c "npm pkg set \"optionalDependencies.@img/sharp-linux-arm64=file:./npm/linux-arm64\""
sudo docker exec sharp sh -c "npm run clean"
sudo docker exec sharp sh -c "npm install --ignore-scripts"
sudo docker exec sharp sh -c "npm test"
linux-arm64-musl-node-18:
resource_class: arm.medium
machine:
image: ubuntu-2204:current
steps:
- checkout
- run: |
sudo docker run -dit --name sharp --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp node:18-alpine3.17
sudo docker exec sharp sh -c "apk add build-base git python3 font-noto --update-cache"
- run: sudo docker exec sharp sh -c "npm install --build-from-source"
- run: sudo docker exec sharp sh -c "npm test"
- run: |
sudo docker exec sharp sh -c "npm run package-from-local-build"
sudo docker exec sharp sh -c "npm pkg set \"optionalDependencies.@img/sharp-linuxmusl-arm64=file:./npm/linuxmusl-arm64\""
sudo docker exec sharp sh -c "npm run clean"
sudo docker exec sharp sh -c "npm install --ignore-scripts"
sudo docker exec sharp sh -c "npm test"
- run: "[[ -n $CIRCLE_TAG ]] && sudo docker exec --env prebuild_upload sharp sh -c \"cd src && ln -s ../package.json && npx prebuild --upload=$prebuild_upload\" || true"
linux-arm64-musl-node-20:
resource_class: arm.medium
machine:
image: ubuntu-2204:current
steps:
- checkout
- run: |
sudo docker run -dit --name sharp --workdir /mnt/sharp node:20-alpine3.18
sudo docker exec sharp sh -c "apk add build-base git python3 font-noto --update-cache"
sudo docker exec sharp sh -c "mkdir -p /mnt/sharp"
sudo docker cp . sharp:/mnt/sharp/.
- run: sudo docker exec sharp sh -c "npm install --build-from-source"
- run: sudo docker exec sharp sh -c "npm test"
- run: |
sudo docker exec sharp sh -c "npm run package-from-local-build"
sudo docker exec sharp sh -c "npm pkg set \"optionalDependencies.@img/sharp-linuxmusl-arm64=file:./npm/linuxmusl-arm64\""
sudo docker exec sharp sh -c "npm run clean"
sudo docker exec sharp sh -c "npm install --ignore-scripts"
sudo docker exec sharp sh -c "npm test"

View File

@ -1,5 +1,5 @@
freebsd_instance: freebsd_instance:
image_family: freebsd-14-0-snap image_family: freebsd-15-0-snap
task: task:
name: FreeBSD name: FreeBSD

View File

@ -43,7 +43,7 @@ and try again before opening an issue.
<!-- Please place an [x] in the relevant box to confirm. --> <!-- Please place an [x] in the relevant box to confirm. -->
- [ ] I am using npm >= 9.6.5 with `--include=optional` - [ ] I am using npm >= 10.1.0 with `--include=optional`
- [ ] I am using yarn >= 3.2.0 - [ ] I am using yarn >= 3.2.0
- [ ] I am using pnpm >= 7.1.0 with `--no-optional=false` - [ ] I am using pnpm >= 7.1.0 with `--no-optional=false`
- [ ] I am using Deno - [ ] I am using Deno

View File

@ -4,88 +4,142 @@ on:
- pull_request - pull_request
permissions: {} permissions: {}
jobs: jobs:
github-runner: build-native:
permissions: permissions:
contents: write contents: read
name: ${{ matrix.platform }} - Node.js ${{ matrix.nodejs_version_major }} ${{ matrix.prebuild && '- prebuild' }} name: "build-${{ matrix.platform }} [Node.js ${{ matrix.nodejs_version_major }}] ${{ matrix.package && '[package]' }}"
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
container: ${{ matrix.container }} container: ${{ matrix.container }}
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
include: include:
- os: ubuntu-22.04 - os: ubuntu-24.04
container: rockylinux:8 container: rockylinux:8
nodejs_arch: x64 nodejs_arch: x64
nodejs_version: "^18.17.0" nodejs_version: "^18.17.0"
nodejs_version_major: 18 nodejs_version_major: 18
platform: linux-x64 platform: linux-x64
prebuild: true package: true
- os: ubuntu-22.04 - os: ubuntu-24.04
container: rockylinux:8 container: rockylinux:8
nodejs_arch: x64 nodejs_arch: x64
nodejs_version: "^20.3.0" nodejs_version: "^20.3.0"
nodejs_version_major: 20 nodejs_version_major: 20
platform: linux-x64 platform: linux-x64
- os: ubuntu-22.04 - os: ubuntu-24.04
container: rockylinux:8
nodejs_arch: x64
nodejs_version: "^22.9.0"
nodejs_version_major: 22
platform: linux-x64
- os: ubuntu-24.04
container: node:18-alpine3.17 container: node:18-alpine3.17
nodejs_version_major: 18 nodejs_version_major: 18
platform: linuxmusl-x64 platform: linuxmusl-x64
prebuild: true package: true
- os: ubuntu-22.04 - os: ubuntu-24.04
container: node:20-alpine3.18 container: node:20-alpine3.18
nodejs_version_major: 20 nodejs_version_major: 20
platform: linuxmusl-x64 platform: linuxmusl-x64
- os: macos-11 - os: ubuntu-24.04
container: node:22-alpine3.20
nodejs_version_major: 22
platform: linuxmusl-x64
- os: ubuntu-24.04-arm
container: arm64v8/rockylinux:8
nodejs_arch: arm64
nodejs_version: "^18.17.0"
nodejs_version_major: 18
platform: linux-arm64
package: true
- os: ubuntu-24.04-arm
container: arm64v8/rockylinux:8
nodejs_arch: arm64
nodejs_version: "^20.3.0"
nodejs_version_major: 20
platform: linux-arm64
- os: macos-13
nodejs_arch: x64 nodejs_arch: x64
nodejs_version: "^18.17.0" nodejs_version: "^18.17.0"
nodejs_version_major: 18 nodejs_version_major: 18
platform: darwin-x64 platform: darwin-x64
prebuild: true package: true
- os: macos-11 - os: macos-13
nodejs_arch: x64 nodejs_arch: x64
nodejs_version: "^20.3.0" nodejs_version: "^20.3.0"
nodejs_version_major: 20 nodejs_version_major: 20
platform: darwin-x64 platform: darwin-x64
- os: macos-13
nodejs_arch: x64
nodejs_version: "^22.9.0"
nodejs_version_major: 22
platform: darwin-x64
- os: macos-14 - os: macos-14
nodejs_arch: arm64 nodejs_arch: arm64
nodejs_version: "^18.17.0" nodejs_version: "^18.17.0"
nodejs_version_major: 18 nodejs_version_major: 18
platform: darwin-arm64 platform: darwin-arm64
prebuild: true package: true
- os: macos-14 - os: macos-14
nodejs_arch: arm64 nodejs_arch: arm64
nodejs_version: "^20.3.0" nodejs_version: "^20.3.0"
nodejs_version_major: 20 nodejs_version_major: 20
platform: darwin-arm64 platform: darwin-arm64
- os: windows-2019 - os: macos-14
nodejs_arch: arm64
nodejs_version: "^22.9.0"
nodejs_version_major: 22
platform: darwin-arm64
- os: windows-2022
nodejs_arch: x86 nodejs_arch: x86
nodejs_version: "18.18.2" # pinned to avoid 18.19.0 and npm 10 nodejs_version: "18.18.2" # pinned to avoid 18.19.0 and npm 10
nodejs_version_major: 18 nodejs_version_major: 18
platform: win32-ia32 platform: win32-ia32
prebuild: true package: true
- os: windows-2019 - os: windows-2022
nodejs_arch: x86 nodejs_arch: x86
nodejs_version: "^20.3.0" nodejs_version: "^20.3.0"
nodejs_version_major: 20 nodejs_version_major: 20
platform: win32-ia32 platform: win32-ia32
- os: windows-2019 - os: windows-2022
nodejs_arch: x86
nodejs_version: "^22.9.0"
nodejs_version_major: 22
platform: win32-ia32
- os: windows-2022
nodejs_arch: x64 nodejs_arch: x64
nodejs_version: "^18.17.0" nodejs_version: "^18.17.0"
nodejs_version_major: 18 nodejs_version_major: 18
platform: win32-x64 platform: win32-x64
prebuild: true package: true
- os: windows-2019 - os: windows-2022
nodejs_arch: x64 nodejs_arch: x64
nodejs_version: "^20.3.0" nodejs_version: "^20.3.0"
nodejs_version_major: 20 nodejs_version_major: 20
platform: win32-x64 platform: win32-x64
- os: windows-2022
nodejs_arch: x64
nodejs_version: "^22.9.0"
nodejs_version_major: 22
platform: win32-x64
- os: windows-11-arm
nodejs_arch: arm64
nodejs_version: "^20.3.0"
nodejs_version_major: 20
platform: win32-arm64
package: true
- os: windows-11-arm
nodejs_arch: arm64
nodejs_version: "^22.9.0"
nodejs_version_major: 22
platform: win32-arm64
steps: steps:
- name: Dependencies (Rocky Linux glibc) - name: Dependencies (Rocky Linux glibc)
if: contains(matrix.container, 'rockylinux') if: contains(matrix.container, 'rockylinux')
run: | run: |
dnf install -y gcc-toolset-11-gcc-c++ make git python3 fontconfig google-noto-sans-fonts dnf install -y gcc-toolset-14-gcc-c++ make git python3.12 fontconfig google-noto-sans-fonts
echo "/opt/rh/gcc-toolset-11/root/usr/bin" >> $GITHUB_PATH echo "/opt/rh/gcc-toolset-14/root/usr/bin" >> $GITHUB_PATH
- name: Dependencies (Linux musl) - name: Dependencies (Linux musl)
if: contains(matrix.container, 'alpine') if: contains(matrix.container, 'alpine')
run: apk add build-base git python3 font-noto --update-cache run: apk add build-base git python3 font-noto --update-cache
@ -100,38 +154,77 @@ jobs:
with: with:
node-version: ${{ matrix.nodejs_version }} node-version: ${{ matrix.nodejs_version }}
architecture: ${{ matrix.nodejs_arch }} architecture: ${{ matrix.nodejs_arch }}
- name: Checkout - uses: actions/checkout@v4
uses: actions/checkout@v4
- name: Install - name: Install
run: npm install --build-from-source run: npm install --build-from-source
- name: Test - name: Test
run: npm test run: npm test
- name: Test packaging - name: Populate npm package
run: | if: matrix.package
npm run package-from-local-build run: npm run package-from-local-build
npm pkg set "optionalDependencies.@img/sharp-${{ matrix.platform }}=file:./npm/${{ matrix.platform }}" - uses: actions/upload-artifact@v4
npm run clean if: matrix.package
npm install --ignore-scripts with:
npm test name: ${{ matrix.platform }}
- name: Prebuild path: npm/${{ matrix.platform }}
if: matrix.prebuild && startsWith(github.ref, 'refs/tags/') retention-days: 1
env: if-no-files-found: error
prebuild_upload: ${{ secrets.GITHUB_TOKEN }} build-linuxmusl-arm-64:
run: |
node -e "require('fs').cpSync('package.json', 'src/package.json')"
cd src
npx prebuild
github-runner-qemu:
permissions: permissions:
contents: write contents: read
name: ${{ matrix.platform }} - Node.js ${{ matrix.nodejs_version_major }} - prebuild name: "build-linuxmusl-arm64 [Node.js ${{ matrix.nodejs_version_major }}] ${{ matrix.package && '[package]' }}"
runs-on: ubuntu-22.04 runs-on: ubuntu-24.04-arm
container:
image: ${{ matrix.container }}
volumes:
- /:/host
strategy:
fail-fast: false
matrix:
include:
- container: node:18-alpine3.17
nodejs_version_major: 18
package: true
- container: node:20-alpine3.18
nodejs_version_major: 20
steps:
- name: Allow Linux musl containers on ARM64 runners # https://github.com/actions/runner/issues/801#issuecomment-2394425757
shell: sh
run: |
apk add nodejs
sed -i "s:ID=alpine:ID=NotpineForGHA:" /etc/os-release
cd /host/home/runner/runners/*/externals/
rm -rf node20/*
mkdir node20/bin
ln -s /usr/bin/node node20/bin/node
- name: Dependencies
run: apk add build-base git python3 font-noto --update-cache
- uses: actions/checkout@v4
- name: Install
run: npm install --build-from-source
- name: Test
run: npm test
- name: Populate npm package
if: matrix.package
run: npm run package-from-local-build
- uses: actions/upload-artifact@v4
if: matrix.package
with:
name: linuxmusl-arm64
path: npm/linuxmusl-arm64
retention-days: 1
if-no-files-found: error
build-qemu:
permissions:
contents: read
name: "build-${{ matrix.platform }} [Node.js ${{ matrix.nodejs_version_major }}] [package]"
runs-on: ubuntu-24.04
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
include: include:
- platform: linux-arm - platform: linux-arm
distro: buster distro: bullseye
run_on_arch: armv6 run_on_arch: armv6
nodejs_arch: armv6l nodejs_arch: armv6l
nodejs_hostname: unofficial-builds.nodejs.org nodejs_hostname: unofficial-builds.nodejs.org
@ -144,14 +237,19 @@ jobs:
nodejs_hostname: nodejs.org nodejs_hostname: nodejs.org
nodejs_version: "18.17.0" nodejs_version: "18.17.0"
nodejs_version_major: 18 nodejs_version_major: 18
- platform: linux-ppc64
distro: bullseye
run_on_arch: ppc64le
nodejs_arch: ppc64le
nodejs_hostname: nodejs.org
nodejs_version: "18.17.0"
nodejs_version_major: 18
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: uraimo/run-on-arch-action@v2 - uses: uraimo/run-on-arch-action@v3
with: with:
arch: ${{ matrix.run_on_arch }} arch: ${{ matrix.run_on_arch }}
distro: ${{ matrix.distro }} distro: ${{ matrix.distro }}
env: |
prebuild_upload: "${{ startsWith(github.ref, 'refs/tags/') && secrets.GITHUB_TOKEN || '' }}"
run: | run: |
apt-get update apt-get update
apt-get install -y curl g++ git libatomic1 make python3 xz-utils apt-get install -y curl g++ git libatomic1 make python3 xz-utils
@ -161,20 +259,20 @@ jobs:
npm install --build-from-source npm install --build-from-source
npx mocha --no-config --spec=test/unit/io.js --timeout=30000 npx mocha --no-config --spec=test/unit/io.js --timeout=30000
npm run package-from-local-build npm run package-from-local-build
npm pkg set "optionalDependencies.@img/sharp-${{ matrix.platform }}=file:./npm/${{ matrix.platform }}" - uses: actions/upload-artifact@v4
npm run clean with:
npm install --ignore-scripts name: ${{ matrix.platform }}
npx mocha --no-config --spec=test/unit/io.js --timeout=30000 path: npm/${{ matrix.platform }}
[[ -n $prebuild_upload ]] && cd src && ln -s ../package.json && npx prebuild || true retention-days: 1
github-runner-emscripten: if-no-files-found: error
build-emscripten:
permissions: permissions:
contents: write contents: read
name: wasm32 - prebuild name: "build-wasm32 [package]"
runs-on: ubuntu-22.04 runs-on: ubuntu-24.04
container: "emscripten/emsdk:3.1.56" container: "emscripten/emsdk:4.0.10"
steps: steps:
- name: Checkout - uses: actions/checkout@v4
uses: actions/checkout@v4
- name: Dependencies - name: Dependencies
run: apt-get update && apt-get install -y pkg-config run: apt-get update && apt-get install -y pkg-config
- name: Dependencies (Node.js) - name: Dependencies (Node.js)
@ -192,17 +290,35 @@ jobs:
test "$EMSCRIPTEN_VERSION_LIBVIPS" = "$EMSCRIPTEN_VERSION_SHARP" test "$EMSCRIPTEN_VERSION_LIBVIPS" = "$EMSCRIPTEN_VERSION_SHARP"
- name: Test - name: Test
run: emmake npm test run: emmake npm test
- name: Test packaging - name: Populate npm package
run: | run: emmake npm run package-from-local-build
emmake npm run package-from-local-build - uses: actions/upload-artifact@v4
npm pkg set "optionalDependencies.@img/sharp-wasm32=file:./npm/wasm32" with:
npm run clean name: wasm32
rm -rf node_modules/@img/sharp-linux-x64 path: npm/wasm32
npm install --cpu=wasm32 retention-days: 1
npm test if-no-files-found: error
- name: Prebuild release:
if: startsWith(github.ref, 'refs/tags/') permissions:
env: contents: write
npm_config_nodedir: emscripten runs-on: ubuntu-24.04
prebuild_upload: ${{ secrets.GITHUB_TOKEN }} needs:
run: cd src && ln -s ../package.json && emmake npx prebuild --platform=emscripten --arch=wasm32 --strip=0 - build-native
- build-linuxmusl-arm-64
- build-qemu
- build-emscripten
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
path: npm
- name: Create npm workspace tarball
run: tar -vcaf npm-workspace.tar.xz --directory npm --exclude=from-local-build.js .
- name: Create GitHub release for tag
if: startsWith(github.ref, 'refs/tags/v')
uses: ncipollo/release-action@v1
with:
artifacts: npm-workspace.tar.xz
artifactContentType: application/x-xz
prerelease: ${{ contains(github.ref, '-rc') }}
makeLatest: ${{ !contains(github.ref, '-rc') }}

View File

@ -16,69 +16,81 @@ jobs:
matrix: matrix:
include: include:
- name: linux-x64-node-npm - name: linux-x64-node-npm
runs-on: ubuntu-22.04 runs-on: ubuntu-24.04
runtime: node runtime: node
package-manager: npm package-manager: npm
- name: linux-x64-node-pnpm - name: linux-x64-node-pnpm
runs-on: ubuntu-22.04 runs-on: ubuntu-24.04
runtime: node runtime: node
package-manager: pnpm package-manager: pnpm
- name: linux-x64-node-yarn - name: linux-x64-node-yarn
runs-on: ubuntu-22.04 runs-on: ubuntu-24.04
runtime: node runtime: node
package-manager: yarn package-manager: yarn
- name: linux-x64-node-yarn-pnp - name: linux-x64-node-yarn-pnp
runs-on: ubuntu-22.04 runs-on: ubuntu-24.04
runtime: node runtime: node
package-manager: yarn-pnp package-manager: yarn-pnp
- name: linux-x64-node-yarn-v1
runs-on: ubuntu-24.04
runtime: node
package-manager: yarn-v1
- name: linux-x64-deno - name: linux-x64-deno
runs-on: ubuntu-22.04 runs-on: ubuntu-24.04
runtime: deno runtime: deno
- name: linux-x64-bun - name: linux-x64-bun
runs-on: ubuntu-22.04 runs-on: ubuntu-24.04
runtime: bun runtime: bun
- name: darwin-x64-node-npm - name: darwin-x64-node-npm
runs-on: macos-11 runs-on: macos-13
runtime: node runtime: node
package-manager: npm package-manager: npm
- name: darwin-x64-node-pnpm - name: darwin-x64-node-pnpm
runs-on: macos-11 runs-on: macos-13
runtime: node runtime: node
package-manager: pnpm package-manager: pnpm
- name: darwin-x64-node-yarn - name: darwin-x64-node-yarn
runs-on: macos-11 runs-on: macos-13
runtime: node runtime: node
package-manager: yarn package-manager: yarn
- name: darwin-x64-node-yarn-pnp - name: darwin-x64-node-yarn-pnp
runs-on: macos-11 runs-on: macos-13
runtime: node runtime: node
package-manager: yarn-pnp package-manager: yarn-pnp
- name: darwin-x64-node-yarn-v1
runs-on: macos-13
runtime: node
package-manager: yarn-v1
- name: darwin-x64-deno - name: darwin-x64-deno
runs-on: macos-11 runs-on: macos-13
runtime: deno runtime: deno
- name: darwin-x64-bun - name: darwin-x64-bun
runs-on: macos-11 runs-on: macos-13
runtime: bun runtime: bun
- name: win32-x64-node-npm - name: win32-x64-node-npm
runs-on: windows-2019 runs-on: windows-2022
runtime: node runtime: node
package-manager: npm package-manager: npm
- name: win32-x64-node-pnpm - name: win32-x64-node-pnpm
runs-on: windows-2019 runs-on: windows-2022
runtime: node runtime: node
package-manager: pnpm package-manager: pnpm
- name: win32-x64-node-yarn - name: win32-x64-node-yarn
runs-on: windows-2019 runs-on: windows-2022
runtime: node runtime: node
package-manager: yarn package-manager: yarn
- name: win32-x64-node-yarn-pnp - name: win32-x64-node-yarn-pnp
runs-on: windows-2019 runs-on: windows-2022
runtime: node runtime: node
package-manager: yarn-pnp package-manager: yarn-pnp
- name: win32-x64-node-yarn-v1
runs-on: windows-2022
runtime: node
package-manager: yarn-v1
- name: win32-x64-deno - name: win32-x64-deno
runs-on: windows-2019 runs-on: windows-2022
runtime: deno runtime: deno
steps: steps:
@ -89,7 +101,7 @@ jobs:
node-version: 20 node-version: 20
- name: Install pnpm - name: Install pnpm
if: ${{ matrix.package-manager == 'pnpm' }} if: ${{ matrix.package-manager == 'pnpm' }}
uses: pnpm/action-setup@v2 uses: pnpm/action-setup@v4
with: with:
version: 8 version: 8
- name: Install Deno - name: Install Deno
@ -99,13 +111,13 @@ jobs:
deno-version: v1.x deno-version: v1.x
- name: Install Bun - name: Install Bun
if: ${{ matrix.runtime == 'bun' }} if: ${{ matrix.runtime == 'bun' }}
uses: oven-sh/setup-bun@v1 uses: oven-sh/setup-bun@v2
with: with:
bun-version: latest bun-version: latest
- name: Version - name: Version
id: version id: version
uses: actions/github-script@v6 uses: actions/github-script@v7
with: with:
script: | script: |
core.setOutput('semver', context.ref.replace('refs/tags/v','')) core.setOutput('semver', context.ref.replace('refs/tags/v',''))
@ -163,6 +175,14 @@ jobs:
yarn install yarn install
yarn node release.mjs yarn node release.mjs
- name: Run with Node.js + yarn v1
if: ${{ matrix.package-manager == 'yarn-v1' }}
run: |
corepack enable
yarn set version classic
yarn install
node release.mjs
- name: Run with Deno - name: Run with Deno
if: ${{ matrix.runtime == 'deno' }} if: ${{ matrix.runtime == 'deno' }}
run: deno run --allow-read --allow-ffi release.mjs run: deno run --allow-read --allow-ffi release.mjs

2
.gitignore vendored
View File

@ -14,3 +14,5 @@ test/leak/libvips.supp
package-lock.json package-lock.json
.idea .idea
.firebase .firebase
.astro
docs/dist

View File

@ -1,6 +0,0 @@
{
"runtime": "napi",
"include-regex": "(sharp-.+\\.node|libvips-.+\\.dll)",
"prerelease": true,
"strip": true
}

View File

@ -1,6 +1,6 @@
# sharp # sharp
<img src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right"> <img src="https://sharp.pixelplumbing.com/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right">
The typical use case for this high speed Node-API module The typical use case for this high speed Node-API module
is to convert large images in common formats to is to convert large images in common formats to

79
docs/astro.config.mjs Normal file
View File

@ -0,0 +1,79 @@
// @ts-check
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
export default defineConfig({
site: 'https://sharp.pixelplumbing.com',
integrations: [
starlight({
title: 'sharp',
description:
'High performance Node.js image processing. The fastest module to resize JPEG, PNG, WebP and TIFF images.',
logo: {
src: './src/assets/sharp-logo.svg',
alt: '#'
},
customCss: ['./src/styles/custom.css'],
head: [{
tag: 'meta',
attrs: {
'http-equiv': 'Content-Security-Policy',
content: "default-src 'self'; connect-src 'self'; object-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://static.cloudflareinsights.com/beacon.min.js/;"
}
}, {
tag: 'link',
attrs: {
rel: 'author',
href: '/humans.txt',
type: 'text/plain'
}
}, {
tag: 'script',
attrs: {
type: 'application/ld+json'
},
content: JSON.stringify({
'@context': 'https://schema.org',
'@type': 'SoftwareSourceCode',
name: 'sharp',
description: 'High performance Node.js image processing',
url: 'https://sharp.pixelplumbing.com',
codeRepository: 'https://github.com/lovell/sharp',
programmingLanguage: ['JavaScript', 'C++'],
runtimePlatform: 'Node.js',
copyrightHolder: {
'@context': 'https://schema.org',
'@type': 'Person',
name: 'Lovell Fuller'
},
copyrightYear: 2013,
license: 'https://www.apache.org/licenses/LICENSE-2.0'
})
}],
sidebar: [
{ label: 'Home', link: '/' },
{ label: 'Installation', slug: 'install' },
{
label: 'API',
items: [
{ label: 'Constructor', slug: 'api-constructor' },
{ label: 'Input metadata', slug: 'api-input' },
{ label: 'Output options', slug: 'api-output' },
{ label: 'Resizing images', slug: 'api-resize' },
{ label: 'Compositing images', slug: 'api-composite' },
{ label: 'Image operations', slug: 'api-operation' },
{ label: 'Colour manipulation', slug: 'api-colour' },
{ label: 'Channel manipulation', slug: 'api-channel' },
{ label: 'Global properties', slug: 'api-utility' }
]
},
{ label: 'Performance', slug: 'performance' },
{ label: 'Changelog', slug: 'changelog' }
],
social: [
{ icon: 'openCollective', label: 'Open Collective', href: 'https://opencollective.com/libvips' },
{ icon: 'github', label: 'GitHub', href: 'https://github.com/lovell/sharp' }
]
})
]
});

View File

@ -1,38 +0,0 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
const fs = require('fs').promises;
const path = require('path');
const jsdoc2md = require('jsdoc-to-markdown');
[
'constructor',
'input',
'resize',
'composite',
'operation',
'colour',
'channel',
'output',
'utility'
].forEach(async (m) => {
const input = path.join('lib', `${m}.js`);
const output = path.join('docs', `api-${m}.md`);
const ast = await jsdoc2md.getTemplateData({ files: input });
const markdown = await jsdoc2md.render({
data: ast,
'global-index-format': 'none',
'module-index-format': 'none'
});
const cleanMarkdown = markdown
.replace(/(## )([A-Za-z0-9]+)([^\n]*)/g, '$1$2\n> $2$3\n') // simplify headings to match those of documentationjs, ensures existing URLs work
.replace(/<a name="[A-Za-z0-9+]+"><\/a>/g, '') // remove anchors, let docute add these (at markdown to HTML render time)
.replace(/\*\*Kind\*\*: global[^\n]+/g, '') // remove all "global" Kind labels (requires JSDoc refactoring)
.trim();
await fs.writeFile(output, cleanMarkdown);
});

42
docs/build.mjs Normal file
View File

@ -0,0 +1,42 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import jsdoc2md from 'jsdoc-to-markdown';
const pages = {
constructor: 'Constructor',
input: 'Input metadata',
resize: 'Resizing images',
composite: 'Compositing images',
operation: 'Image operations',
colour: 'Colour manipulation',
channel: 'Channel manipulation',
output: 'Output options',
utility: 'Global properties'
};
Object.keys(pages).forEach(async (m) => {
const input = path.join('lib', `${m}.js`);
const output = path.join('docs', 'src', 'content', 'docs', `api-${m}.md`);
const ast = await jsdoc2md.getTemplateData({ files: input });
const markdown = await jsdoc2md.render({
data: ast,
'global-index-format': 'none',
'module-index-format': 'none'
});
const cleanMarkdown =
`---\n# This file was auto-generated from JSDoc in lib/${m}.js\ntitle: ${pages[m]}\n---\n\n` +
markdown
.replace(/(## )([A-Za-z0-9]+)([^\n]*)/g, '$1$2\n> $2$3\n') // simplify headings
.replace(/<a name="[A-Za-z0-9+]+"><\/a>/g, '') // remove anchors
.replace(/\*\*Kind\*\*: global[^\n]+/g, '') // remove all "global" Kind labels (requires JSDoc refactoring)
.trim();
await fs.writeFile(output, cleanMarkdown);
});

1
docs/docute.min.js vendored

File diff suppressed because one or more lines are too long

View File

@ -1,14 +1,7 @@
{ {
"hosting": { "hosting": {
"site": "pixelplumbing-sharp", "site": "pixelplumbing-sharp",
"public": ".", "public": "dist",
"ignore": [
".*",
"build.js",
"firebase.json",
"image/**",
"search-index/**"
],
"headers": [ "headers": [
{ {
"source": "**", "source": "**",
@ -18,99 +11,6 @@
{ "key": "X-Frame-Options", "value": "SAMEORIGIN" } { "key": "X-Frame-Options", "value": "SAMEORIGIN" }
] ]
} }
],
"redirects": [
{
"source": "**/install/**",
"destination": "/install",
"type": 301
},
{
"source": "/page/install",
"destination": "/install",
"type": 301
},
{
"source": "**/api-constructor/**",
"destination": "/api-constructor",
"type": 301
},
{
"source": "**/api-input/**",
"destination": "/api-input",
"type": 301
},
{
"source": "**/api-output/**",
"destination": "/api-output",
"type": 301
},
{
"source": "**/api-resize/**",
"destination": "/api-resize",
"type": 301
},
{
"source": "**/api-compsite/**",
"destination": "/api-compsite",
"type": 301
},
{
"source": "**/api-operation/**",
"destination": "/api-operation",
"type": 301
},
{
"source": "**/api-colour/**",
"destination": "/api-colour",
"type": 301
},
{
"source": "**/api-channel/**",
"destination": "/api-channel",
"type": 301
},
{
"source": "**/api-utility/**",
"destination": "/api-utility",
"type": 301
},
{
"source": "/page/api",
"destination": "/api-constructor",
"type": 301
},
{
"source": "**/performance/**",
"destination": "/performance",
"type": 301
},
{
"source": "/page/performance",
"destination": "/performance",
"type": 301
},
{
"source": "**/changelog/**",
"destination": "/changelog",
"type": 301
},
{
"source": "/page/changelog",
"destination": "/changelog",
"type": 301
},
{
"source": "/en/**",
"destination": "/",
"type": 301
}
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
] ]
} }
} }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 652 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

File diff suppressed because one or more lines are too long

17
docs/package.json Normal file
View File

@ -0,0 +1,17 @@
{
"name": "sharp-docs",
"type": "module",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "astro dev",
"start": "astro dev",
"build": "astro build",
"preview": "astro preview",
"astro": "astro"
},
"dependencies": {
"@astrojs/starlight": "^0.34.3",
"astro": "^5.7.13"
}
}

View File

@ -1,111 +0,0 @@
# Performance
A test to benchmark the performance of this module relative to alternatives.
Greater libvips performance can be expected with caching enabled (default)
and using 8+ core machines, especially those with larger L1/L2 CPU caches.
The I/O limits of the relevant (de)compression library will generally determine maximum throughput.
## Contenders
* [jimp](https://www.npmjs.com/package/jimp) v0.22.10 - Image processing in pure JavaScript.
* [imagemagick](https://www.npmjs.com/package/imagemagick) v0.1.3 - Supports filesystem only and "*has been unmaintained for a long time*".
* [gm](https://www.npmjs.com/package/gm) v1.25.0 - Fully featured wrapper around GraphicsMagick's `gm` command line utility.
* [@squoosh/lib](https://www.npmjs.com/package/@squoosh/lib) v0.5.3 - Image libraries transpiled to WebAssembly, includes GPLv3 code, but "*Project no longer maintained*".
* [@squoosh/cli](https://www.npmjs.com/package/@squoosh/cli) v0.7.3 - Command line wrapper around `@squoosh/lib`, avoids GPLv3 by spawning process, but "*Project no longer maintained*".
* sharp v0.33.0 / libvips v8.15.0 - Caching within libvips disabled to ensure a fair comparison.
## Environment
### AMD64
* AWS EC2 us-east-2 [c7a.xlarge](https://aws.amazon.com/ec2/instance-types/c7a/) (4x AMD EPYC 9R14)
* Ubuntu 23.10 [13f233a16be2](https://hub.docker.com/layers/library/ubuntu/23.10/images/sha256-13f233a16be210b57907b98b0d927ceff7571df390701e14fe1f3901b2c4a4d7)
* Node.js 20.10.0
### ARM64
* AWS EC2 us-east-2 [c7g.xlarge](https://aws.amazon.com/ec2/instance-types/c7g/) (4x ARM Graviton3)
* Ubuntu 23.10 [7708743264cb](https://hub.docker.com/layers/library/ubuntu/23.10/images/sha256-7708743264cbb7f6cf7fc13e915faece45a6cdda455748bc55e58e8de3d27b63)
* Node.js 20.10.0
## Task: JPEG
Decompress a 2725x2225 JPEG image,
resize to 720x588 using Lanczos 3 resampling (where available),
then compress to JPEG at a "quality" setting of 80.
Note: jimp does not support Lanczos 3, bicubic resampling used instead.
#### Results: JPEG (AMD64)
| Module | Input | Output | Ops/sec | Speed-up |
| :----------------- | :----- | :----- | ------: | -------: |
| jimp | buffer | buffer | 0.84 | 1.0 |
| squoosh-cli | file | file | 1.54 | 1.8 |
| squoosh-lib | buffer | buffer | 2.24 | 2.7 |
| imagemagick | file | file | 11.75 | 14.0 |
| gm | buffer | buffer | 12.66 | 15.1 |
| gm | file | file | 12.72 | 15.1 |
| sharp | stream | stream | 48.31 | 57.5 |
| sharp | file | file | 51.42 | 61.2 |
| sharp | buffer | buffer | 52.41 | 62.4 |
#### Results: JPEG (ARM64)
| Module | Input | Output | Ops/sec | Speed-up |
| :----------------- | :----- | :----- | ------: | -------: |
| jimp | buffer | buffer | 0.88 | 1.0 |
| squoosh-cli | file | file | 1.18 | 1.3 |
| squoosh-lib | buffer | buffer | 1.99 | 2.3 |
| gm | buffer | buffer | 6.06 | 6.9 |
| gm | file | file | 10.81 | 12.3 |
| imagemagick | file | file | 10.95 | 12.4 |
| sharp | stream | stream | 33.15 | 37.7 |
| sharp | file | file | 34.99 | 39.8 |
| sharp | buffer | buffer | 36.05 | 41.0 |
## Task: PNG
Decompress a 2048x1536 RGBA PNG image,
premultiply the alpha channel,
resize to 720x540 using Lanczos 3 resampling (where available),
unpremultiply then compress as PNG with a "default" zlib compression level of 6
and without adaptive filtering.
Note: jimp does not support premultiply/unpremultiply.
### Results: PNG (AMD64)
| Module | Input | Output | Ops/sec | Speed-up |
| :----------------- | :----- | :----- | ------: | -------: |
| squoosh-cli | file | file | 0.34 | 1.0 |
| squoosh-lib | buffer | buffer | 0.51 | 1.5 |
| jimp | buffer | buffer | 3.59 | 10.6 |
| gm | file | file | 8.54 | 25.1 |
| imagemagick | file | file | 9.23 | 27.1 |
| sharp | file | file | 25.43 | 74.8 |
| sharp | buffer | buffer | 25.70 | 75.6 |
### Results: PNG (ARM64)
| Module | Input | Output | Ops/sec | Speed-up |
| :----------------- | :----- | :----- | ------: | -------: |
| squoosh-cli | file | file | 0.33 | 1.0 |
| squoosh-lib | buffer | buffer | 0.46 | 1.4 |
| jimp | buffer | buffer | 3.51 | 10.6 |
| gm | file | file | 7.47 | 22.6 |
| imagemagick | file | file | 8.06 | 24.4 |
| sharp | file | file | 17.31 | 52.5 |
| sharp | buffer | buffer | 17.66 | 53.5 |
## Running the benchmark test
Requires Docker.
```sh
git clone https://github.com/lovell/sharp.git
cd sharp/test/bench
./run-with-docker.sh
```

View File

Before

Width:  |  Height:  |  Size: 4.0 KiB

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

Before

Width:  |  Height:  |  Size: 508 B

After

Width:  |  Height:  |  Size: 508 B

View File

@ -28,7 +28,7 @@ Name: Brandon Aaron
GitHub: https://github.com/brandonaaron GitHub: https://github.com/brandonaaron
Name: Andreas Lind Name: Andreas Lind
GitHub: https://github.com/papandreouGitHub: GitHub: https://github.com/papandreou
Name: Maurus Cuelenaere Name: Maurus Cuelenaere
GitHub: https://github.com/mcuelenaere GitHub: https://github.com/mcuelenaere
@ -293,3 +293,33 @@ GitHub: https://github.com/mertalev
Name: Adriaan Meuris Name: Adriaan Meuris
GitHub: https://github.com/adriaanmeuris GitHub: https://github.com/adriaanmeuris
Name: Richard Hillmann
GitHub: https://github.com/project0
Name: Pongsatorn Manusopit
GitHub: https://github.com/ton11797
Name: Nathan Keynes
GitHub: https://github.com/nkeynes
Name: Sumit D
GitHub: https://github.com/sumitd2
Name: Caleb Meredith
GitHub: https://github.com/calebmer
Name: Don Denton
GitHub: https://github.com/happycollision
Name: Florent Zabera
GitHub: https://github.com/florentzabera
Name: Quentin Pinçon
GitHub: https://github.com/qpincon
Name: Hans Chen
GitHub: https://github.com/hans00
Name: Thibaut Patel
GitHub: https://github.com/tpatel

4
docs/public/robots.txt Normal file
View File

@ -0,0 +1,4 @@
User-agent: *
Disallow:
Sitemap: https://sharp.pixelplumbing.com/sitemap-index.xml

View File

Before

Width:  |  Height:  |  Size: 929 B

After

Width:  |  Height:  |  Size: 929 B

View File

@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="86 86 550 550">
<!-- Creative Commons CC0 1.0 Universal Public Domain Dedication -->
<path fill="none" stroke="#9c0" stroke-width="80" d="M258.411 285.777l200.176-26.8M244.113 466.413L451.44 438.66M451.441 438.66V238.484M451.441 88.363v171.572l178.725-23.917M270.323 255.602V477.22M272.71 634.17V462.591L93.984 486.515"/>
<path fill="none" stroke="#090" stroke-width="80" d="M451.441 610.246V438.66l178.725-23.91M269.688 112.59v171.58L90.964 308.093"/>
</svg>

After

Width:  |  Height:  |  Size: 508 B

View File

@ -1,2 +0,0 @@
User-agent: *
Disallow:

File diff suppressed because one or more lines are too long

View File

@ -1,64 +0,0 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
const fs = require('fs');
const path = require('path');
const { extractDescription, extractKeywords, extractParameters } = require('./extract');
const searchIndex = [];
// Install
const contents = fs.readFileSync(path.join(__dirname, '..', 'install.md'), 'utf8');
const matches = contents.matchAll(
/## (?<title>[A-Za-z0-9 ]+)\n\n(?<body>[^#]+)/gs
);
for (const match of matches) {
const { title, body } = match.groups;
const description = extractDescription(body);
searchIndex.push({
t: title,
d: description,
k: extractKeywords(`${title} ${description}`),
l: `/install#${title.toLowerCase().replace(/ /g, '-')}`
});
}
// API
[
'constructor',
'input',
'output',
'resize',
'composite',
'operation',
'channel',
'colour',
'utility'
].forEach((section) => {
const contents = fs.readFileSync(path.join(__dirname, '..', `api-${section}.md`), 'utf8');
const matches = contents.matchAll(
/## (?<title>[A-Za-z]+)\n[^\n]+\n(?<firstparagraph>.+?)\n\n.+?(?<parameters>\| Param .+?\n\n)?\*\*Example/gs
);
for (const match of matches) {
const { title, firstparagraph, parameters } = match.groups;
const description = firstparagraph.startsWith('###')
? 'Constructor'
: extractDescription(firstparagraph);
const parameterNames = parameters ? extractParameters(parameters) : '';
searchIndex.push({
t: title,
d: description,
k: extractKeywords(`${title} ${description} ${parameterNames}`),
l: `/api-${section}#${title.toLowerCase()}`
});
}
});
fs.writeFileSync(
path.join(__dirname, '..', 'search-index.json'),
JSON.stringify(searchIndex)
);

View File

@ -1,34 +0,0 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
const stopWords = require('./stop-words');
const extractDescription = (str) =>
str
.replace(/### Examples.*/sg, '')
.replace(/\(http[^)]+/g, '')
.replace(/\s+/g, ' ')
.replace(/[^A-Za-z0-9_/\-,. ]/g, '')
.replace(/\s+/g, ' ')
.substring(0, 200)
.trim();
const extractParameters = (str) =>
[...str.matchAll(/options\.(?<name>[^.`\] ]+)/gs)]
.map((match) => match.groups.name)
.map((name) => name.replace(/([A-Z])/g, ' $1').toLowerCase())
.join(' ');
const extractKeywords = (str) =>
[
...new Set(
str
.split(/[ -/]/)
.map((word) => word.toLowerCase().replace(/[^a-z]/g, ''))
.filter((word) => word.length > 2 && word.length < 15 && !stopWords.includes(word))
)
].join(' ');
module.exports = { extractDescription, extractKeywords, extractParameters };

View File

@ -1,140 +0,0 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
module.exports = [
'about',
'after',
'all',
'allows',
'already',
'also',
'alternative',
'always',
'and',
'any',
'are',
'available',
'based',
'been',
'before',
'best',
'both',
'call',
'callback',
'can',
'containing',
'contains',
'created',
'current',
'date',
'default',
'deprecated',
'does',
'each',
'either',
'ensure',
'entirely',
'etc',
'every',
'except',
'following',
'for',
'from',
'get',
'gets',
'given',
'has',
'have',
'helps',
'how',
'image',
'implies',
'include',
'including',
'involve',
'its',
'last',
'least',
'lots',
'make',
'may',
'meaning',
'more',
'most',
'much',
'must',
'non',
'not',
'now',
'occur',
'occurs',
'one',
'options',
'other',
'out',
'over',
'part',
'perform',
'performs',
'please',
'pre',
'previously',
'produce',
'proper',
'provide',
'provided',
'ready',
'requires',
'requiresharp',
'returned',
'run',
'same',
'see',
'set',
'sets',
'sharp',
'should',
'since',
'site',
'some',
'specified',
'spelling',
'such',
'support',
'supported',
'sure',
'take',
'task',
'than',
'that',
'the',
'their',
'then',
'there',
'therefore',
'these',
'this',
'under',
'unless',
'unmaintained',
'unsuitable',
'unsupported',
'until',
'use',
'used',
'using',
'value',
'values',
'via',
'were',
'when',
'which',
'while',
'will',
'with',
'without',
'you',
'your'
];

View File

@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="86 86 550 550">
<!-- Creative Commons CC0 1.0 Universal Public Domain Dedication -->
<path fill="none" stroke="#9c0" stroke-width="80" d="M258.411 285.777l200.176-26.8M244.113 466.413L451.44 438.66M451.441 438.66V238.484M451.441 88.363v171.572l178.725-23.917M270.323 255.602V477.22M272.71 634.17V462.591L93.984 486.515"/>
<path fill="none" stroke="#090" stroke-width="80" d="M451.441 610.246V438.66l178.725-23.91M269.688 112.59v171.58L90.964 308.093"/>
</svg>

After

Width:  |  Height:  |  Size: 508 B

View File

@ -0,0 +1,7 @@
import { defineCollection } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';
export const collections = {
docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};

View File

@ -1,7 +1,12 @@
---
# This file was auto-generated from JSDoc in lib/channel.js
title: Channel manipulation
---
## removeAlpha ## removeAlpha
> removeAlpha() ⇒ <code>Sharp</code> > removeAlpha() ⇒ <code>Sharp</code>
Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel. Remove alpha channels, if any. This is a no-op if the image does not have an alpha channel.
See also [flatten](/api-operation#flatten). See also [flatten](/api-operation#flatten).

View File

@ -1,3 +1,8 @@
---
# This file was auto-generated from JSDoc in lib/colour.js
title: Colour manipulation
---
## tint ## tint
> tint(tint) ⇒ <code>Sharp</code> > tint(tint) ⇒ <code>Sharp</code>
@ -27,9 +32,9 @@ const output = await sharp(input)
Convert to 8-bit greyscale; 256 shades of grey. Convert to 8-bit greyscale; 256 shades of grey.
This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results. This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results.
By default the output image will be web-friendly sRGB and contain three (identical) color channels. By default the output image will be web-friendly sRGB and contain three (identical) colour channels.
This may be overridden by other sharp operations such as `toColourspace('b-w')`, This may be overridden by other sharp operations such as `toColourspace('b-w')`,
which will produce an output image containing one color channel. which will produce an output image containing one colour channel.
An alpha channel may be present, and will be unchanged by the operation. An alpha channel may be present, and will be unchanged by the operation.

View File

@ -1,3 +1,8 @@
---
# This file was auto-generated from JSDoc in lib/composite.js
title: Compositing images
---
## composite ## composite
> composite(images) ⇒ <code>Sharp</code> > composite(images) ⇒ <code>Sharp</code>
@ -6,8 +11,8 @@ Composite image(s) over the processed (resized, extracted etc.) image.
The images to composite must be the same size or smaller than the processed image. The images to composite must be the same size or smaller than the processed image.
If both `top` and `left` options are provided, they take precedence over `gravity`. If both `top` and `left` options are provided, they take precedence over `gravity`.
Any resize, rotate or extract operations in the same processing pipeline Other operations in the same processing pipeline (e.g. resize, rotate, flip,
will always be applied to the input image before composition. flop, extract) will always be applied to the input image before composition.
The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`, The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`,
`dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`, `dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`,
@ -46,6 +51,7 @@ and https://www.cairographics.org/operators/
| [images[].input.text.dpi] | <code>number</code> | <code>72</code> | the resolution (size) at which to render the text. Does not take effect if `height` is specified. | | [images[].input.text.dpi] | <code>number</code> | <code>72</code> | the resolution (size) at which to render the text. Does not take effect if `height` is specified. |
| [images[].input.text.rgba] | <code>boolean</code> | <code>false</code> | set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like `<span foreground="red">Red!</span>`. | | [images[].input.text.rgba] | <code>boolean</code> | <code>false</code> | set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like `<span foreground="red">Red!</span>`. |
| [images[].input.text.spacing] | <code>number</code> | <code>0</code> | text line height in points. Will use the font line height if none is specified. | | [images[].input.text.spacing] | <code>number</code> | <code>0</code> | text line height in points. Will use the font line height if none is specified. |
| [images[].autoOrient] | <code>Boolean</code> | <code>false</code> | set to true to use EXIF orientation data, if present, to orient the image. |
| [images[].blend] | <code>String</code> | <code>&#x27;over&#x27;</code> | how to blend this image with the image below. | | [images[].blend] | <code>String</code> | <code>&#x27;over&#x27;</code> | how to blend this image with the image below. |
| [images[].gravity] | <code>String</code> | <code>&#x27;centre&#x27;</code> | gravity at which to place the overlay. | | [images[].gravity] | <code>String</code> | <code>&#x27;centre&#x27;</code> | gravity at which to place the overlay. |
| [images[].top] | <code>Number</code> | | the pixel offset from the top edge. | | [images[].top] | <code>Number</code> | | the pixel offset from the top edge. |

View File

@ -1,3 +1,8 @@
---
# This file was auto-generated from JSDoc in lib/constructor.js
title: Constructor
---
## Sharp ## Sharp
> Sharp > Sharp
@ -28,33 +33,34 @@ where the overall height is the `pageHeight` multiplied by the number of `pages`
| Param | Type | Default | Description | | Param | Type | Default | Description |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| [input] | <code>Buffer</code> \| <code>ArrayBuffer</code> \| <code>Uint8Array</code> \| <code>Uint8ClampedArray</code> \| <code>Int8Array</code> \| <code>Uint16Array</code> \| <code>Int16Array</code> \| <code>Uint32Array</code> \| <code>Int32Array</code> \| <code>Float32Array</code> \| <code>Float64Array</code> \| <code>string</code> | | if present, can be a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or a TypedArray containing raw pixel image data, or a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. | | [input] | <code>Buffer</code> \| <code>ArrayBuffer</code> \| <code>Uint8Array</code> \| <code>Uint8ClampedArray</code> \| <code>Int8Array</code> \| <code>Uint16Array</code> \| <code>Int16Array</code> \| <code>Uint32Array</code> \| <code>Int32Array</code> \| <code>Float32Array</code> \| <code>Float64Array</code> \| <code>string</code> \| <code>Array</code> | | if present, can be a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or a TypedArray containing raw pixel image data, or a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. An array of inputs can be provided, and these will be joined together. JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. |
| [options] | <code>Object</code> | | if present, is an Object with optional attributes. | | [options] | <code>Object</code> | | if present, is an Object with optional attributes. |
| [options.failOn] | <code>string</code> | <code>&quot;&#x27;warning&#x27;&quot;</code> | When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort. | | [options.failOn] | <code>string</code> | <code>&quot;&#x27;warning&#x27;&quot;</code> | When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort. |
| [options.limitInputPixels] | <code>number</code> \| <code>boolean</code> | <code>268402689</code> | 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). | | [options.limitInputPixels] | <code>number</code> \| <code>boolean</code> | <code>268402689</code> | 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). |
| [options.unlimited] | <code>boolean</code> | <code>false</code> | Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). | | [options.unlimited] | <code>boolean</code> | <code>false</code> | Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). |
| [options.autoOrient] | <code>boolean</code> | <code>false</code> | Set this to `true` to rotate/flip the image to match EXIF `Orientation`, if any. |
| [options.sequentialRead] | <code>boolean</code> | <code>true</code> | Set this to `false` to use random access rather than sequential read. Some operations will do this automatically. | | [options.sequentialRead] | <code>boolean</code> | <code>true</code> | Set this to `false` to use random access rather than sequential read. Some operations will do this automatically. |
| [options.density] | <code>number</code> | <code>72</code> | number representing the DPI for vector images in the range 1 to 100000. | | [options.density] | <code>number</code> | <code>72</code> | number representing the DPI for vector images in the range 1 to 100000. |
| [options.ignoreIcc] | <code>number</code> | <code>false</code> | should the embedded ICC profile, if any, be ignored. | | [options.ignoreIcc] | <code>number</code> | <code>false</code> | should the embedded ICC profile, if any, be ignored. |
| [options.pages] | <code>number</code> | <code>1</code> | Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages. | | [options.pages] | <code>number</code> | <code>1</code> | Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages. |
| [options.page] | <code>number</code> | <code>0</code> | Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based. | | [options.page] | <code>number</code> | <code>0</code> | Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based. |
| [options.subifd] | <code>number</code> | <code>-1</code> | subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. |
| [options.level] | <code>number</code> | <code>0</code> | level to extract from a multi-level input (OpenSlide), zero based. |
| [options.animated] | <code>boolean</code> | <code>false</code> | Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`. | | [options.animated] | <code>boolean</code> | <code>false</code> | Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`. |
| [options.raw] | <code>Object</code> | | describes raw pixel input image data. See `raw()` for pixel ordering. | | [options.raw] | <code>Object</code> | | describes raw pixel input image data. See `raw()` for pixel ordering. |
| [options.raw.width] | <code>number</code> | | integral number of pixels wide. | | [options.raw.width] | <code>number</code> | | integral number of pixels wide. |
| [options.raw.height] | <code>number</code> | | integral number of pixels high. | | [options.raw.height] | <code>number</code> | | integral number of pixels high. |
| [options.raw.channels] | <code>number</code> | | integral number of channels, between 1 and 4. | | [options.raw.channels] | <code>number</code> | | integral number of channels, between 1 and 4. |
| [options.raw.premultiplied] | <code>boolean</code> | | specifies that the raw input has already been premultiplied, set to `true` to avoid sharp premultiplying the image. (optional, default `false`) | | [options.raw.premultiplied] | <code>boolean</code> | | specifies that the raw input has already been premultiplied, set to `true` to avoid sharp premultiplying the image. (optional, default `false`) |
| [options.raw.pageHeight] | <code>number</code> | | The pixel height of each page/frame for animated images, must be an integral factor of `raw.height`. |
| [options.create] | <code>Object</code> | | describes a new image to be created. | | [options.create] | <code>Object</code> | | describes a new image to be created. |
| [options.create.width] | <code>number</code> | | integral number of pixels wide. | | [options.create.width] | <code>number</code> | | integral number of pixels wide. |
| [options.create.height] | <code>number</code> | | integral number of pixels high. | | [options.create.height] | <code>number</code> | | integral number of pixels high. |
| [options.create.channels] | <code>number</code> | | integral number of channels, either 3 (RGB) or 4 (RGBA). | | [options.create.channels] | <code>number</code> | | integral number of channels, either 3 (RGB) or 4 (RGBA). |
| [options.create.background] | <code>string</code> \| <code>Object</code> | | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. | | [options.create.background] | <code>string</code> \| <code>Object</code> | | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |
| [options.create.pageHeight] | <code>number</code> | | The pixel height of each page/frame for animated images, must be an integral factor of `create.height`. |
| [options.create.noise] | <code>Object</code> | | describes a noise to be created. | | [options.create.noise] | <code>Object</code> | | describes a noise to be created. |
| [options.create.noise.type] | <code>string</code> | | type of generated noise, currently only `gaussian` is supported. | | [options.create.noise.type] | <code>string</code> | | type of generated noise, currently only `gaussian` is supported. |
| [options.create.noise.mean] | <code>number</code> | | mean of pixels in generated noise. | | [options.create.noise.mean] | <code>number</code> | <code>128</code> | Mean value of pixels in the generated noise. |
| [options.create.noise.sigma] | <code>number</code> | | standard deviation of pixels in generated noise. | | [options.create.noise.sigma] | <code>number</code> | <code>30</code> | Standard deviation of pixel values in the generated noise. |
| [options.text] | <code>Object</code> | | describes a new text image to be created. | | [options.text] | <code>Object</code> | | describes a new text image to be created. |
| [options.text.text] | <code>string</code> | | text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`. | | [options.text.text] | <code>string</code> | | text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`. |
| [options.text.font] | <code>string</code> | | font name to render with. | | [options.text.font] | <code>string</code> | | font name to render with. |
@ -67,6 +73,24 @@ where the overall height is the `pageHeight` multiplied by the number of `pages`
| [options.text.rgba] | <code>boolean</code> | <code>false</code> | set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`. | | [options.text.rgba] | <code>boolean</code> | <code>false</code> | set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`. |
| [options.text.spacing] | <code>number</code> | <code>0</code> | text line height in points. Will use the font line height if none is specified. | | [options.text.spacing] | <code>number</code> | <code>0</code> | text line height in points. Will use the font line height if none is specified. |
| [options.text.wrap] | <code>string</code> | <code>&quot;&#x27;word&#x27;&quot;</code> | word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'. | | [options.text.wrap] | <code>string</code> | <code>&quot;&#x27;word&#x27;&quot;</code> | word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'. |
| [options.join] | <code>Object</code> | | describes how an array of input images should be joined. |
| [options.join.across] | <code>number</code> | <code>1</code> | number of images to join horizontally. |
| [options.join.animated] | <code>boolean</code> | <code>false</code> | set this to `true` to join the images as an animated image. |
| [options.join.shim] | <code>number</code> | <code>0</code> | number of pixels to insert between joined images. |
| [options.join.background] | <code>string</code> \| <code>Object</code> | | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |
| [options.join.halign] | <code>string</code> | <code>&quot;&#x27;left&#x27;&quot;</code> | horizontal alignment style for images joined horizontally (`'left'`, `'centre'`, `'center'`, `'right'`). |
| [options.join.valign] | <code>string</code> | <code>&quot;&#x27;top&#x27;&quot;</code> | vertical alignment style for images joined vertically (`'top'`, `'centre'`, `'center'`, `'bottom'`). |
| [options.tiff] | <code>Object</code> | | Describes TIFF specific options. |
| [options.tiff.subifd] | <code>number</code> | <code>-1</code> | Sub Image File Directory to extract for OME-TIFF, defaults to main image. |
| [options.svg] | <code>Object</code> | | Describes SVG specific options. |
| [options.svg.stylesheet] | <code>string</code> | | Custom CSS for SVG input, applied with a User Origin during the CSS cascade. |
| [options.svg.highBitdepth] | <code>boolean</code> | <code>false</code> | Set to `true` to render SVG input at 32-bits per channel (128-bit) instead of 8-bits per channel (32-bit) RGBA. |
| [options.pdf] | <code>Object</code> | | Describes PDF specific options. Requires the use of a globally-installed libvips compiled with support for PDFium, Poppler, ImageMagick or GraphicsMagick. |
| [options.pdf.background] | <code>string</code> \| <code>Object</code> | | Background colour to use when PDF is partially transparent. Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |
| [options.openSlide] | <code>Object</code> | | Describes OpenSlide specific options. Requires the use of a globally-installed libvips compiled with support for OpenSlide. |
| [options.openSlide.level] | <code>number</code> | <code>0</code> | Level to extract from a multi-level input, zero based. |
| [options.jp2] | <code>Object</code> | | Describes JPEG 2000 specific options. Requires the use of a globally-installed libvips compiled with support for OpenJPEG. |
| [options.jp2.oneshot] | <code>boolean</code> | <code>false</code> | Set to `true` to decode tiled JPEG 2000 images in a single operation, improving compatibility. |
**Example** **Example**
```js ```js
@ -166,6 +190,22 @@ await sharp({
} }
}).toFile('text_rgba.png'); }).toFile('text_rgba.png');
``` ```
**Example**
```js
// Join four input images as a 2x2 grid with a 4 pixel gutter
const data = await sharp(
[image1, image2, image3, image4],
{ join: { across: 2, shim: 4 } }
).toBuffer();
```
**Example**
```js
// Generate a two-frame animated image from emoji
const images = ['😀', '😛'].map(text => ({
text: { text, width: 64, height: 64, channels: 4, rgba: true }
}));
await sharp(images, { join: { animated: true } }).toFile('out.gif');
```
## clone ## clone

View File

@ -1,3 +1,8 @@
---
# This file was auto-generated from JSDoc in lib/input.js
title: Input metadata
---
## metadata ## metadata
> metadata([callback]) ⇒ <code>Promise.&lt;Object&gt;</code> \| <code>Sharp</code> > metadata([callback]) ⇒ <code>Promise.&lt;Object&gt;</code> \| <code>Sharp</code>
@ -22,15 +27,16 @@ A `Promise` is returned when `callback` is not provided.
- `density`: Number of pixels per inch (DPI), if present - `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 - `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 - `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan
- `isPalette`: Boolean indicating whether the image is palette-based (GIF, PNG).
- `bitsPerSample`: Number of bits per sample for each channel (GIF, PNG, HEIF).
- `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP - `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. - `pageHeight`: Number of pixels high each page in a multi-page image will be.
- `paletteBitDepth`: Bit depth of palette-based image (GIF, PNG).
- `loop`: Number of times to loop an animated image, zero refers to a continuous loop. - `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. - `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 - `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 - `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 - `subifds`: Number of Sub Image File Directories in an OME-TIFF image
- `background`: Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value - `background`: Default background colour, if present, for PNG (bKGD) and GIF images
- `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC) - `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC)
- `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present - `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present
- `hasProfile`: Boolean indicating the presence of an embedded ICC profile - `hasProfile`: Boolean indicating the presence of an embedded ICC profile
@ -42,6 +48,7 @@ A `Promise` is returned when `callback` is not provided.
- `xmp`: Buffer containing raw XMP data, if present - `xmp`: Buffer containing raw XMP data, if present
- `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present - `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present
- `formatMagick`: String containing format for images loaded via *magick - `formatMagick`: String containing format for images loaded via *magick
- `comments`: Array of keyword/text pairs representing PNG text blocks, if present.
@ -70,15 +77,9 @@ image
``` ```
**Example** **Example**
```js ```js
// Based on EXIF rotation metadata, get the right-side-up width and height: // Get dimensions taking EXIF Orientation into account.
const { autoOrient } = await sharp(input).metadata();
const size = getNormalSize(await sharp(input).metadata()); const { width, height } = autoOrient;
function getNormalSize({ width, height, orientation }) {
return (orientation || 0) >= 5
? { width: height, height: width }
: { width, height };
}
``` ```

View File

@ -1,22 +1,24 @@
---
# This file was auto-generated from JSDoc in lib/operation.js
title: Image operations
---
## rotate ## rotate
> rotate([angle], [options]) ⇒ <code>Sharp</code> > rotate([angle], [options]) ⇒ <code>Sharp</code>
Rotate the output image by either an explicit angle Rotate the output image.
or auto-orient based on the EXIF `Orientation` tag.
If an angle is provided, it is converted to a valid positive degree rotation. The provided angle is converted to a valid positive degree rotation.
For example, `-450` will produce a 270 degree rotation. For example, `-450` will produce a 270 degree rotation.
When rotating by an angle other than a multiple of 90, When rotating by an angle other than a multiple of 90,
the background colour can be provided with the `background` option. the background colour can be provided with the `background` option.
If no angle is provided, it is determined from the EXIF data. For backwards compatibility, if no angle is provided, `.autoOrient()` will be called.
Mirroring is supported and may infer the use of a flip operation.
The use of `rotate` without an angle will remove the EXIF `Orientation` tag, if any. Only one rotation can occur per pipeline (aside from an initial call without
arguments to orient via EXIF data). Previous calls to `rotate` in the same
Only one rotation can occur per pipeline. pipeline will be ignored.
Previous calls to `rotate` in the same pipeline will be ignored.
Multi-page images can only be rotated by 180 degrees. Multi-page images can only be rotated by 180 degrees.
@ -35,18 +37,6 @@ for example `.rotate(x).extract(y)` will produce a different result to `.extract
| [options] | <code>Object</code> | | if present, is an Object with optional attributes. | | [options] | <code>Object</code> | | if present, is an Object with optional attributes. |
| [options.background] | <code>string</code> \| <code>Object</code> | <code>&quot;\&quot;#000000\&quot;&quot;</code> | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. | | [options.background] | <code>string</code> \| <code>Object</code> | <code>&quot;\&quot;#000000\&quot;&quot;</code> | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |
**Example**
```js
const pipeline = sharp()
.rotate()
.resize(null, 200)
.toBuffer(function (err, outputBuffer, info) {
// outputBuffer contains 200px high JPEG image data,
// auto-rotated using EXIF Orientation tag
// info.width and info.height contain the dimensions of the resized image
});
readableStream.pipe(pipeline);
```
**Example** **Example**
```js ```js
const rotateThenResize = await sharp(input) const rotateThenResize = await sharp(input)
@ -60,6 +50,34 @@ const resizeThenRotate = await sharp(input)
``` ```
## autoOrient
> autoOrient() ⇒ <code>Sharp</code>
Auto-orient based on the EXIF `Orientation` tag, then remove the tag.
Mirroring is supported and may infer the use of a flip operation.
Previous or subsequent use of `rotate(angle)` and either `flip()` or `flop()`
will logically occur after auto-orientation, regardless of call order.
**Example**
```js
const output = await sharp(input).autoOrient().toBuffer();
```
**Example**
```js
const pipeline = sharp()
.autoOrient()
.resize(null, 200)
.toBuffer(function (err, outputBuffer, info) {
// outputBuffer contains 200px high JPEG image data,
// auto-oriented using EXIF Orientation tag
// info.width and info.height contain the dimensions of the resized image
});
readableStream.pipe(pipeline);
```
## flip ## flip
> flip([flip]) ⇒ <code>Sharp</code> > flip([flip]) ⇒ <code>Sharp</code>
@ -104,7 +122,7 @@ const output = await sharp(input).flop().toBuffer();
Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any. Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.
You must provide an array of length 4 or a 2x2 affine transformation matrix. You must provide an array of length 4 or a 2x2 affine transformation matrix.
By default, new pixels are filled with a black background. You can provide a background color with the `background` option. By default, new pixels are filled with a black background. You can provide a background colour with the `background` option.
A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`. A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`.
In the case of a 2x2 matrix, the transform is: In the case of a 2x2 matrix, the transform is:
@ -231,7 +249,7 @@ const output = await sharp(input).median(5).toBuffer();
## blur ## blur
> blur([sigma]) ⇒ <code>Sharp</code> > blur([options]) ⇒ <code>Sharp</code>
Blur the image. Blur the image.
@ -245,9 +263,12 @@ When a `sigma` is provided, performs a slower, more accurate Gaussian blur.
- <code>Error</code> Invalid parameters - <code>Error</code> Invalid parameters
| Param | Type | Description | | Param | Type | Default | Description |
| --- | --- | --- | | --- | --- | --- | --- |
| [sigma] | <code>number</code> | a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. | | [options] | <code>Object</code> \| <code>number</code> \| <code>Boolean</code> | | |
| [options.sigma] | <code>number</code> | | a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. |
| [options.precision] | <code>string</code> | <code>&quot;&#x27;integer&#x27;&quot;</code> | How accurate the operation should be, one of: integer, float, approximate. |
| [options.minAmplitude] | <code>number</code> | <code>0.2</code> | A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask. |
**Example** **Example**
```js ```js
@ -263,6 +284,52 @@ const gaussianBlurred = await sharp(input)
``` ```
## dilate
> dilate([width]) ⇒ <code>Sharp</code>
Expand foreground objects using the dilate morphological operator.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [width] | <code>Number</code> | <code>1</code> | dilation width in pixels. |
**Example**
```js
const output = await sharp(input)
.dilate()
.toBuffer();
```
## erode
> erode([width]) ⇒ <code>Sharp</code>
Shrink foreground objects using the erode morphological operator.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [width] | <code>Number</code> | <code>1</code> | erosion width in pixels. |
**Example**
```js
const output = await sharp(input)
.erode()
.toBuffer();
```
## flatten ## flatten
> flatten([options]) ⇒ <code>Sharp</code> > flatten([options]) ⇒ <code>Sharp</code>
@ -580,7 +647,7 @@ Recombine the image with the specified matrix.
| Param | Type | Description | | Param | Type | Description |
| --- | --- | --- | | --- | --- | --- |
| inputMatrix | <code>Array.&lt;Array.&lt;number&gt;&gt;</code> | 3x3 Recombination matrix | | inputMatrix | <code>Array.&lt;Array.&lt;number&gt;&gt;</code> | 3x3 or 4x4 Recombination matrix |
**Example** **Example**
```js ```js

View File

@ -1,3 +1,8 @@
---
# This file was auto-generated from JSDoc in lib/output.js
title: Output options
---
## toFile ## toFile
> toFile(fileOut, [callback]) ⇒ <code>Promise.&lt;Object&gt;</code> > toFile(fileOut, [callback]) ⇒ <code>Promise.&lt;Object&gt;</code>
@ -24,7 +29,7 @@ A `Promise` is returned when `callback` is not provided.
| Param | Type | Description | | Param | Type | Description |
| --- | --- | --- | | --- | --- | --- |
| fileOut | <code>string</code> | the path to write the image data to. | | fileOut | <code>string</code> | the path to write the image data to. |
| [callback] | <code>function</code> | 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`. When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region. May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. | | [callback] | <code>function</code> | 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`. When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region. Animated output will also contain `pageHeight` and `pages`. May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. |
**Example** **Example**
```js ```js
@ -59,6 +64,7 @@ See [withMetadata](#withmetadata) for control over this.
- `info` contains the output image `format`, `size` (bytes), `width`, `height`, - `info` contains the output image `format`, `size` (bytes), `width`, `height`,
`channels` and `premultiplied` (indicating if premultiplication was used). `channels` and `premultiplied` (indicating if premultiplication was used).
When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
Animated output will also contain `pageHeight` and `pages`.
May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.
A `Promise` is returned when `callback` is not provided. A `Promise` is returned when `callback` is not provided.
@ -236,6 +242,57 @@ const outputWithP3 = await sharp(input)
``` ```
## keepXmp
> keepXmp() ⇒ <code>Sharp</code>
Keep XMP metadata from the input image in the output image.
**Since**: 0.34.3
**Example**
```js
const outputWithXmp = await sharp(inputWithXmp)
.keepXmp()
.toBuffer();
```
## withXmp
> withXmp(xmp) ⇒ <code>Sharp</code>
Set XMP metadata in the output image.
Supported by PNG, JPEG, WebP, and TIFF output.
**Throws**:
- <code>Error</code> Invalid parameters
**Since**: 0.34.3
| Param | Type | Description |
| --- | --- | --- |
| xmp | <code>string</code> | String containing XMP metadata to be embedded in the output image. |
**Example**
```js
const xmpString = `
<?xml version="1.0"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">
<dc:creator><rdf:Seq><rdf:li>John Doe</rdf:li></rdf:Seq></dc:creator>
</rdf:Description>
</rdf:RDF>
</x:xmpmeta>`;
const data = await sharp(input)
.withXmp(xmpString)
.toBuffer();
```
## keepMetadata ## keepMetadata
> keepMetadata() ⇒ <code>Sharp</code> > keepMetadata() ⇒ <code>Sharp</code>
@ -438,6 +495,7 @@ Use these WebP options for output image.
| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression mode | | [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression mode |
| [options.nearLossless] | <code>boolean</code> | <code>false</code> | use near_lossless compression mode | | [options.nearLossless] | <code>boolean</code> | <code>false</code> | use near_lossless compression mode |
| [options.smartSubsample] | <code>boolean</code> | <code>false</code> | use high quality chroma subsampling | | [options.smartSubsample] | <code>boolean</code> | <code>false</code> | use high quality chroma subsampling |
| [options.smartDeblock] | <code>boolean</code> | <code>false</code> | auto-adjust the deblocking filter, can improve low contrast edges (slow) |
| [options.preset] | <code>string</code> | <code>&quot;&#x27;default&#x27;&quot;</code> | named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text | | [options.preset] | <code>string</code> | <code>&quot;&#x27;default&#x27;&quot;</code> | named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text |
| [options.effort] | <code>number</code> | <code>4</code> | CPU effort, between 0 (fastest) and 6 (slowest) | | [options.effort] | <code>number</code> | <code>4</code> | CPU effort, between 0 (fastest) and 6 (slowest) |
| [options.loop] | <code>number</code> | <code>0</code> | number of animation iterations, use 0 for infinite animation | | [options.loop] | <code>number</code> | <code>0</code> | number of animation iterations, use 0 for infinite animation |
@ -489,6 +547,7 @@ The palette of the input image will be re-used if possible.
| [options.dither] | <code>number</code> | <code>1.0</code> | level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) | | [options.dither] | <code>number</code> | <code>1.0</code> | level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) |
| [options.interFrameMaxError] | <code>number</code> | <code>0</code> | maximum inter-frame error for transparency, between 0 (lossless) and 32 | | [options.interFrameMaxError] | <code>number</code> | <code>0</code> | maximum inter-frame error for transparency, between 0 (lossless) and 32 |
| [options.interPaletteMaxError] | <code>number</code> | <code>3</code> | maximum inter-palette error for palette reuse, between 0 and 256 | | [options.interPaletteMaxError] | <code>number</code> | <code>3</code> | maximum inter-palette error for palette reuse, between 0 and 256 |
| [options.keepDuplicateFrames] | <code>boolean</code> | <code>false</code> | keep duplicate frames in the output instead of combining them |
| [options.loop] | <code>number</code> | <code>0</code> | number of animation iterations, use 0 for infinite animation | | [options.loop] | <code>number</code> | <code>0</code> | number of animation iterations, use 0 for infinite animation |
| [options.delay] | <code>number</code> \| <code>Array.&lt;number&gt;</code> | | delay(s) between animation frames (in milliseconds) | | [options.delay] | <code>number</code> \| <code>Array.&lt;number&gt;</code> | | delay(s) between animation frames (in milliseconds) |
| [options.force] | <code>boolean</code> | <code>true</code> | force GIF output, otherwise attempt to use input format | | [options.force] | <code>boolean</code> | <code>true</code> | force GIF output, otherwise attempt to use input format |
@ -619,6 +678,9 @@ Use these AVIF options for output image.
AVIF image sequences are not supported. AVIF image sequences are not supported.
Prebuilt binaries support a bitdepth of 8 only. Prebuilt binaries support a bitdepth of 8 only.
This feature is experimental on the Windows ARM64 platform
and requires a CPU with ARM64v8.4 or later.
**Throws**: **Throws**:
@ -693,8 +755,6 @@ Requires libvips compiled with support for libjxl.
The prebuilt binaries do not include this - see The prebuilt binaries do not include this - see
[installing a custom libvips](https://sharp.pixelplumbing.com/install#custom-libvips). [installing a custom libvips](https://sharp.pixelplumbing.com/install#custom-libvips).
Image metadata (EXIF, XMP) is unsupported.
**Throws**: **Throws**:
@ -709,7 +769,9 @@ Image metadata (EXIF, XMP) is unsupported.
| [options.quality] | <code>number</code> | | calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified | | [options.quality] | <code>number</code> | | calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified |
| [options.decodingTier] | <code>number</code> | <code>0</code> | target decode speed tier, between 0 (highest quality) and 4 (lowest quality) | | [options.decodingTier] | <code>number</code> | <code>0</code> | target decode speed tier, between 0 (highest quality) and 4 (lowest quality) |
| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression | | [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression |
| [options.effort] | <code>number</code> | <code>7</code> | CPU effort, between 3 (fastest) and 9 (slowest) | | [options.effort] | <code>number</code> | <code>7</code> | CPU effort, between 1 (fastest) and 9 (slowest) |
| [options.loop] | <code>number</code> | <code>0</code> | number of animation iterations, use 0 for infinite animation |
| [options.delay] | <code>number</code> \| <code>Array.&lt;number&gt;</code> | | delay(s) between animation frames (in milliseconds) |
@ -760,10 +822,6 @@ Use a `.zip` or `.szi` file extension with `toFile` to write to a compressed arc
The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`. The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`.
Requires libvips compiled with support for libgsf.
The prebuilt binaries do not include this - see
[installing a custom libvips](https://sharp.pixelplumbing.com/install#custom-libvips).
**Throws**: **Throws**:

View File

@ -1,3 +1,8 @@
---
# This file was auto-generated from JSDoc in lib/resize.js
title: Resizing images
---
## resize ## resize
> resize([width], [height], [options]) ⇒ <code>Sharp</code> > resize([width], [height], [options]) ⇒ <code>Sharp</code>
@ -12,7 +17,7 @@ When both a `width` and `height` are provided, the possible methods by which the
Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property. Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property.
<img alt="Examples of various values for the fit property when resizing" width="100%" style="aspect-ratio: 998/243" src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/api-resize-fit.svg"> <img alt="Examples of various values for the fit property when resizing" width="100%" style="aspect-ratio: 998/243" src="/api-resize-fit.svg">
When using a **fit** of `cover` or `contain`, the default **position** is `centre`. Other options are: 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.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`.
@ -33,6 +38,8 @@ Possible downsizing kernels are:
- `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf). - `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf).
- `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`. - `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`.
- `lanczos3`: Use a Lanczos kernel with `a=3` (the default). - `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
- `mks2013`: Use a [Magic Kernel Sharp](https://johncostella.com/magic/mks.pdf) 2013 kernel, as adopted by Facebook.
- `mks2021`: Use a Magic Kernel Sharp 2021 kernel, with more accurate (reduced) sharpening than the 2013 version.
When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators. When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators.
Downsampling kernels without a matching upsampling interpolator map to `cubic`. Downsampling kernels without a matching upsampling interpolator map to `cubic`.

View File

@ -1,3 +1,8 @@
---
# This file was auto-generated from JSDoc in lib/utility.js
title: Global properties
---
## versions ## versions
> versions > versions
@ -108,15 +113,9 @@ Some image format libraries spawn additional threads,
e.g. libaom manages its own 4 threads when encoding AVIF images, e.g. libaom manages its own 4 threads when encoding AVIF images,
and these are independent of the value set here. and these are independent of the value set here.
The maximum number of images that sharp can process in parallel :::note
is controlled by libuv's `UV_THREADPOOL_SIZE` environment variable, Further [control over performance](/performance) is available.
which defaults to 4. :::
https://nodejs.org/api/cli.html#uv_threadpool_sizesize
For example, by default, a machine with 8 CPU cores will process
4 images in parallel and use up to 8 threads per image,
so there will be up to 32 concurrent threads.
**Returns**: <code>number</code> - concurrency **Returns**: <code>number</code> - concurrency

View File

@ -1,8 +1,164 @@
# Changelog ---
title: Changelog
---
## v0.34 - *hat*
Requires libvips v8.17.1
### v0.34.3 - TBD
* Upgrade to libvips v8.17.1 for upstream bug fixes.
* Add "Magic Kernel Sharp" (no relation) to resizing kernels.
* Deprecate top-level, format-specific constructor parameters, e.g. `subifd` becomes `tiff.subifd`.
* Expose `stylesheet` and `highBitdepth` SVG input parameters.
* Expose `keepDuplicateFrames` GIF output parameter.
* Add support for RAW digital camera image input. Requires libvips compiled with libraw support.
* Provide XMP metadata as a string, as well as a Buffer, where possible.
* Add `pageHeight` option to `create` and `raw` input for animated images.
[#3236](https://github.com/lovell/sharp/issues/3236)
* Expose JPEG 2000 `oneshot` decoder option.
[#4262](https://github.com/lovell/sharp/pull/4262)
[@mbklein](https://github.com/mbklein)
* Support composite operation with non-sRGB pipeline colourspace.
[#4412](https://github.com/lovell/sharp/pull/4412)
[@kleisauke](https://github.com/kleisauke)
* Add `keepXmp` and `withXmp` for control over output XMP metadata.
[#4416](https://github.com/lovell/sharp/pull/4416)
[@tpatel](https://github.com/tpatel)
### v0.34.2 - 20th May 2025
* Ensure animated GIF to WebP conversion retains loop (regression in 0.34.0).
[#3394](https://github.com/lovell/sharp/issues/3394)
* Ensure `pdfBackground` constructor property is used.
[#4207](https://github.com/lovell/sharp/pull/4207)
[#4398](https://github.com/lovell/sharp/issues/4398)
* Add experimental support for prebuilt Windows ARM64 binaries.
[#4375](https://github.com/lovell/sharp/pull/4375)
[@hans00](https://github.com/hans00)
* Ensure resizing with a `fit` of `contain` supports multiple alpha channels.
[#4382](https://github.com/lovell/sharp/issues/4382)
* TypeScript: Ensure `metadata` response more closely matches reality.
[#4383](https://github.com/lovell/sharp/issues/4383)
* TypeScript: Ensure `smartDeblock` property is included in WebP definition.
[#4387](https://github.com/lovell/sharp/pull/4387)
[@Stephen-X](https://github.com/Stephen-X)
* Ensure support for wide-character filenames on Windows (regression in 0.34.0).
[#4391](https://github.com/lovell/sharp/issues/4391)
### v0.34.1 - 7th April 2025
* TypeScript: Ensure new `autoOrient` property is optional.
[#4362](https://github.com/lovell/sharp/pull/4362)
[@styfle](https://github.com/styfle)
### v0.34.0 - 4th April 2025
* Breaking: Support array of input images to be joined or animated.
[#1580](https://github.com/lovell/sharp/issues/1580)
* Breaking: Ensure `removeAlpha` removes all alpha channels.
[#2266](https://github.com/lovell/sharp/issues/2266)
* Breaking: Non-animated GIF output defaults to no-loop instead of loop-forever.
[#3394](https://github.com/lovell/sharp/issues/3394)
* Breaking: Support `info.size` on wide-character systems via upgrade to C++17.
[#3943](https://github.com/lovell/sharp/issues/3943)
* Breaking: Ensure `background` metadata can be parsed by `color` package.
[#4090](https://github.com/lovell/sharp/issues/4090)
* Add `isPalette` and `bitsPerSample` to metadata, deprecate `paletteBitDepth`.
* Expose WebP `smartDeblock` output option.
* Prevent use of linux-x64 binaries with v1 microarchitecture.
* Add `autoOrient` operation and constructor option.
[#4151](https://github.com/lovell/sharp/pull/4151)
[@happycollision](https://github.com/happycollision)
* TypeScript: Ensure channel counts use the correct range.
[#4197](https://github.com/lovell/sharp/pull/4197)
[@DavidVaness](https://github.com/DavidVaness)
* Improve support for ppc64le architecture.
[#4203](https://github.com/lovell/sharp/pull/4203)
[@sumitd2](https://github.com/sumitd2)
* Add `pdfBackground` constructor property.
[#4207](https://github.com/lovell/sharp/pull/4207)
[@calebmer](https://github.com/calebmer)
* Expose erode and dilate operations.
[#4243](https://github.com/lovell/sharp/pull/4243)
[@qpincon](https://github.com/qpincon)
* Add support for RGBE images. Requires libvips compiled with radiance support.
[#4316](https://github.com/lovell/sharp/pull/4316)
[@florentzabera](https://github.com/florentzabera)
* Allow wide-gamut HEIF output at higher bitdepths.
[#4344](https://github.com/lovell/sharp/issues/4344)
## v0.33 - *gauge* ## v0.33 - *gauge*
Requires libvips v8.15.2 Requires libvips v8.15.3
### v0.33.5 - 16th August 2024
* Upgrade to libvips v8.15.3 for upstream bug fixes.
* Add `pageHeight` and `pages` to response of multi-page output.
[#3411](https://github.com/lovell/sharp/issues/3411)
* Ensure option to force use of a globally-installed libvips works correctly.
[#4111](https://github.com/lovell/sharp/pull/4111)
[@project0](https://github.com/project0)
* Minimise use of `engines` property to improve yarn v1 support.
[#4130](https://github.com/lovell/sharp/issues/4130)
* Ensure `sharp.format.heif` includes only AVIF when using prebuilt binaries.
[#4132](https://github.com/lovell/sharp/issues/4132)
* Add support to recomb operation for 4x4 matrices.
[#4147](https://github.com/lovell/sharp/pull/4147)
[@ton11797](https://github.com/ton11797)
* Expose PNG text chunks as `comments` metadata.
[#4157](https://github.com/lovell/sharp/pull/4157)
[@nkeynes](https://github.com/nkeynes)
* Expose optional `precision` and `minAmplitude` parameters of `blur` operation.
[#4168](https://github.com/lovell/sharp/pull/4168)
[#4172](https://github.com/lovell/sharp/pull/4172)
[@marcosc90](https://github.com/marcosc90)
* Ensure `keepIccProfile` avoids colour transformation where possible.
[#4186](https://github.com/lovell/sharp/issues/4186)
* TypeScript: `chromaSubsampling` metadata is optional.
[#4191](https://github.com/lovell/sharp/pull/4191)
[@DavidVaness](https://github.com/DavidVaness)
### v0.33.4 - 16th May 2024 ### v0.33.4 - 16th May 2024

View File

@ -1,6 +1,8 @@
# sharp ---
title: "High performance Node.js image processing"
---
<img src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right"> <img src="/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right">
The typical use case for this high speed Node-API module The typical use case for this high speed Node-API module
is to convert large images in common formats to is to convert large images in common formats to
@ -23,7 +25,11 @@ rotation, extraction, compositing and gamma correction are available.
Most modern macOS, Windows and Linux systems Most modern macOS, Windows and Linux systems
do not require any additional install or runtime dependencies. do not require any additional install or runtime dependencies.
### Formats ```sh
npm install sharp
```
## Formats
This module supports reading JPEG, PNG, WebP, GIF, AVIF, TIFF and SVG images. This module supports reading JPEG, PNG, WebP, GIF, AVIF, TIFF and SVG images.
@ -37,7 +43,7 @@ Deep Zoom image pyramids can be generated,
suitable for use with "slippy map" tile viewers like suitable for use with "slippy map" tile viewers like
[OpenSeadragon](https://github.com/openseadragon/openseadragon). [OpenSeadragon](https://github.com/openseadragon/openseadragon).
### Fast ## Fast
This module is powered by the blazingly fast This module is powered by the blazingly fast
[libvips](https://github.com/libvips/libvips) image processing library, [libvips](https://github.com/libvips/libvips) image processing library,
@ -52,7 +58,7 @@ taking full advantage of multiple CPU cores and L1/L2/L3 cache.
Everything remains non-blocking thanks to _libuv_, Everything remains non-blocking thanks to _libuv_,
no child processes are spawned and Promises/async/await are supported. no child processes are spawned and Promises/async/await are supported.
### Optimal ## Optimal
The features of `mozjpeg` and `pngquant` can be used The features of `mozjpeg` and `pngquant` can be used
to optimise the file size of JPEG and PNG images respectively, to optimise the file size of JPEG and PNG images respectively,
@ -71,12 +77,12 @@ The file size of animated GIF output is optimised
without having to use separate command line tools such as without having to use separate command line tools such as
[gifsicle](https://www.lcdf.org/gifsicle/). [gifsicle](https://www.lcdf.org/gifsicle/).
### Contributing ## Contributing
A [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md) A [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md)
covers reporting bugs, requesting features and submitting code changes. covers reporting bugs, requesting features and submitting code changes.
### Licensing ## Licensing
Copyright 2013 Lovell Fuller and others. Copyright 2013 Lovell Fuller and others.

View File

@ -1,8 +1,12 @@
# Installation ---
title: Installation
---
Works with your choice of JavaScript package manager. Works with your choice of JavaScript package manager.
> ⚠️ **Please ensure your package manager is configured to install optional dependencies** :::caution
Please ensure your package manager is configured to install optional dependencies
:::
If a package manager lockfile must support multiple platforms, If a package manager lockfile must support multiple platforms,
please see the [cross-platform](#cross-platform) section please see the [cross-platform](#cross-platform) section
@ -16,13 +20,12 @@ npm install sharp
pnpm add sharp pnpm add sharp
``` ```
```sh When using `pnpm`, you may need to add `sharp` to
yarn add sharp [ignoredBuiltDependencies](https://pnpm.io/settings#ignoredbuiltdependencies)
``` to silence warnings.
```sh ```sh
# yarn v1 (maintenance mode) yarn add sharp
yarn add sharp --ignore-engines
``` ```
```sh ```sh
@ -41,14 +44,16 @@ deno run --allow-ffi ...
Ready-compiled sharp and libvips binaries are provided for use on the most common platforms: Ready-compiled sharp and libvips binaries are provided for use on the most common platforms:
* macOS x64 (>= 10.13) * macOS x64 (>= 10.15)
* macOS ARM64 * macOS ARM64
* Linux ARM (glibc >= 2.28) * Linux ARM (glibc >= 2.31)
* Linux ARM64 (glibc >= 2.26, musl >= 1.2.2) * Linux ARM64 (glibc >= 2.26, musl >= 1.2.2)
* Linux ppc64 (glibc >= 2.31)
* Linux s390x (glibc >= 2.31) * Linux s390x (glibc >= 2.31)
* Linux x64 (glibc >= 2.26, musl >= 1.2.2, CPU with SSE4.2) * Linux x64 (glibc >= 2.26, musl >= 1.2.2, CPU with SSE4.2)
* Windows x64 * Windows x64
* Windows x86 * Windows x86
* Windows ARM64 (experimental, CPU with ARMv8.4 required for all features)
This provides support for the This provides support for the
JPEG, PNG, WebP, AVIF (limited to 8-bit depth), TIFF, GIF and SVG (input) image formats. JPEG, PNG, WebP, AVIF (limited to 8-bit depth), TIFF, GIF and SVG (input) image formats.
@ -63,7 +68,9 @@ within the same installation tree and/or using the same lockfile.
### npm v10+ ### npm v10+
> ⚠️ **npm `package-lock.json` files can cause installation problems due to [npm bug #4828](https://github.com/npm/cli/issues/4828)** :::caution
npm `package-lock.json` files shared by multiple platforms can cause installation problems due to [npm bug #4828](https://github.com/npm/cli/issues/4828)
:::
Provides limited support via `--os`, `--cpu` and `--libc` flags. Provides limited support via `--os`, `--cpu` and `--libc` flags.
@ -87,12 +94,12 @@ Use the [supportedArchitectures](https://yarnpkg.com/configuration/yarnrc#suppor
### pnpm v8+ ### pnpm v8+
Use the [supportedArchitectures](https://pnpm.io/package_json#pnpmsupportedarchitectures) configuration. Use the [supportedArchitectures](https://pnpm.io/settings#supportedarchitectures) configuration.
## Custom libvips ## Custom libvips
To use a custom, globally-installed version of libvips instead of the provided binaries, To use a custom, globally-installed version of libvips instead of the provided binaries,
make sure it is at least the version listed under `engines.libvips` in the `package.json` file make sure it is at least the version listed under `config.libvips` in the `package.json` file
and that it can be located using `pkg-config --modversion vips-cpp`. and that it can be located using `pkg-config --modversion vips-cpp`.
For help compiling libvips and its dependencies, please see For help compiling libvips and its dependencies, please see
@ -115,7 +122,7 @@ environment variables.
Building from source requires: Building from source requires:
* C++11 compiler * C++17 compiler
* [node-addon-api](https://www.npmjs.com/package/node-addon-api) version 7+ * [node-addon-api](https://www.npmjs.com/package/node-addon-api) version 7+
* [node-gyp](https://github.com/nodejs/node-gyp#installation) version 9+ and its dependencies * [node-gyp](https://github.com/nodejs/node-gyp#installation) version 9+ and its dependencies
@ -126,6 +133,10 @@ If `node-addon-api` or `node-gyp` cannot be found, try adding them via:
npm install --save node-addon-api node-gyp npm install --save node-addon-api node-gyp
``` ```
When using `pnpm`, you may need to add `sharp` to
[onlyBuiltDependencies](https://pnpm.io/settings#onlybuiltdependencies)
to ensure the installation script can be run.
For cross-compiling, the `--platform`, `--arch` and `--libc` npm flags For cross-compiling, the `--platform`, `--arch` and `--libc` npm flags
(or the `npm_config_platform`, `npm_config_arch` and `npm_config_libc` environment variables) (or the `npm_config_platform`, `npm_config_arch` and `npm_config_libc` environment variables)
can be used to configure the target environment. can be used to configure the target environment.
@ -139,6 +150,8 @@ Use in web browsers is unsupported.
Native text rendering is unsupported. Native text rendering is unsupported.
[Tile-based output](/api-output#tile) is unsupported.
```sh ```sh
npm install --cpu=wasm32 sharp npm install --cpu=wasm32 sharp
``` ```
@ -162,7 +175,7 @@ The default memory allocator on most glibc-based Linux systems
processes that involve lots of small memory allocations. processes that involve lots of small memory allocations.
For this reason, by default, sharp will limit the use of thread-based For this reason, by default, sharp will limit the use of thread-based
[concurrency](api-utility#concurrency) when the glibc allocator is [concurrency](/api-utility#concurrency) when the glibc allocator is
detected at runtime. detected at runtime.
To help avoid fragmentation and improve performance on these systems, To help avoid fragmentation and improve performance on these systems,
@ -240,8 +253,10 @@ custom:
### electron ### electron
#### electron-builder
Ensure `sharp` is unpacked from the ASAR archive file using the Ensure `sharp` is unpacked from the ASAR archive file using the
[asarUnpack](https://www.electron.build/configuration/configuration.html) [asarUnpack](https://www.electron.build/app-builder-lib.interface.platformspecificbuildoptions#asarunpack)
option. option.
```json ```json
@ -256,6 +271,26 @@ option.
} }
``` ```
#### electron-forge
Ensure `sharp` is unpacked from the ASAR archive file using the
[unpack](https://js.electronforge.io/interfaces/_electron_forge_maker_squirrel.InternalOptions.Options.html#asar)
option.
```json
{
"packagerConfig": {
"asar": {
"unpack": "**/node_modules/{sharp,@img}/**/*"
}
}
}
```
When using `electron-forge` with [Webpack](#webpack),
you may also need to add
[forge-externals-plugin](https://www.npmjs.com/package/@timfish/forge-externals-plugin).
### vite ### vite
Ensure `sharp` is excluded from bundling via the Ensure `sharp` is excluded from bundling via the

View File

@ -0,0 +1,137 @@
---
title: Performance
---
## Parallelism and concurrency
Node.js uses a libuv-managed thread pool when processing asynchronous calls to native modules such as sharp.
The maximum number of images that sharp can process in parallel is controlled by libuv's
[`UV_THREADPOOL_SIZE`](https://nodejs.org/api/cli.html#uv_threadpool_sizesize)
environment variable, which defaults to 4.
When using more than 4 physical CPU cores, set this environment variable
before the Node.js process starts to increase the thread pool size.
```sh
export UV_THREADPOOL_SIZE="$(lscpu -p | egrep -v "^#" | sort -u -t, -k 2,4 | wc -l)"
```
libvips uses a glib-managed thread pool to avoid the overhead of spawning new threads.
The default number of threads used to concurrently process each image is the same as the number of CPU cores,
except when using glibc-based Linux without jemalloc, where the default is `1` to help reduce memory fragmentation.
Use [`sharp.concurrency()`](/api-utility/#concurrency) to manage the number of threads per image.
To reduce memory fragmentation when using the default Linux glibc memory allocator, set the
[`MALLOC_ARENA_MAX`](https://www.gnu.org/software/libc/manual/html_node/Memory-Allocation-Tunables.html)
environment variable before the Node.js process starts to reduce the number of memory pools.
```sh
export MALLOC_ARENA_MAX="2"
```
## Benchmark
A test to benchmark the performance of this module relative to alternatives.
Greater libvips performance can be expected with caching enabled (default)
and using 8+ core machines, especially those with larger L1/L2 CPU caches.
The I/O limits of the relevant (de)compression library will generally determine maximum throughput.
### Contenders
- [jimp](https://www.npmjs.com/package/jimp) v1.6.0 - Image processing in pure JavaScript.
- [imagemagick](https://www.npmjs.com/package/imagemagick) v0.1.3 - Supports filesystem only and "_has been unmaintained for a long time_".
- [gm](https://www.npmjs.com/package/gm) v1.25.1 - Fully featured wrapper around GraphicsMagick's `gm` command line utility, but "_has been sunset_".
- sharp v0.34.3 / libvips v8.17.0 - Caching within libvips disabled to ensure a fair comparison.
### Environment
#### AMD64
- AWS EC2 us-west-2 [c7a.xlarge](https://aws.amazon.com/ec2/instance-types/c7a/) (4x AMD EPYC 9R14)
- Ubuntu 25.04
- Node.js 24.3.0
#### ARM64
- AWS EC2 us-west-2 [c8g.xlarge](https://aws.amazon.com/ec2/instance-types/c8g/) (4x ARM Graviton4)
- Ubuntu 25.04
- Node.js 24.3.0
### Task: JPEG
Decompress a 2725x2225 JPEG image,
resize to 720x588 using Lanczos 3 resampling (where available),
then compress to JPEG at a "quality" setting of 80.
Note: jimp does not support Lanczos 3, bicubic resampling used instead.
#### Results: JPEG (AMD64)
| Package | I/O | Ops/sec | Speed-up |
| :---------- | :----- | ------: | -------: |
| jimp | buffer | 2.40 | 1.0 |
| jimp | file | 2.60 | 1.1 |
| imagemagick | file | 9.70 | 4.0 |
| gm | buffer | 11.60 | 4.8 |
| gm | file | 11.72 | 4.9 |
| sharp | stream | 59.40 | 24.8 |
| sharp | file | 62.67 | 26.1 |
| sharp | buffer | 64.42 | 26.8 |
#### Results: JPEG (ARM64)
| Package | I/O | Ops/sec | Speed-up |
| :---------- | :----- | ------: | -------: |
| jimp | buffer | 2.24 | 1.0 |
| jimp | file | 2.47 | 1.1 |
| imagemagick | file | 10.42 | 4.7 |
| gm | buffer | 12.80 | 5.7 |
| gm | file | 12.88 | 5.7 |
| sharp | stream | 45.58 | 20.3 |
| sharp | file | 47.99 | 21.4 |
| sharp | buffer | 49.20 | 22.0 |
### Task: PNG
Decompress a 2048x1536 RGBA PNG image,
premultiply the alpha channel,
resize to 720x540 using Lanczos 3 resampling (where available),
unpremultiply then compress as PNG with a "default" zlib compression level of 6
and without adaptive filtering.
Note: jimp does not support premultiply/unpremultiply.
#### Results: PNG (AMD64)
| Package | I/O | Ops/sec | Speed-up |
| :---------- | :----- | ------: | -------: |
| imagemagick | file | 6.06 | 1.0 |
| gm | file | 8.44 | 1.4 |
| jimp | buffer | 10.98 | 1.8 |
| sharp | file | 28.26 | 4.7 |
| sharp | buffer | 28.70 | 4.7 |
#### Results: PNG (ARM64)
| Package | I/O | Ops/sec | Speed-up |
| :---------- | :----- | ------: | -------: |
| imagemagick | file | 7.09 | 1.0 |
| gm | file | 8.93 | 1.3 |
| jimp | buffer | 10.28 | 1.5 |
| sharp | file | 23.81 | 3.4 |
| sharp | buffer | 24.19 | 3.4 |
## Running the benchmark test
Requires Docker.
```sh
git clone https://github.com/lovell/sharp.git
cd sharp/test/bench
./run-with-docker.sh
```

View File

@ -0,0 +1,45 @@
@view-transition {
navigation: auto;
}
:root {
--sl-content-width: 60rem;
--sl-color-accent-low: #072d00;
--sl-color-accent: #247f00;
--sl-color-accent-high: #aad7a0;
--sl-color-white: #ffffff;
--sl-color-gray-1: #eaf0e8;
--sl-color-gray-2: #c5cdc3;
--sl-color-gray-3: #99a796;
--sl-color-gray-4: #4f5c4d;
--sl-color-gray-5: #303c2d;
--sl-color-gray-6: #1f2a1c;
--sl-color-black: #151a13;
}
:root[data-theme="light"] {
--sl-color-accent-low: #c0e2b8;
--sl-color-accent: #165800;
--sl-color-accent-high: #0d3e00;
--sl-color-white: #151a13;
--sl-color-gray-1: #1f2a1c;
--sl-color-gray-2: #303c2d;
--sl-color-gray-3: #4f5c4d;
--sl-color-gray-4: #82907f;
--sl-color-gray-5: #bdc4bb;
--sl-color-gray-6: #eaf0e8;
--sl-color-gray-7: #f4f7f3;
--sl-color-black: #ffffff;
}
blockquote {
background-color: var(--sl-color-gray-6);
padding: 1rem;
}
.site-title::after {
content: "High performance Node.js image processing";
color: var(--sl-color-text);
font-size: var(--sl-text-sm);
padding-top: 0.3rem;
}

5
docs/tsconfig.json Normal file
View File

@ -0,0 +1,5 @@
{
"extends": "astro/tsconfigs/strict",
"include": [".astro/types.d.ts", "**/*"],
"exclude": ["dist"]
}

View File

@ -18,7 +18,7 @@ try {
} }
try { try {
const gyp = require('node-gyp'); const gyp = require('node-gyp');
log(`Found node-gyp version ${gyp().version}`); log(`Found node-gyp ${gyp().version}`);
} catch (err) { } catch (err) {
log('Please add node-gyp to your dependencies'); log('Please add node-gyp to your dependencies');
return; return;
@ -30,7 +30,7 @@ try {
} }
}; };
if (useGlobalLibvips()) { if (useGlobalLibvips(log)) {
buildFromSource(`Detected globally-installed libvips v${globalLibvipsVersion()}`); buildFromSource(`Detected globally-installed libvips v${globalLibvipsVersion()}`);
} else if (process.env.npm_config_build_from_source) { } else if (process.env.npm_config_build_from_source) {
buildFromSource('Detected --build-from-source flag'); buildFromSource('Detected --build-from-source flag');

View File

@ -16,7 +16,7 @@ const bool = {
}; };
/** /**
* Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel. * Remove alpha channels, if any. This is a no-op if the image does not have an alpha channel.
* *
* See also {@link /api-operation#flatten|flatten}. * See also {@link /api-operation#flatten|flatten}.
* *
@ -158,6 +158,7 @@ function bandbool (boolOp) {
/** /**
* Decorate the Sharp prototype with channel-related functions. * Decorate the Sharp prototype with channel-related functions.
* @module Sharp
* @private * @private
*/ */
module.exports = function (Sharp) { module.exports = function (Sharp) {

View File

@ -39,9 +39,9 @@ function tint (tint) {
/** /**
* Convert to 8-bit greyscale; 256 shades of grey. * Convert to 8-bit greyscale; 256 shades of grey.
* This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results. * This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results.
* By default the output image will be web-friendly sRGB and contain three (identical) color channels. * By default the output image will be web-friendly sRGB and contain three (identical) colour channels.
* This may be overridden by other sharp operations such as `toColourspace('b-w')`, * This may be overridden by other sharp operations such as `toColourspace('b-w')`,
* which will produce an output image containing one color channel. * which will produce an output image containing one colour channel.
* An alpha channel may be present, and will be unchanged by the operation. * An alpha channel may be present, and will be unchanged by the operation.
* *
* @example * @example
@ -135,17 +135,15 @@ function toColorspace (colorspace) {
} }
/** /**
* Update a colour attribute of the this.options Object. * Create a RGBA colour array from a given value.
* @private * @private
* @param {string} key
* @param {string|Object} value * @param {string|Object} value
* @throws {Error} Invalid value * @throws {Error} Invalid value
*/ */
function _setBackgroundColourOption (key, value) { function _getBackgroundColourOption (value) {
if (is.defined(value)) {
if (is.object(value) || is.string(value)) { if (is.object(value) || is.string(value)) {
const colour = color(value); const colour = color(value);
this.options[key] = [ return [
colour.red(), colour.red(),
colour.green(), colour.green(),
colour.blue(), colour.blue(),
@ -155,10 +153,23 @@ function _setBackgroundColourOption (key, value) {
throw is.invalidParameterError('background', 'object or string', value); throw is.invalidParameterError('background', 'object or string', value);
} }
} }
/**
* Update a colour attribute of the this.options Object.
* @private
* @param {string} key
* @param {string|Object} value
* @throws {Error} Invalid value
*/
function _setBackgroundColourOption (key, value) {
if (is.defined(value)) {
this.options[key] = _getBackgroundColourOption(value);
}
} }
/** /**
* Decorate the Sharp prototype with colour-related functions. * Decorate the Sharp prototype with colour-related functions.
* @module Sharp
* @private * @private
*/ */
module.exports = function (Sharp) { module.exports = function (Sharp) {
@ -172,6 +183,7 @@ module.exports = function (Sharp) {
toColourspace, toColourspace,
toColorspace, toColorspace,
// Private // Private
_getBackgroundColourOption,
_setBackgroundColourOption _setBackgroundColourOption
}); });
// Class attributes // Class attributes

View File

@ -46,8 +46,8 @@ const blend = {
* The images to composite must be the same size or smaller than the processed image. * The images to composite must be the same size or smaller than the processed image.
* If both `top` and `left` options are provided, they take precedence over `gravity`. * If both `top` and `left` options are provided, they take precedence over `gravity`.
* *
* Any resize, rotate or extract operations in the same processing pipeline * Other operations in the same processing pipeline (e.g. resize, rotate, flip,
* will always be applied to the input image before composition. * flop, extract) will always be applied to the input image before composition.
* *
* The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`, * The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`,
* `dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`, * `dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`,
@ -110,6 +110,7 @@ const blend = {
* @param {number} [images[].input.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified. * @param {number} [images[].input.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified.
* @param {boolean} [images[].input.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like `<span foreground="red">Red!</span>`. * @param {boolean} [images[].input.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like `<span foreground="red">Red!</span>`.
* @param {number} [images[].input.text.spacing=0] - text line height in points. Will use the font line height if none is specified. * @param {number} [images[].input.text.spacing=0] - text line height in points. Will use the font line height if none is specified.
* @param {Boolean} [images[].autoOrient=false] - set to true to use EXIF orientation data, if present, to orient the image.
* @param {String} [images[].blend='over'] - how to blend this image with the image below. * @param {String} [images[].blend='over'] - how to blend this image with the image below.
* @param {String} [images[].gravity='centre'] - gravity at which to place the overlay. * @param {String} [images[].gravity='centre'] - gravity at which to place the overlay.
* @param {Number} [images[].top] - the pixel offset from the top edge. * @param {Number} [images[].top] - the pixel offset from the top edge.
@ -202,6 +203,7 @@ function composite (images) {
/** /**
* Decorate the Sharp prototype with composite-related functions. * Decorate the Sharp prototype with composite-related functions.
* @module Sharp
* @private * @private
*/ */
module.exports = function (Sharp) { module.exports = function (Sharp) {

View File

@ -121,10 +121,25 @@ const debuglog = util.debuglog('sharp');
* } * }
* }).toFile('text_rgba.png'); * }).toFile('text_rgba.png');
* *
* @param {(Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string)} [input] - if present, can be * @example
* // Join four input images as a 2x2 grid with a 4 pixel gutter
* const data = await sharp(
* [image1, image2, image3, image4],
* { join: { across: 2, shim: 4 } }
* ).toBuffer();
*
* @example
* // Generate a two-frame animated image from emoji
* const images = ['😀', '😛'].map(text => ({
* text: { text, width: 64, height: 64, channels: 4, rgba: true }
* }));
* await sharp(images, { join: { animated: true } }).toFile('out.gif');
*
* @param {(Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string|Array)} [input] - if present, can be
* a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or * a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or
* a TypedArray containing raw pixel image data, or * a TypedArray containing raw pixel image data, or
* a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. * a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file.
* An array of inputs can be provided, and these will be joined together.
* JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. * JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present.
* @param {Object} [options] - if present, is an Object with optional attributes. * @param {Object} [options] - if present, is an Object with optional attributes.
* @param {string} [options.failOn='warning'] - When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort. * @param {string} [options.failOn='warning'] - When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort.
@ -132,13 +147,12 @@ const debuglog = util.debuglog('sharp');
* (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted. * (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). * An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF).
* @param {boolean} [options.unlimited=false] - Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). * @param {boolean} [options.unlimited=false] - Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF).
* @param {boolean} [options.autoOrient=false] - Set this to `true` to rotate/flip the image to match EXIF `Orientation`, if any.
* @param {boolean} [options.sequentialRead=true] - Set this to `false` to use random access rather than sequential read. Some operations will do this automatically. * @param {boolean} [options.sequentialRead=true] - Set this to `false` to use random access rather than sequential read. Some operations will do this automatically.
* @param {number} [options.density=72] - number representing the DPI for vector images in the range 1 to 100000. * @param {number} [options.density=72] - number representing the DPI for vector images in the range 1 to 100000.
* @param {number} [options.ignoreIcc=false] - should the embedded ICC profile, if any, be ignored. * @param {number} [options.ignoreIcc=false] - should the embedded ICC profile, if any, be ignored.
* @param {number} [options.pages=1] - Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages. * @param {number} [options.pages=1] - Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages.
* @param {number} [options.page=0] - Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based. * @param {number} [options.page=0] - Page number to start extracting from for multi-page input (GIF, WebP, TIFF), 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 (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`. * @param {boolean} [options.animated=false] - Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`.
* @param {Object} [options.raw] - describes raw pixel input image data. See `raw()` for pixel ordering. * @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.width] - integral number of pixels wide.
@ -146,15 +160,17 @@ const debuglog = util.debuglog('sharp');
* @param {number} [options.raw.channels] - integral number of channels, between 1 and 4. * @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` * @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`) * to avoid sharp premultiplying the image. (optional, default `false`)
* @param {number} [options.raw.pageHeight] - The pixel height of each page/frame for animated images, must be an integral factor of `raw.height`.
* @param {Object} [options.create] - describes a new image to be created. * @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.width] - integral number of pixels wide.
* @param {number} [options.create.height] - integral number of pixels high. * @param {number} [options.create.height] - integral number of pixels high.
* @param {number} [options.create.channels] - integral number of channels, either 3 (RGB) or 4 (RGBA). * @param {number} [options.create.channels] - integral number of channels, either 3 (RGB) or 4 (RGBA).
* @param {string|Object} [options.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. * @param {string|Object} [options.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
* @param {number} [options.create.pageHeight] - The pixel height of each page/frame for animated images, must be an integral factor of `create.height`.
* @param {Object} [options.create.noise] - describes a noise to be created. * @param {Object} [options.create.noise] - describes a noise to be created.
* @param {string} [options.create.noise.type] - type of generated noise, currently only `gaussian` is supported. * @param {string} [options.create.noise.type] - type of generated noise, currently only `gaussian` is supported.
* @param {number} [options.create.noise.mean] - mean of pixels in generated noise. * @param {number} [options.create.noise.mean=128] - Mean value of pixels in the generated noise.
* @param {number} [options.create.noise.sigma] - standard deviation of pixels in generated noise. * @param {number} [options.create.noise.sigma=30] - Standard deviation of pixel values in the generated noise.
* @param {Object} [options.text] - describes a new text image to be created. * @param {Object} [options.text] - describes a new text image to be created.
* @param {string} [options.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`. * @param {string} [options.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.
* @param {string} [options.text.font] - font name to render with. * @param {string} [options.text.font] - font name to render with.
@ -167,6 +183,24 @@ const debuglog = util.debuglog('sharp');
* @param {boolean} [options.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`. * @param {boolean} [options.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`.
* @param {number} [options.text.spacing=0] - text line height in points. Will use the font line height if none is specified. * @param {number} [options.text.spacing=0] - text line height in points. Will use the font line height if none is specified.
* @param {string} [options.text.wrap='word'] - word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'. * @param {string} [options.text.wrap='word'] - word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'.
* @param {Object} [options.join] - describes how an array of input images should be joined.
* @param {number} [options.join.across=1] - number of images to join horizontally.
* @param {boolean} [options.join.animated=false] - set this to `true` to join the images as an animated image.
* @param {number} [options.join.shim=0] - number of pixels to insert between joined images.
* @param {string|Object} [options.join.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
* @param {string} [options.join.halign='left'] - horizontal alignment style for images joined horizontally (`'left'`, `'centre'`, `'center'`, `'right'`).
* @param {string} [options.join.valign='top'] - vertical alignment style for images joined vertically (`'top'`, `'centre'`, `'center'`, `'bottom'`).
* @param {Object} [options.tiff] - Describes TIFF specific options.
* @param {number} [options.tiff.subifd=-1] - Sub Image File Directory to extract for OME-TIFF, defaults to main image.
* @param {Object} [options.svg] - Describes SVG specific options.
* @param {string} [options.svg.stylesheet] - Custom CSS for SVG input, applied with a User Origin during the CSS cascade.
* @param {boolean} [options.svg.highBitdepth=false] - Set to `true` to render SVG input at 32-bits per channel (128-bit) instead of 8-bits per channel (32-bit) RGBA.
* @param {Object} [options.pdf] - Describes PDF specific options. Requires the use of a globally-installed libvips compiled with support for PDFium, Poppler, ImageMagick or GraphicsMagick.
* @param {string|Object} [options.pdf.background] - Background colour to use when PDF is partially transparent. Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
* @param {Object} [options.openSlide] - Describes OpenSlide specific options. Requires the use of a globally-installed libvips compiled with support for OpenSlide.
* @param {number} [options.openSlide.level=0] - Level to extract from a multi-level input, zero based.
* @param {Object} [options.jp2] - Describes JPEG 2000 specific options. Requires the use of a globally-installed libvips compiled with support for OpenJPEG.
* @param {boolean} [options.jp2.oneshot=false] - Set to `true` to decode tiled JPEG 2000 images in a single operation, improving compatibility.
* @returns {Sharp} * @returns {Sharp}
* @throws {Error} Invalid parameters * @throws {Error} Invalid parameters
*/ */
@ -193,7 +227,6 @@ const Sharp = function (input, options) {
canvas: 'crop', canvas: 'crop',
position: 0, position: 0,
resizeBackground: [0, 0, 0, 255], resizeBackground: [0, 0, 0, 255],
useExifOrientation: false,
angle: 0, angle: 0,
rotationAngle: 0, rotationAngle: 0,
rotationBackground: [0, 0, 0, 255], rotationBackground: [0, 0, 0, 255],
@ -226,6 +259,8 @@ const Sharp = function (input, options) {
negateAlpha: true, negateAlpha: true,
medianSize: 0, medianSize: 0,
blurSigma: 0, blurSigma: 0,
precision: 'integer',
minAmpl: 0.2,
sharpenSigma: 0, sharpenSigma: 0,
sharpenM1: 1, sharpenM1: 1,
sharpenM2: 2, sharpenM2: 2,
@ -237,6 +272,8 @@ const Sharp = function (input, options) {
trimBackground: [], trimBackground: [],
trimThreshold: -1, trimThreshold: -1,
trimLineArt: false, trimLineArt: false,
dilateWidth: 0,
erodeWidth: 0,
gamma: 0, gamma: 0,
gammaOut: 0, gammaOut: 0,
greyscale: false, greyscale: false,
@ -269,7 +306,10 @@ const Sharp = function (input, options) {
withIccProfile: '', withIccProfile: '',
withExif: {}, withExif: {},
withExifMerge: true, withExifMerge: true,
withXmp: '',
resolveWithObject: false, resolveWithObject: false,
loop: -1,
delay: [],
// output format // output format
jpegQuality: 80, jpegQuality: 80,
jpegProgressive: false, jpegProgressive: false,
@ -297,6 +337,7 @@ const Sharp = function (input, options) {
webpLossless: false, webpLossless: false,
webpNearLossless: false, webpNearLossless: false,
webpSmartSubsample: false, webpSmartSubsample: false,
webpSmartDeblock: false,
webpPreset: 'default', webpPreset: 'default',
webpEffort: 4, webpEffort: 4,
webpMinSize: false, webpMinSize: false,
@ -306,6 +347,7 @@ const Sharp = function (input, options) {
gifDither: 1, gifDither: 1,
gifInterFrameMaxError: 0, gifInterFrameMaxError: 0,
gifInterPaletteMaxError: 3, gifInterPaletteMaxError: 3,
gifKeepDuplicateFrames: false,
gifReuse: true, gifReuse: true,
gifProgressive: false, gifProgressive: false,
tiffQuality: 80, tiffQuality: 80,
@ -346,6 +388,7 @@ const Sharp = function (input, options) {
timeoutSeconds: 0, timeoutSeconds: 0,
linearA: [], linearA: [],
linearB: [], linearB: [],
pdfBackground: [255, 255, 255, 255],
// Function to notify of libvips warnings // Function to notify of libvips warnings
debuglog: warning => { debuglog: warning => {
this.emit('warning', warning); this.emit('warning', warning);
@ -445,6 +488,7 @@ Object.assign(Sharp.prototype, { clone });
/** /**
* Export constructor. * Export constructor.
* @module Sharp
* @private * @private
*/ */
module.exports = Sharp; module.exports = Sharp;

378
lib/index.d.ts vendored
View File

@ -40,19 +40,7 @@ import { Duplex } from 'stream';
*/ */
declare function sharp(options?: sharp.SharpOptions): sharp.Sharp; declare function sharp(options?: sharp.SharpOptions): sharp.Sharp;
declare function sharp( declare function sharp(
input?: input?: sharp.SharpInput | Array<sharp.SharpInput>,
| Buffer
| ArrayBuffer
| Uint8Array
| Uint8ClampedArray
| Int8Array
| Uint16Array
| Int16Array
| Uint32Array
| Int32Array
| Float32Array
| Float64Array
| string,
options?: sharp.SharpOptions, options?: sharp.SharpOptions,
): sharp.Sharp; ): sharp.Sharp;
@ -62,33 +50,35 @@ declare namespace sharp {
/** An Object containing the version numbers of sharp, libvips and its dependencies. */ /** An Object containing the version numbers of sharp, libvips and its dependencies. */
const versions: { const versions: {
vips: string; aom?: string | undefined;
archive?: string | undefined;
cairo?: string | undefined; cairo?: string | undefined;
croco?: string | undefined; cgif?: string | undefined;
exif?: string | undefined; exif?: string | undefined;
expat?: string | undefined; expat?: string | undefined;
ffi?: string | undefined; ffi?: string | undefined;
fontconfig?: string | undefined; fontconfig?: string | undefined;
freetype?: string | undefined; freetype?: string | undefined;
gdkpixbuf?: string | undefined; fribidi?: string | undefined;
gif?: string | undefined;
glib?: string | undefined; glib?: string | undefined;
gsf?: string | undefined;
harfbuzz?: string | undefined; harfbuzz?: string | undefined;
jpeg?: string | undefined; heif?: string | undefined;
highway?: string | undefined;
imagequant?: string | undefined;
lcms?: string | undefined; lcms?: string | undefined;
orc?: string | undefined; mozjpeg?: string | undefined;
pango?: string | undefined; pango?: string | undefined;
pixman?: string | undefined; pixman?: string | undefined;
png?: string | undefined; png?: string | undefined;
sharp?: string | undefined; "proxy-libintl"?: string | undefined;
svg?: string | undefined; rsvg?: string | undefined;
sharp: string;
spng?: string | undefined;
tiff?: string | undefined; tiff?: string | undefined;
vips: string;
webp?: string | undefined; webp?: string | undefined;
avif?: string | undefined;
heif?: string | undefined;
xml?: string | undefined; xml?: string | undefined;
zlib?: string | undefined; "zlib-ng"?: string | undefined;
}; };
/** An Object containing the available interpolators and their proper values */ /** An Object containing the available interpolators and their proper values */
@ -244,14 +234,14 @@ declare namespace sharp {
* @param tint Parsed by the color module. * @param tint Parsed by the color module.
* @returns A sharp instance that can be used to chain operations * @returns A sharp instance that can be used to chain operations
*/ */
tint(tint: Color): Sharp; tint(tint: Colour | Color): Sharp;
/** /**
* Convert to 8-bit greyscale; 256 shades of grey. * Convert to 8-bit greyscale; 256 shades of grey.
* This is a linear operation. * This is a linear operation.
* If the input image is in a non-linear colour space such as sRGB, use gamma() with greyscale() for the best results. * If the input image is in a non-linear colour space such as sRGB, use gamma() with greyscale() for the best results.
* By default the output image will be web-friendly sRGB and contain three (identical) color channels. * By default the output image will be web-friendly sRGB and contain three (identical) colour channels.
* This may be overridden by other sharp operations such as toColourspace('b-w'), which will produce an output image containing one color channel. * This may be overridden by other sharp operations such as toColourspace('b-w'), which will produce an output image containing one colour channel.
* An alpha channel may be present, and will be unchanged by the operation. * An alpha channel may be present, and will be unchanged by the operation.
* @param greyscale true to enable and false to disable (defaults to true) * @param greyscale true to enable and false to disable (defaults to true)
* @returns A sharp instance that can be used to chain operations * @returns A sharp instance that can be used to chain operations
@ -364,24 +354,72 @@ declare namespace sharp {
//#region Operation functions //#region Operation functions
/** /**
* Rotate the output image by either an explicit angle or auto-orient based on the EXIF Orientation tag. * Rotate the output image by either an explicit angle
* or auto-orient based on the EXIF `Orientation` tag.
* *
* If an angle is provided, it is converted to a valid positive degree rotation. For example, -450 will produce a 270deg rotation. * If an angle is provided, it is converted to a valid positive degree rotation.
* For example, `-450` will produce a 270 degree rotation.
* *
* When rotating by an angle other than a multiple of 90, the background colour can be provided with the background option. * When rotating by an angle other than a multiple of 90,
* the background colour can be provided with the `background` option.
* *
* If no angle is provided, it is determined from the EXIF data. Mirroring is supported and may infer the use of a flip operation. * If no angle is provided, it is determined from the EXIF data.
* Mirroring is supported and may infer the use of a flip operation.
* *
* The use of rotate implies the removal of the EXIF Orientation tag, if any. * The use of `rotate` without an angle will remove the EXIF `Orientation` tag, if any.
* *
* Method order is important when both rotating and extracting regions, for example rotate(x).extract(y) will produce a different result to extract(y).rotate(x). * Only one rotation can occur per pipeline (aside from an initial call without
* @param angle angle of rotation. (optional, default auto) * arguments to orient via EXIF data). Previous calls to `rotate` in the same
* @param options if present, is an Object with optional attributes. * pipeline will be ignored.
*
* Multi-page images can only be rotated by 180 degrees.
*
* Method order is important when rotating, resizing and/or extracting regions,
* for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.
*
* @example
* const pipeline = sharp()
* .rotate()
* .resize(null, 200)
* .toBuffer(function (err, outputBuffer, info) {
* // outputBuffer contains 200px high JPEG image data,
* // auto-rotated using EXIF Orientation tag
* // info.width and info.height contain the dimensions of the resized image
* });
* readableStream.pipe(pipeline);
*
* @example
* const rotateThenResize = await sharp(input)
* .rotate(90)
* .resize({ width: 16, height: 8, fit: 'fill' })
* .toBuffer();
* const resizeThenRotate = await sharp(input)
* .resize({ width: 16, height: 8, fit: 'fill' })
* .rotate(90)
* .toBuffer();
*
* @param {number} [angle=auto] angle of rotation.
* @param {Object} [options] - if present, is an Object with optional attributes.
* @param {string|Object} [options.background="#000000"] parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
* @returns {Sharp}
* @throws {Error} Invalid parameters * @throws {Error} Invalid parameters
* @returns A sharp instance that can be used to chain operations
*/ */
rotate(angle?: number, options?: RotateOptions): Sharp; rotate(angle?: number, options?: RotateOptions): Sharp;
/**
* Alias for calling `rotate()` with no arguments, which orients the image based
* on EXIF orientsion.
*
* This operation is aliased to emphasize its purpose, helping to remove any
* confusion between rotation and orientation.
*
* @example
* const output = await sharp(input).autoOrient().toBuffer();
*
* @returns {Sharp}
*/
autoOrient(): Sharp
/** /**
* Flip the image about the vertical Y axis. This always occurs after rotation, if any. * Flip the image about the vertical Y axis. This always occurs after rotation, if any.
* The use of flip implies the removal of the EXIF Orientation tag, if any. * The use of flip implies the removal of the EXIF Orientation tag, if any.
@ -401,7 +439,7 @@ declare namespace sharp {
/** /**
* Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any. * Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.
* You must provide an array of length 4 or a 2x2 affine transformation matrix. * You must provide an array of length 4 or a 2x2 affine transformation matrix.
* By default, new pixels are filled with a black background. You can provide a background color with the `background` option. * By default, new pixels are filled with a black background. You can provide a background colour with the `background` option.
* A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`. * A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`.
* *
* In the case of a 2x2 matrix, the transform is: * In the case of a 2x2 matrix, the transform is:
@ -464,7 +502,23 @@ declare namespace sharp {
* @throws {Error} Invalid parameters * @throws {Error} Invalid parameters
* @returns A sharp instance that can be used to chain operations * @returns A sharp instance that can be used to chain operations
*/ */
blur(sigma?: number | boolean): Sharp; blur(sigma?: number | boolean | BlurOptions): Sharp;
/**
* Expand foreground objects using the dilate morphological operator.
* @param {Number} [width=1] dilation width in pixels.
* @throws {Error} Invalid parameters
* @returns A sharp instance that can be used to chain operations
*/
dilate(width?: number): Sharp;
/**
* Shrink foreground objects using the erode morphological operator.
* @param {Number} [width=1] erosion width in pixels.
* @throws {Error} Invalid parameters
* @returns A sharp instance that can be used to chain operations
*/
erode(width?: number): Sharp;
/** /**
* Merge alpha transparency channel, if any, with background. * Merge alpha transparency channel, if any, with background.
@ -571,11 +625,11 @@ declare namespace sharp {
/** /**
* Recomb the image with the specified matrix. * Recomb the image with the specified matrix.
* @param inputMatrix 3x3 Recombination matrix * @param inputMatrix 3x3 Recombination matrix or 4x4 Recombination matrix
* @throws {Error} Invalid parameters * @throws {Error} Invalid parameters
* @returns A sharp instance that can be used to chain operations * @returns A sharp instance that can be used to chain operations
*/ */
recomb(inputMatrix: Matrix3x3): Sharp; recomb(inputMatrix: Matrix3x3 | Matrix4x4): Sharp;
/** /**
* Transforms the image using brightness, saturation, hue rotation and lightness. * Transforms the image using brightness, saturation, hue rotation and lightness.
@ -676,6 +730,20 @@ declare namespace sharp {
*/ */
withIccProfile(icc: string, options?: WithIccProfileOptions): Sharp; withIccProfile(icc: string, options?: WithIccProfileOptions): Sharp;
/**
* Keep all XMP metadata from the input image in the output image.
* @returns A sharp instance that can be used to chain operations
*/
keepXmp(): Sharp;
/**
* Set XMP metadata in the output image.
* @param {string} xmp - String containing XMP metadata to be embedded in the output image.
* @returns A sharp instance that can be used to chain operations
* @throws {Error} Invalid parameters
*/
withXmp(xmp: string): Sharp;
/** /**
* Include all metadata (EXIF, XMP, IPTC) from the input image in the output image. * Include all metadata (EXIF, XMP, IPTC) from the input image in the output image.
* The default behaviour, when withMetadata is not used, is to strip all metadata and convert to the device-independent sRGB colour space. * The default behaviour, when withMetadata is not used, is to strip all metadata and convert to the device-independent sRGB colour space.
@ -799,8 +867,6 @@ declare namespace sharp {
* Use tile-based deep zoom (image pyramid) output. * Use tile-based deep zoom (image pyramid) output.
* Set the format and options for tile images via the toFormat, jpeg, png or webp functions. * Set the format and options for tile images via the toFormat, jpeg, png or webp functions.
* Use a .zip or .szi file extension with toFile to write to a compressed archive file format. * Use a .zip or .szi file extension with toFile to write to a compressed archive file format.
*
* Warning: multiple sharp instances concurrently producing tile output can expose a possible race condition in some versions of libgsf.
* @param tile tile options * @param tile tile options
* @throws {Error} Invalid options * @throws {Error} Invalid options
* @returns A sharp instance that can be used to chain operations * @returns A sharp instance that can be used to chain operations
@ -899,7 +965,27 @@ declare namespace sharp {
//#endregion //#endregion
} }
type SharpInput = Buffer
| ArrayBuffer
| Uint8Array
| Uint8ClampedArray
| Int8Array
| Uint16Array
| Int16Array
| Uint32Array
| Int32Array
| Float32Array
| Float64Array
| string;
interface SharpOptions { interface SharpOptions {
/**
* Auto-orient based on the EXIF `Orientation` tag, if present.
* Mirroring is supported and may infer the use of a flip operation.
*
* Using this option will remove the EXIF `Orientation` tag, if any.
*/
autoOrient?: boolean | undefined;
/** /**
* When to abort processing of invalid pixel data, one of (in order of sensitivity): * When to abort processing of invalid pixel data, one of (in order of sensitivity):
* 'none' (least), 'truncated', 'error' or 'warning' (most), highers level imply lower levels, invalid metadata will always abort. (optional, default 'warning') * 'none' (least), 'truncated', 'error' or 'warning' (most), highers level imply lower levels, invalid metadata will always abort. (optional, default 'warning')
@ -931,9 +1017,21 @@ declare namespace sharp {
pages?: number | undefined; pages?: number | undefined;
/** Page number to start extracting from for multi-page input (GIF, TIFF, PDF), zero based. (optional, default 0) */ /** Page number to start extracting from for multi-page input (GIF, TIFF, PDF), zero based. (optional, default 0) */
page?: number | undefined; page?: number | undefined;
/** subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. (optional, default -1) */ /** TIFF specific input options */
tiff?: TiffInputOptions | undefined;
/** SVG specific input options */
svg?: SvgInputOptions | undefined;
/** PDF specific input options */
pdf?: PdfInputOptions | undefined;
/** OpenSlide specific input options */
openSlide?: OpenSlideInputOptions | undefined;
/** JPEG 2000 specific input options */
jp2?: Jp2InputOptions | undefined;
/** Deprecated: use tiff.subifd instead */
subifd?: number | undefined; subifd?: number | undefined;
/** Level to extract from a multi-level input (OpenSlide), zero based. (optional, default 0) */ /** Deprecated: use pdf.background instead */
pdfBackground?: Colour | Color | undefined;
/** Deprecated: use openSlide.level instead */
level?: number | undefined; level?: number | undefined;
/** Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). (optional, default false) */ /** Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). (optional, default false) */
animated?: boolean | undefined; animated?: boolean | undefined;
@ -943,6 +1041,8 @@ declare namespace sharp {
create?: Create | undefined; create?: Create | undefined;
/** Describes a new text image to be created. */ /** Describes a new text image to be created. */
text?: CreateText | undefined; text?: CreateText | undefined;
/** Describes how array of input images should be joined. */
join?: Join | undefined;
} }
interface CacheOptions { interface CacheOptions {
@ -969,25 +1069,32 @@ declare namespace sharp {
interface Raw { interface Raw {
width: number; width: number;
height: number; height: number;
channels: 1 | 2 | 3 | 4; channels: Channels;
} }
interface CreateRaw extends Raw { interface CreateRaw extends Raw {
/** Specifies that the raw input has already been premultiplied, set to true to avoid sharp premultiplying the image. (optional, default false) */ /** Specifies that the raw input has already been premultiplied, set to true to avoid sharp premultiplying the image. (optional, default false) */
premultiplied?: boolean | undefined; premultiplied?: boolean | undefined;
/** The height of each page/frame for animated images, must be an integral factor of the overall image height. */
pageHeight?: number | undefined;
} }
type CreateChannels = 3 | 4;
interface Create { interface Create {
/** Number of pixels wide. */ /** Number of pixels wide. */
width: number; width: number;
/** Number of pixels high. */ /** Number of pixels high. */
height: number; height: number;
/** Number of bands e.g. 3 for RGB, 4 for RGBA */ /** Number of bands, 3 for RGB, 4 for RGBA */
channels: Channels; channels: CreateChannels;
/** Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. */ /** Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. */
background: Color; background: Colour | Color;
/** Describes a noise to be created. */ /** Describes a noise to be created. */
noise?: Noise | undefined; noise?: Noise | undefined;
/** The height of each page/frame for animated images, must be an integral factor of the overall image height. */
pageHeight?: number | undefined;
} }
interface CreateText { interface CreateText {
@ -1021,6 +1128,48 @@ declare namespace sharp {
wrap?: TextWrap; wrap?: TextWrap;
} }
interface Join {
/** Number of images per row. */
across?: number | undefined;
/** Treat input as frames of an animated image. */
animated?: boolean | undefined;
/** Space between images, in pixels. */
shim?: number | undefined;
/** Background colour. */
background?: Colour | Color | undefined;
/** Horizontal alignment. */
halign?: HorizontalAlignment | undefined;
/** Vertical alignment. */
valign?: VerticalAlignment | undefined;
}
interface TiffInputOptions {
/** Sub Image File Directory to extract, defaults to main image. Use -1 for all subifds. */
subifd?: number | undefined;
}
interface SvgInputOptions {
/** Custom CSS for SVG input, applied with a User Origin during the CSS cascade. */
stylesheet?: string | undefined;
/** Set to `true` to render SVG input at 32-bits per channel (128-bit) instead of 8-bits per channel (32-bit) RGBA. */
highBitdepth?: boolean | undefined;
}
interface PdfInputOptions {
/** Background colour to use when PDF is partially transparent. Requires the use of a globally-installed libvips compiled with support for PDFium, Poppler, ImageMagick or GraphicsMagick. */
background?: Colour | Color | undefined;
}
interface OpenSlideInputOptions {
/** Level to extract from a multi-level input, zero based. (optional, default 0) */
level?: number | undefined;
}
interface Jp2InputOptions {
/** Set to `true` to load JPEG 2000 images using [oneshot mode](https://github.com/libvips/libvips/issues/4205) */
oneshot?: boolean | undefined;
}
interface ExifDir { interface ExifDir {
[k: string]: string; [k: string]: string;
} }
@ -1053,25 +1202,36 @@ declare namespace sharp {
/** Number value of the EXIF Orientation header, if present */ /** Number value of the EXIF Orientation header, if present */
orientation?: number | undefined; orientation?: number | undefined;
/** Name of decoder used to decompress image data e.g. jpeg, png, webp, gif, svg */ /** Name of decoder used to decompress image data e.g. jpeg, png, webp, gif, svg */
format?: keyof FormatEnum | undefined; format: keyof FormatEnum;
/** Total size of image in bytes, for Stream and Buffer input only */ /** Total size of image in bytes, for Stream and Buffer input only */
size?: number | undefined; size?: number | undefined;
/** Number of pixels wide (EXIF orientation is not taken into consideration) */ /** Number of pixels wide (EXIF orientation is not taken into consideration) */
width?: number | undefined; width: number;
/** Number of pixels high (EXIF orientation is not taken into consideration) */ /** Number of pixels high (EXIF orientation is not taken into consideration) */
height?: number | undefined; height: number;
/** Any changed metadata after the image orientation is applied. */
autoOrient: {
/** Number of pixels wide (EXIF orientation is taken into consideration) */
width: number;
/** Number of pixels high (EXIF orientation is taken into consideration) */
height: number;
};
/** Name of colour space interpretation */ /** Name of colour space interpretation */
space?: keyof ColourspaceEnum | undefined; space: keyof ColourspaceEnum;
/** Number of bands e.g. 3 for sRGB, 4 for CMYK */ /** Number of bands e.g. 3 for sRGB, 4 for CMYK */
channels?: Channels | undefined; channels: Channels;
/** Name of pixel depth format e.g. uchar, char, ushort, float ... */ /** Name of pixel depth format e.g. uchar, char, ushort, float ... */
depth?: string | undefined; depth: keyof DepthEnum;
/** Number of pixels per inch (DPI), if present */ /** Number of pixels per inch (DPI), if present */
density?: number | undefined; density?: number | undefined;
/** 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 */ /** 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 */
chromaSubsampling: string; chromaSubsampling?: string | undefined;
/** Boolean indicating whether the image is interlaced using a progressive scan */ /** Boolean indicating whether the image is interlaced using a progressive scan */
isProgressive?: boolean | undefined; isProgressive: boolean;
/** Boolean indicating whether the image is palette-based (GIF, PNG). */
isPalette: boolean;
/** Number of bits per sample for each channel (GIF, PNG). */
bitsPerSample?: number | undefined;
/** Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP */ /** Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP */
pages?: number | undefined; pages?: number | undefined;
/** Number of pixels high each page in a multi-page image will be. */ /** Number of pixels high each page in a multi-page image will be. */
@ -1083,9 +1243,9 @@ declare namespace sharp {
/** Number of the primary page in a HEIF image */ /** Number of the primary page in a HEIF image */
pagePrimary?: number | undefined; pagePrimary?: number | undefined;
/** Boolean indicating the presence of an embedded ICC profile */ /** Boolean indicating the presence of an embedded ICC profile */
hasProfile?: boolean | undefined; hasProfile: boolean;
/** Boolean indicating the presence of an alpha transparency channel */ /** Boolean indicating the presence of an alpha transparency channel */
hasAlpha?: boolean | undefined; hasAlpha: boolean;
/** Buffer containing raw EXIF data, if present */ /** Buffer containing raw EXIF data, if present */
exif?: Buffer | undefined; exif?: Buffer | undefined;
/** Buffer containing raw ICC profile data, if present */ /** Buffer containing raw ICC profile data, if present */
@ -1094,12 +1254,14 @@ declare namespace sharp {
iptc?: Buffer | undefined; iptc?: Buffer | undefined;
/** Buffer containing raw XMP data, if present */ /** Buffer containing raw XMP data, if present */
xmp?: Buffer | undefined; xmp?: Buffer | undefined;
/** String containing XMP data, if valid UTF-8 */
xmpAsString?: string | undefined;
/** Buffer containing raw TIFFTAG_PHOTOSHOP data, if present */ /** Buffer containing raw TIFFTAG_PHOTOSHOP data, if present */
tifftagPhotoshop?: Buffer | undefined; tifftagPhotoshop?: Buffer | undefined;
/** The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC) */ /** The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC) */
compression?: 'av1' | 'hevc'; compression?: 'av1' | 'hevc';
/** Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value */ /** Default background colour, if present, for PNG (bKGD) and GIF images */
background?: { r: number; g: number; b: number } | number; background?: { r: number; g: number; b: number } | { gray: number };
/** Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide */ /** Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide */
levels?: LevelMetadata[] | undefined; levels?: LevelMetadata[] | undefined;
/** Number of Sub Image File Directories in an OME-TIFF image */ /** Number of Sub Image File Directories in an OME-TIFF image */
@ -1108,6 +1270,8 @@ declare namespace sharp {
resolutionUnit?: 'inch' | 'cm' | undefined; resolutionUnit?: 'inch' | 'cm' | undefined;
/** String containing format for images loaded via *magick */ /** String containing format for images loaded via *magick */
formatMagick?: string | undefined; formatMagick?: string | undefined;
/** Array of keyword/text pairs representing PNG text blocks, if present. */
comments?: CommentsMetadata[] | undefined;
} }
interface LevelMetadata { interface LevelMetadata {
@ -1115,6 +1279,11 @@ declare namespace sharp {
height: number; height: number;
} }
interface CommentsMetadata {
keyword: string;
text: string;
}
interface Stats { interface Stats {
/** Array of channel statistics for each channel in the image. */ /** Array of channel statistics for each channel in the image. */
channels: ChannelStats[]; channels: ChannelStats[];
@ -1225,6 +1394,8 @@ declare namespace sharp {
nearLossless?: boolean | undefined; nearLossless?: boolean | undefined;
/** Use high quality chroma subsampling (optional, default false) */ /** Use high quality chroma subsampling (optional, default false) */
smartSubsample?: boolean | undefined; smartSubsample?: boolean | undefined;
/** Auto-adjust the deblocking filter, slow but can improve low contrast edges (optional, default false) */
smartDeblock?: boolean | undefined;
/** Level of CPU effort to reduce file size, integer 0-6 (optional, default 4) */ /** Level of CPU effort to reduce file size, integer 0-6 (optional, default 4) */
effort?: number | undefined; effort?: number | undefined;
/** Prevent use of animation key frames to minimise file size (slow) (optional, default false) */ /** Prevent use of animation key frames to minimise file size (slow) (optional, default false) */
@ -1277,9 +1448,11 @@ declare namespace sharp {
/** Level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) (optional, default 1.0) */ /** Level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) (optional, default 1.0) */
dither?: number | undefined; dither?: number | undefined;
/** Maximum inter-frame error for transparency, between 0 (lossless) and 32 (optional, default 0) */ /** Maximum inter-frame error for transparency, between 0 (lossless) and 32 (optional, default 0) */
interFrameMaxError?: number; interFrameMaxError?: number | undefined;
/** Maximum inter-palette error for palette reuse, between 0 and 256 (optional, default 3) */ /** Maximum inter-palette error for palette reuse, between 0 and 256 (optional, default 3) */
interPaletteMaxError?: number; interPaletteMaxError?: number | undefined;
/** Keep duplicate frames in the output instead of combining them (optional, default false) */
keepDuplicateFrames?: boolean | undefined;
} }
interface TiffOptions extends OutputOptions { interface TiffOptions extends OutputOptions {
@ -1332,12 +1505,23 @@ declare namespace sharp {
interface RotateOptions { interface RotateOptions {
/** parsed by the color module to extract values for red, green, blue and alpha. (optional, default "#000000") */ /** parsed by the color module to extract values for red, green, blue and alpha. (optional, default "#000000") */
background?: Color | undefined; background?: Colour | Color | undefined;
}
type Precision = 'integer' | 'float' | 'approximate';
interface BlurOptions {
/** A value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2` */
sigma: number;
/** A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask. */
minAmplitude?: number;
/** How accurate the operation should be, one of: integer, float, approximate. (optional, default "integer") */
precision?: Precision | undefined;
} }
interface FlattenOptions { interface FlattenOptions {
/** background colour, parsed by the color module, defaults to black. (optional, default {r:0,g:0,b:0}) */ /** background colour, parsed by the color module, defaults to black. (optional, default {r:0,g:0,b:0}) */
background?: Color | undefined; background?: Colour | Color | undefined;
} }
interface NegateOptions { interface NegateOptions {
@ -1362,7 +1546,7 @@ declare namespace sharp {
/** Position, gravity or strategy to use when fit is cover or contain. (optional, default 'centre') */ /** Position, gravity or strategy to use when fit is cover or contain. (optional, default 'centre') */
position?: number | string | undefined; position?: number | string | undefined;
/** Background colour when using a fit of contain, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */ /** Background colour when using a fit of contain, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */
background?: Color | undefined; background?: Colour | Color | undefined;
/** The kernel to use for image reduction. (optional, default 'lanczos3') */ /** The kernel to use for image reduction. (optional, default 'lanczos3') */
kernel?: keyof KernelEnum | undefined; kernel?: keyof KernelEnum | undefined;
/** Do not enlarge if the width or height are already less than the specified dimensions, equivalent to GraphicsMagick's > geometry option. (optional, default false) */ /** Do not enlarge if the width or height are already less than the specified dimensions, equivalent to GraphicsMagick's > geometry option. (optional, default false) */
@ -1386,7 +1570,7 @@ declare namespace sharp {
interface Noise { interface Noise {
/** type of generated noise, currently only gaussian is supported. */ /** type of generated noise, currently only gaussian is supported. */
type?: 'gaussian' | undefined; type: 'gaussian';
/** mean of pixels in generated noise. */ /** mean of pixels in generated noise. */
mean?: number | undefined; mean?: number | undefined;
/** standard deviation of pixels in generated noise. */ /** standard deviation of pixels in generated noise. */
@ -1405,14 +1589,14 @@ declare namespace sharp {
/** single pixel count to right edge (optional, default 0) */ /** single pixel count to right edge (optional, default 0) */
right?: number | undefined; right?: number | undefined;
/** background colour, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */ /** background colour, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */
background?: Color | undefined; background?: Colour | Color | undefined;
/** how the extension is done, one of: "background", "copy", "repeat", "mirror" (optional, default `'background'`) */ /** how the extension is done, one of: "background", "copy", "repeat", "mirror" (optional, default `'background'`) */
extendWith?: ExtendWith | undefined; extendWith?: ExtendWith | undefined;
} }
interface TrimOptions { interface TrimOptions {
/** Background colour, parsed by the color module, defaults to that of the top-left pixel. (optional) */ /** Background colour, parsed by the color module, defaults to that of the top-left pixel. (optional) */
background?: Color | undefined; background?: Colour | Color | undefined;
/** Allowed difference from the above colour, a positive number. (optional, default 10) */ /** Allowed difference from the above colour, a positive number. (optional, default 10) */
threshold?: number | undefined; threshold?: number | undefined;
/** Does the input more closely resemble line art (e.g. vector) rather than being photographic? (optional, default false) */ /** Does the input more closely resemble line art (e.g. vector) rather than being photographic? (optional, default false) */
@ -1423,8 +1607,8 @@ declare namespace sharp {
depth?: 'char' | 'uchar' | 'short' | 'ushort' | 'int' | 'uint' | 'float' | 'complex' | 'double' | 'dpcomplex'; depth?: 'char' | 'uchar' | 'short' | 'ushort' | 'int' | 'uint' | 'float' | 'complex' | 'double' | 'dpcomplex';
} }
/** 3 for sRGB, 4 for CMYK */ /** 1 for grayscale, 2 for grayscale + alpha, 3 for sRGB, 4 for CMYK or RGBA */
type Channels = 3 | 4; type Channels = 1 | 2 | 3 | 4;
interface RGBA { interface RGBA {
r?: number | undefined; r?: number | undefined;
@ -1433,7 +1617,8 @@ declare namespace sharp {
alpha?: number | undefined; alpha?: number | undefined;
} }
type Color = string | RGBA; type Colour = string | RGBA;
type Color = Colour;
interface Kernel { interface Kernel {
/** width of the kernel in pixels. */ /** width of the kernel in pixels. */
@ -1487,6 +1672,8 @@ declare namespace sharp {
failOn?: FailOnOptions | undefined; failOn?: FailOnOptions | undefined;
/** see sharp() constructor, (optional, default 268402689) */ /** see sharp() constructor, (optional, default 268402689) */
limitInputPixels?: number | boolean | undefined; limitInputPixels?: number | boolean | undefined;
/** see sharp() constructor, (optional, default false) */
autoOrient?: boolean | undefined;
} }
interface TileOptions { interface TileOptions {
@ -1558,7 +1745,7 @@ declare namespace sharp {
size: number; size: number;
width: number; width: number;
height: number; height: number;
channels: 1 | 2 | 3 | 4; channels: Channels;
/** indicating if premultiplication was used */ /** indicating if premultiplication was used */
premultiplied: boolean; premultiplied: boolean;
/** Only defined when using a crop strategy */ /** Only defined when using a crop strategy */
@ -1574,6 +1761,10 @@ declare namespace sharp {
/** When using the attention crop strategy, the focal point of the cropped region */ /** When using the attention crop strategy, the focal point of the cropped region */
attentionX?: number | undefined; attentionX?: number | undefined;
attentionY?: number | undefined; attentionY?: number | undefined;
/** Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP */
pages?: number | undefined;
/** Number of pixels high each page in a multi-page image will be. */
pageHeight?: number | undefined;
} }
interface AvailableFormatInfo { interface AvailableFormatInfo {
@ -1596,6 +1787,8 @@ declare namespace sharp {
mitchell: 'mitchell'; mitchell: 'mitchell';
lanczos2: 'lanczos2'; lanczos2: 'lanczos2';
lanczos3: 'lanczos3'; lanczos3: 'lanczos3';
mks2013: 'mks2013';
mks2021: 'mks2021';
} }
interface PresetEnum { interface PresetEnum {
@ -1614,11 +1807,38 @@ declare namespace sharp {
} }
interface ColourspaceEnum { interface ColourspaceEnum {
multiband: string;
'b-w': string; 'b-w': string;
bw: string; cmc: string;
cmyk: string; cmyk: string;
fourier: string;
grey16: string;
histogram: string;
hsv: string;
lab: string;
labq: string;
labs: string;
lch: string;
matrix: string;
multiband: string;
rgb: string;
rgb16: string;
scrgb: string;
srgb: string; srgb: string;
xyz: string;
yxy: string;
}
interface DepthEnum {
char: string;
complex: string;
double: string;
dpcomplex: string;
float: string;
int: string;
short: string;
uchar: string;
uint: string;
ushort: string;
} }
type FailOnOptions = 'none' | 'truncated' | 'error' | 'warning'; type FailOnOptions = 'none' | 'truncated' | 'error' | 'warning';
@ -1627,6 +1847,10 @@ declare namespace sharp {
type TextWrap = 'word' | 'char' | 'word-char' | 'none'; type TextWrap = 'word' | 'char' | 'word-char' | 'none';
type HorizontalAlignment = 'left' | 'centre' | 'center' | 'right';
type VerticalAlignment = 'top' | 'centre' | 'center' | 'bottom';
type TileContainer = 'fs' | 'zip'; type TileContainer = 'fs' | 'zip';
type TileLayout = 'dz' | 'iiif' | 'iiif3' | 'zoomify' | 'google'; type TileLayout = 'dz' | 'iiif' | 'iiif3' | 'zoomify' | 'google';
@ -1682,7 +1906,9 @@ declare namespace sharp {
interface FormatEnum { interface FormatEnum {
avif: AvailableFormatInfo; avif: AvailableFormatInfo;
dcraw: AvailableFormatInfo;
dz: AvailableFormatInfo; dz: AvailableFormatInfo;
exr: AvailableFormatInfo;
fits: AvailableFormatInfo; fits: AvailableFormatInfo;
gif: AvailableFormatInfo; gif: AvailableFormatInfo;
heif: AvailableFormatInfo; heif: AvailableFormatInfo;
@ -1696,6 +1922,7 @@ declare namespace sharp {
pdf: AvailableFormatInfo; pdf: AvailableFormatInfo;
png: AvailableFormatInfo; png: AvailableFormatInfo;
ppm: AvailableFormatInfo; ppm: AvailableFormatInfo;
rad: AvailableFormatInfo;
raw: AvailableFormatInfo; raw: AvailableFormatInfo;
svg: AvailableFormatInfo; svg: AvailableFormatInfo;
tiff: AvailableFormatInfo; tiff: AvailableFormatInfo;
@ -1730,6 +1957,7 @@ declare namespace sharp {
type Matrix2x2 = [[number, number], [number, number]]; type Matrix2x2 = [[number, number], [number, number]];
type Matrix3x3 = [[number, number, number], [number, number, number], [number, number, number]]; type Matrix3x3 = [[number, number, number], [number, number, number], [number, number, number]];
type Matrix4x4 = [[number, number, number, number], [number, number, number, number], [number, number, number, number], [number, number, number, number]];
} }
export = sharp; export = sharp;

View File

@ -3,30 +3,46 @@
'use strict'; 'use strict';
const color = require('color');
const is = require('./is'); const is = require('./is');
const sharp = require('./sharp'); const sharp = require('./sharp');
/** /**
* Justication alignment * Justification alignment
* @member * @member
* @private * @private
*/ */
const align = { const align = {
left: 'low', left: 'low',
top: 'low',
low: 'low',
center: 'centre', center: 'centre',
centre: 'centre', centre: 'centre',
right: 'high' right: 'high',
bottom: 'high',
high: 'high'
}; };
const inputStreamParameters = [
// Limits and error handling
'failOn', 'limitInputPixels', 'unlimited',
// Format-generic
'animated', 'autoOrient', 'density', 'ignoreIcc', 'page', 'pages', 'sequentialRead',
// Format-specific
'jp2', 'openSlide', 'pdf', 'raw', 'svg', 'tiff',
// Deprecated
'failOnError', 'openSlideLevel', 'pdfBackground', 'tiffSubifd'
];
/** /**
* Extract input options, if any, from an object. * Extract input options, if any, from an object.
* @private * @private
*/ */
function _inputOptionsFromObject (obj) { function _inputOptionsFromObject (obj) {
const { raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd } = obj; const params = inputStreamParameters
return [raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd].some(is.defined) .filter(p => is.defined(obj[p]))
? { raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd } .map(p => ([p, obj[p]]));
return params.length
? Object.fromEntries(params)
: undefined; : undefined;
} }
@ -36,6 +52,7 @@ function _inputOptionsFromObject (obj) {
*/ */
function _createInputDescriptor (input, inputOptions, containerOptions) { function _createInputDescriptor (input, inputOptions, containerOptions) {
const inputDescriptor = { const inputDescriptor = {
autoOrient: false,
failOn: 'warning', failOn: 'warning',
limitInputPixels: Math.pow(0x3FFF, 2), limitInputPixels: Math.pow(0x3FFF, 2),
ignoreIcc: false, ignoreIcc: false,
@ -71,6 +88,18 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
} else if (!is.defined(input) && !is.defined(inputOptions) && is.object(containerOptions) && containerOptions.allowStream) { } else if (!is.defined(input) && !is.defined(inputOptions) && is.object(containerOptions) && containerOptions.allowStream) {
// Stream without options // Stream without options
inputDescriptor.buffer = []; inputDescriptor.buffer = [];
} else if (Array.isArray(input)) {
if (input.length > 1) {
// Join images together
if (!this.options.joining) {
this.options.joining = true;
this.options.join = input.map(i => this._createInputDescriptor(i));
} else {
throw new Error('Recursive join is unsupported');
}
} else {
throw new Error('Expected at least two images to join');
}
} else { } else {
throw new Error(`Unsupported input '${input}' of type ${typeof input}${ throw new Error(`Unsupported input '${input}' of type ${typeof input}${
is.defined(inputOptions) ? ` when also providing options of type ${typeof inputOptions}` : '' is.defined(inputOptions) ? ` when also providing options of type ${typeof inputOptions}` : ''
@ -93,6 +122,14 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
throw is.invalidParameterError('failOn', 'one of: none, truncated, error, warning', inputOptions.failOn); throw is.invalidParameterError('failOn', 'one of: none, truncated, error, warning', inputOptions.failOn);
} }
} }
// autoOrient
if (is.defined(inputOptions.autoOrient)) {
if (is.bool(inputOptions.autoOrient)) {
inputDescriptor.autoOrient = inputOptions.autoOrient;
} else {
throw is.invalidParameterError('autoOrient', 'boolean', inputOptions.autoOrient);
}
}
// Density // Density
if (is.defined(inputOptions.density)) { if (is.defined(inputOptions.density)) {
if (is.inRange(inputOptions.density, 1, 100000)) { if (is.inRange(inputOptions.density, 1, 100000)) {
@ -148,8 +185,6 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
inputDescriptor.rawWidth = inputOptions.raw.width; inputDescriptor.rawWidth = inputOptions.raw.width;
inputDescriptor.rawHeight = inputOptions.raw.height; inputDescriptor.rawHeight = inputOptions.raw.height;
inputDescriptor.rawChannels = inputOptions.raw.channels; inputDescriptor.rawChannels = inputOptions.raw.channels;
inputDescriptor.rawPremultiplied = !!inputOptions.raw.premultiplied;
switch (input.constructor) { switch (input.constructor) {
case Uint8Array: case Uint8Array:
case Uint8ClampedArray: case Uint8ClampedArray:
@ -183,6 +218,25 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
} else { } else {
throw new Error('Expected width, height and channels for raw pixel input'); throw new Error('Expected width, height and channels for raw pixel input');
} }
inputDescriptor.rawPremultiplied = false;
if (is.defined(inputOptions.raw.premultiplied)) {
if (is.bool(inputOptions.raw.premultiplied)) {
inputDescriptor.rawPremultiplied = inputOptions.raw.premultiplied;
} else {
throw is.invalidParameterError('raw.premultiplied', 'boolean', inputOptions.raw.premultiplied);
}
}
inputDescriptor.rawPageHeight = 0;
if (is.defined(inputOptions.raw.pageHeight)) {
if (is.integer(inputOptions.raw.pageHeight) && inputOptions.raw.pageHeight > 0 && inputOptions.raw.pageHeight <= inputOptions.raw.height) {
if (inputOptions.raw.height % inputOptions.raw.pageHeight !== 0) {
throw new Error(`Expected raw.height ${inputOptions.raw.height} to be a multiple of raw.pageHeight ${inputOptions.raw.pageHeight}`);
}
inputDescriptor.rawPageHeight = inputOptions.raw.pageHeight;
} else {
throw is.invalidParameterError('raw.pageHeight', 'positive integer', inputOptions.raw.pageHeight);
}
}
} }
// Multi-page input (GIF, TIFF, PDF) // Multi-page input (GIF, TIFF, PDF)
if (is.defined(inputOptions.animated)) { if (is.defined(inputOptions.animated)) {
@ -206,22 +260,68 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
throw is.invalidParameterError('page', 'integer between 0 and 100000', inputOptions.page); throw is.invalidParameterError('page', 'integer between 0 and 100000', inputOptions.page);
} }
} }
// Multi-level input (OpenSlide) // OpenSlide specific options
if (is.defined(inputOptions.level)) { if (is.object(inputOptions.openSlide) && is.defined(inputOptions.openSlide.level)) {
if (is.integer(inputOptions.openSlide.level) && is.inRange(inputOptions.openSlide.level, 0, 256)) {
inputDescriptor.openSlideLevel = inputOptions.openSlide.level;
} else {
throw is.invalidParameterError('openSlide.level', 'integer between 0 and 256', inputOptions.openSlide.level);
}
} else if (is.defined(inputOptions.level)) {
// Deprecated
if (is.integer(inputOptions.level) && is.inRange(inputOptions.level, 0, 256)) { if (is.integer(inputOptions.level) && is.inRange(inputOptions.level, 0, 256)) {
inputDescriptor.level = inputOptions.level; inputDescriptor.openSlideLevel = inputOptions.level;
} else { } else {
throw is.invalidParameterError('level', 'integer between 0 and 256', inputOptions.level); throw is.invalidParameterError('level', 'integer between 0 and 256', inputOptions.level);
} }
} }
// Sub Image File Directory (TIFF) // TIFF specific options
if (is.defined(inputOptions.subifd)) { if (is.object(inputOptions.tiff) && is.defined(inputOptions.tiff.subifd)) {
if (is.integer(inputOptions.tiff.subifd) && is.inRange(inputOptions.tiff.subifd, -1, 100000)) {
inputDescriptor.tiffSubifd = inputOptions.tiff.subifd;
} else {
throw is.invalidParameterError('tiff.subifd', 'integer between -1 and 100000', inputOptions.tiff.subifd);
}
} else if (is.defined(inputOptions.subifd)) {
// Deprecated
if (is.integer(inputOptions.subifd) && is.inRange(inputOptions.subifd, -1, 100000)) { if (is.integer(inputOptions.subifd) && is.inRange(inputOptions.subifd, -1, 100000)) {
inputDescriptor.subifd = inputOptions.subifd; inputDescriptor.tiffSubifd = inputOptions.subifd;
} else { } else {
throw is.invalidParameterError('subifd', 'integer between -1 and 100000', inputOptions.subifd); throw is.invalidParameterError('subifd', 'integer between -1 and 100000', inputOptions.subifd);
} }
} }
// SVG specific options
if (is.object(inputOptions.svg)) {
if (is.defined(inputOptions.svg.stylesheet)) {
if (is.string(inputOptions.svg.stylesheet)) {
inputDescriptor.svgStylesheet = inputOptions.svg.stylesheet;
} else {
throw is.invalidParameterError('svg.stylesheet', 'string', inputOptions.svg.stylesheet);
}
}
if (is.defined(inputOptions.svg.highBitdepth)) {
if (is.bool(inputOptions.svg.highBitdepth)) {
inputDescriptor.svgHighBitdepth = inputOptions.svg.highBitdepth;
} else {
throw is.invalidParameterError('svg.highBitdepth', 'boolean', inputOptions.svg.highBitdepth);
}
}
}
// PDF specific options
if (is.object(inputOptions.pdf) && is.defined(inputOptions.pdf.background)) {
inputDescriptor.pdfBackground = this._getBackgroundColourOption(inputOptions.pdf.background);
} else if (is.defined(inputOptions.pdfBackground)) {
// Deprecated
inputDescriptor.pdfBackground = this._getBackgroundColourOption(inputOptions.pdfBackground);
}
// JPEG 2000 specific options
if (is.object(inputOptions.jp2) && is.defined(inputOptions.jp2.oneshot)) {
if (is.bool(inputOptions.jp2.oneshot)) {
inputDescriptor.jp2Oneshot = inputOptions.jp2.oneshot;
} else {
throw is.invalidParameterError('jp2.oneshot', 'boolean', inputOptions.jp2.oneshot);
}
}
// Create new image // Create new image
if (is.defined(inputOptions.create)) { if (is.defined(inputOptions.create)) {
if ( if (
@ -233,39 +333,50 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
inputDescriptor.createWidth = inputOptions.create.width; inputDescriptor.createWidth = inputOptions.create.width;
inputDescriptor.createHeight = inputOptions.create.height; inputDescriptor.createHeight = inputOptions.create.height;
inputDescriptor.createChannels = inputOptions.create.channels; inputDescriptor.createChannels = inputOptions.create.channels;
inputDescriptor.createPageHeight = 0;
if (is.defined(inputOptions.create.pageHeight)) {
if (is.integer(inputOptions.create.pageHeight) && inputOptions.create.pageHeight > 0 && inputOptions.create.pageHeight <= inputOptions.create.height) {
if (inputOptions.create.height % inputOptions.create.pageHeight !== 0) {
throw new Error(`Expected create.height ${inputOptions.create.height} to be a multiple of create.pageHeight ${inputOptions.create.pageHeight}`);
}
inputDescriptor.createPageHeight = inputOptions.create.pageHeight;
} else {
throw is.invalidParameterError('create.pageHeight', 'positive integer', inputOptions.create.pageHeight);
}
}
// Noise // Noise
if (is.defined(inputOptions.create.noise)) { if (is.defined(inputOptions.create.noise)) {
if (!is.object(inputOptions.create.noise)) { if (!is.object(inputOptions.create.noise)) {
throw new Error('Expected noise to be an object'); throw new Error('Expected noise to be an object');
} }
if (!is.inArray(inputOptions.create.noise.type, ['gaussian'])) { if (inputOptions.create.noise.type !== 'gaussian') {
throw new Error('Only gaussian noise is supported at the moment'); throw new Error('Only gaussian noise is supported at the moment');
} }
inputDescriptor.createNoiseType = inputOptions.create.noise.type;
if (!is.inRange(inputOptions.create.channels, 1, 4)) { if (!is.inRange(inputOptions.create.channels, 1, 4)) {
throw is.invalidParameterError('create.channels', 'number between 1 and 4', inputOptions.create.channels); throw is.invalidParameterError('create.channels', 'number between 1 and 4', inputOptions.create.channels);
} }
inputDescriptor.createNoiseType = inputOptions.create.noise.type; inputDescriptor.createNoiseMean = 128;
if (is.defined(inputOptions.create.noise.mean)) {
if (is.number(inputOptions.create.noise.mean) && is.inRange(inputOptions.create.noise.mean, 0, 10000)) { if (is.number(inputOptions.create.noise.mean) && is.inRange(inputOptions.create.noise.mean, 0, 10000)) {
inputDescriptor.createNoiseMean = inputOptions.create.noise.mean; inputDescriptor.createNoiseMean = inputOptions.create.noise.mean;
} else { } else {
throw is.invalidParameterError('create.noise.mean', 'number between 0 and 10000', inputOptions.create.noise.mean); throw is.invalidParameterError('create.noise.mean', 'number between 0 and 10000', inputOptions.create.noise.mean);
} }
}
inputDescriptor.createNoiseSigma = 30;
if (is.defined(inputOptions.create.noise.sigma)) {
if (is.number(inputOptions.create.noise.sigma) && is.inRange(inputOptions.create.noise.sigma, 0, 10000)) { if (is.number(inputOptions.create.noise.sigma) && is.inRange(inputOptions.create.noise.sigma, 0, 10000)) {
inputDescriptor.createNoiseSigma = inputOptions.create.noise.sigma; inputDescriptor.createNoiseSigma = inputOptions.create.noise.sigma;
} else { } else {
throw is.invalidParameterError('create.noise.sigma', 'number between 0 and 10000', inputOptions.create.noise.sigma); throw is.invalidParameterError('create.noise.sigma', 'number between 0 and 10000', inputOptions.create.noise.sigma);
} }
}
} else if (is.defined(inputOptions.create.background)) { } else if (is.defined(inputOptions.create.background)) {
if (!is.inRange(inputOptions.create.channels, 3, 4)) { if (!is.inRange(inputOptions.create.channels, 3, 4)) {
throw is.invalidParameterError('create.channels', 'number between 3 and 4', inputOptions.create.channels); throw is.invalidParameterError('create.channels', 'number between 3 and 4', inputOptions.create.channels);
} }
const background = color(inputOptions.create.background); inputDescriptor.createBackground = this._getBackgroundColourOption(inputOptions.create.background);
inputDescriptor.createBackground = [
background.red(),
background.green(),
background.blue(),
Math.round(background.alpha() * 255)
];
} else { } else {
throw new Error('Expected valid noise or background to create a new input image'); throw new Error('Expected valid noise or background to create a new input image');
} }
@ -356,6 +467,51 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
throw new Error('Expected a valid string to create an image with text.'); throw new Error('Expected a valid string to create an image with text.');
} }
} }
// Join images together
if (is.defined(inputOptions.join)) {
if (is.defined(this.options.join)) {
if (is.defined(inputOptions.join.animated)) {
if (is.bool(inputOptions.join.animated)) {
inputDescriptor.joinAnimated = inputOptions.join.animated;
} else {
throw is.invalidParameterError('join.animated', 'boolean', inputOptions.join.animated);
}
}
if (is.defined(inputOptions.join.across)) {
if (is.integer(inputOptions.join.across) && is.inRange(inputOptions.join.across, 1, 1000000)) {
inputDescriptor.joinAcross = inputOptions.join.across;
} else {
throw is.invalidParameterError('join.across', 'integer between 1 and 100000', inputOptions.join.across);
}
}
if (is.defined(inputOptions.join.shim)) {
if (is.integer(inputOptions.join.shim) && is.inRange(inputOptions.join.shim, 0, 1000000)) {
inputDescriptor.joinShim = inputOptions.join.shim;
} else {
throw is.invalidParameterError('join.shim', 'integer between 0 and 100000', inputOptions.join.shim);
}
}
if (is.defined(inputOptions.join.background)) {
inputDescriptor.joinBackground = this._getBackgroundColourOption(inputOptions.join.background);
}
if (is.defined(inputOptions.join.halign)) {
if (is.string(inputOptions.join.halign) && is.string(this.constructor.align[inputOptions.join.halign])) {
inputDescriptor.joinHalign = this.constructor.align[inputOptions.join.halign];
} else {
throw is.invalidParameterError('join.halign', 'valid alignment', inputOptions.join.halign);
}
}
if (is.defined(inputOptions.join.valign)) {
if (is.string(inputOptions.join.valign) && is.string(this.constructor.align[inputOptions.join.valign])) {
inputDescriptor.joinValign = this.constructor.align[inputOptions.join.valign];
} else {
throw is.invalidParameterError('join.valign', 'valid alignment', inputOptions.join.valign);
}
}
} else {
throw new Error('Expected input to be an array of images to join');
}
}
} else if (is.defined(inputOptions)) { } else if (is.defined(inputOptions)) {
throw new Error('Invalid input options ' + inputOptions); throw new Error('Invalid input options ' + inputOptions);
} }
@ -430,15 +586,16 @@ function _isStreamInput () {
* - `density`: Number of pixels per inch (DPI), if present * - `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 * - `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 * - `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan
* - `isPalette`: Boolean indicating whether the image is palette-based (GIF, PNG).
* - `bitsPerSample`: Number of bits per sample for each channel (GIF, PNG, HEIF).
* - `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP * - `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. * - `pageHeight`: Number of pixels high each page in a multi-page image will be.
* - `paletteBitDepth`: Bit depth of palette-based image (GIF, PNG).
* - `loop`: Number of times to loop an animated image, zero refers to a continuous loop. * - `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. * - `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 * - `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 * - `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 * - `subifds`: Number of Sub Image File Directories in an OME-TIFF image
* - `background`: Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value * - `background`: Default background colour, if present, for PNG (bKGD) and GIF images
* - `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC) * - `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC)
* - `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present * - `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present
* - `hasProfile`: Boolean indicating the presence of an embedded ICC profile * - `hasProfile`: Boolean indicating the presence of an embedded ICC profile
@ -448,8 +605,10 @@ function _isStreamInput () {
* - `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present * - `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present
* - `iptc`: Buffer containing raw IPTC data, if present * - `iptc`: Buffer containing raw IPTC data, if present
* - `xmp`: Buffer containing raw XMP data, if present * - `xmp`: Buffer containing raw XMP data, if present
* - `xmpAsString`: String containing XMP data, if valid UTF-8.
* - `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present * - `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present
* - `formatMagick`: String containing format for images loaded via *magick * - `formatMagick`: String containing format for images loaded via *magick
* - `comments`: Array of keyword/text pairs representing PNG text blocks, if present.
* *
* @example * @example
* const metadata = await sharp(input).metadata(); * const metadata = await sharp(input).metadata();
@ -469,15 +628,9 @@ function _isStreamInput () {
* }); * });
* *
* @example * @example
* // Based on EXIF rotation metadata, get the right-side-up width and height: * // Get dimensions taking EXIF Orientation into account.
* * const { autoOrient } = await sharp(input).metadata();
* const size = getNormalSize(await sharp(input).metadata()); * const { width, height } = autoOrient;
*
* function getNormalSize({ width, height, orientation }) {
* return (orientation || 0) >= 5
* ? { width: height, height: width }
* : { width, height };
* }
* *
* @param {Function} [callback] - called with the arguments `(err, metadata)` * @param {Function} [callback] - called with the arguments `(err, metadata)`
* @returns {Promise<Object>|Sharp} * @returns {Promise<Object>|Sharp}
@ -638,6 +791,7 @@ function stats (callback) {
/** /**
* Decorate the Sharp prototype with input-related functions. * Decorate the Sharp prototype with input-related functions.
* @module Sharp
* @private * @private
*/ */
module.exports = function (Sharp) { module.exports = function (Sharp) {

View File

@ -10,17 +10,17 @@ const semverGreaterThanOrEqualTo = require('semver/functions/gte');
const semverSatisfies = require('semver/functions/satisfies'); const semverSatisfies = require('semver/functions/satisfies');
const detectLibc = require('detect-libc'); const detectLibc = require('detect-libc');
const { engines, optionalDependencies } = require('../package.json'); const { config, engines, optionalDependencies } = require('../package.json');
const minimumLibvipsVersionLabelled = process.env.npm_package_config_libvips || /* istanbul ignore next */ const minimumLibvipsVersionLabelled = process.env.npm_package_config_libvips || /* istanbul ignore next */
engines.libvips; config.libvips;
const minimumLibvipsVersion = semverCoerce(minimumLibvipsVersionLabelled).version; const minimumLibvipsVersion = semverCoerce(minimumLibvipsVersionLabelled).version;
const prebuiltPlatforms = [ const prebuiltPlatforms = [
'darwin-arm64', 'darwin-x64', 'darwin-arm64', 'darwin-x64',
'linux-arm', 'linux-arm64', 'linux-s390x', 'linux-x64', 'linux-arm', 'linux-arm64', 'linux-ppc64', 'linux-s390x', 'linux-x64',
'linuxmusl-arm64', 'linuxmusl-x64', 'linuxmusl-arm64', 'linuxmusl-x64',
'win32-ia32', 'win32-x64' 'win32-arm64', 'win32-ia32', 'win32-x64'
]; ];
const spawnSyncOptions = { const spawnSyncOptions = {
@ -113,7 +113,9 @@ const sha512 = (s) => createHash('sha512').update(s).digest('hex');
const yarnLocator = () => { const yarnLocator = () => {
try { try {
const identHash = sha512(`imgsharp-libvips-${buildPlatformArch()}`); const identHash = sha512(`imgsharp-libvips-${buildPlatformArch()}`);
const npmVersion = semverCoerce(optionalDependencies[`@img/sharp-libvips-${buildPlatformArch()}`]).version; const npmVersion = semverCoerce(optionalDependencies[`@img/sharp-libvips-${buildPlatformArch()}`], {
includePrerelease: true
}).version;
return sha512(`${identHash}npm:${npmVersion}`).slice(0, 10); return sha512(`${identHash}npm:${npmVersion}`).slice(0, 10);
} catch {} } catch {}
return ''; return '';
@ -162,21 +164,23 @@ const pkgConfigPath = () => {
} }
}; };
const skipSearch = (status, reason) => { const skipSearch = (status, reason, logger) => {
log(`Detected ${reason}, skipping search for globally-installed libvips`); if (logger) {
logger(`Detected ${reason}, skipping search for globally-installed libvips`);
}
return status; return status;
}; };
const useGlobalLibvips = () => { const useGlobalLibvips = (logger) => {
if (Boolean(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS) === true) { if (Boolean(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS) === true) {
return skipSearch(false, 'SHARP_IGNORE_GLOBAL_LIBVIPS'); return skipSearch(false, 'SHARP_IGNORE_GLOBAL_LIBVIPS', logger);
} }
if (Boolean(process.env.SHARP_FORCE_GLOBAL_LIBVIPS) === true) { if (Boolean(process.env.SHARP_FORCE_GLOBAL_LIBVIPS) === true) {
return skipSearch(true, 'SHARP_FORCE_GLOBAL_LIBVIPS'); return skipSearch(true, 'SHARP_FORCE_GLOBAL_LIBVIPS', logger);
} }
/* istanbul ignore next */ /* istanbul ignore next */
if (isRosetta()) { if (isRosetta()) {
return skipSearch(false, 'Rosetta'); return skipSearch(false, 'Rosetta', logger);
} }
const globalVipsVersion = globalLibvipsVersion(); const globalVipsVersion = globalLibvipsVersion();
return !!globalVipsVersion && /* istanbul ignore next */ return !!globalVipsVersion && /* istanbul ignore next */

View File

@ -3,26 +3,33 @@
'use strict'; 'use strict';
const color = require('color');
const is = require('./is'); const is = require('./is');
/** /**
* Rotate the output image by either an explicit angle * How accurate an operation should be.
* or auto-orient based on the EXIF `Orientation` tag. * @member
* @private
*/
const vipsPrecision = {
integer: 'integer',
float: 'float',
approximate: 'approximate'
};
/**
* Rotate the output image.
* *
* If an angle is provided, it is converted to a valid positive degree rotation. * The provided angle is converted to a valid positive degree rotation.
* For example, `-450` will produce a 270 degree rotation. * For example, `-450` will produce a 270 degree rotation.
* *
* When rotating by an angle other than a multiple of 90, * When rotating by an angle other than a multiple of 90,
* the background colour can be provided with the `background` option. * the background colour can be provided with the `background` option.
* *
* If no angle is provided, it is determined from the EXIF data. * For backwards compatibility, if no angle is provided, `.autoOrient()` will be called.
* Mirroring is supported and may infer the use of a flip operation.
* *
* The use of `rotate` without an angle will remove the EXIF `Orientation` tag, if any. * Only one rotation can occur per pipeline (aside from an initial call without
* * arguments to orient via EXIF data). Previous calls to `rotate` in the same
* Only one rotation can occur per pipeline. * pipeline will be ignored.
* Previous calls to `rotate` in the same pipeline will be ignored.
* *
* Multi-page images can only be rotated by 180 degrees. * Multi-page images can only be rotated by 180 degrees.
* *
@ -30,17 +37,6 @@ const is = require('./is');
* for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`. * for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.
* *
* @example * @example
* const pipeline = sharp()
* .rotate()
* .resize(null, 200)
* .toBuffer(function (err, outputBuffer, info) {
* // outputBuffer contains 200px high JPEG image data,
* // auto-rotated using EXIF Orientation tag
* // info.width and info.height contain the dimensions of the resized image
* });
* readableStream.pipe(pipeline);
*
* @example
* const rotateThenResize = await sharp(input) * const rotateThenResize = await sharp(input)
* .rotate(90) * .rotate(90)
* .resize({ width: 16, height: 8, fit: 'fill' }) * .resize({ width: 16, height: 8, fit: 'fill' })
@ -57,23 +53,20 @@ const is = require('./is');
* @throws {Error} Invalid parameters * @throws {Error} Invalid parameters
*/ */
function rotate (angle, options) { function rotate (angle, options) {
if (this.options.useExifOrientation || this.options.angle || this.options.rotationAngle) {
this.options.debuglog('ignoring previous rotate options');
}
if (!is.defined(angle)) { if (!is.defined(angle)) {
this.options.useExifOrientation = true; return this.autoOrient();
} else if (is.integer(angle) && !(angle % 90)) { }
if (this.options.angle || this.options.rotationAngle) {
this.options.debuglog('ignoring previous rotate options');
this.options.angle = 0;
this.options.rotationAngle = 0;
}
if (is.integer(angle) && !(angle % 90)) {
this.options.angle = angle; this.options.angle = angle;
} else if (is.number(angle)) { } else if (is.number(angle)) {
this.options.rotationAngle = angle; this.options.rotationAngle = angle;
if (is.object(options) && options.background) { if (is.object(options) && options.background) {
const backgroundColour = color(options.background); this._setBackgroundColourOption('rotationBackground', options.background);
this.options.rotationBackground = [
backgroundColour.red(),
backgroundColour.green(),
backgroundColour.blue(),
Math.round(backgroundColour.alpha() * 255)
];
} }
} else { } else {
throw is.invalidParameterError('angle', 'numeric', angle); throw is.invalidParameterError('angle', 'numeric', angle);
@ -81,6 +74,34 @@ function rotate (angle, options) {
return this; return this;
} }
/**
* Auto-orient based on the EXIF `Orientation` tag, then remove the tag.
* Mirroring is supported and may infer the use of a flip operation.
*
* Previous or subsequent use of `rotate(angle)` and either `flip()` or `flop()`
* will logically occur after auto-orientation, regardless of call order.
*
* @example
* const output = await sharp(input).autoOrient().toBuffer();
*
* @example
* const pipeline = sharp()
* .autoOrient()
* .resize(null, 200)
* .toBuffer(function (err, outputBuffer, info) {
* // outputBuffer contains 200px high JPEG image data,
* // auto-oriented using EXIF Orientation tag
* // info.width and info.height contain the dimensions of the resized image
* });
* readableStream.pipe(pipeline);
*
* @returns {Sharp}
*/
function autoOrient () {
this.options.input.autoOrient = true;
return this;
}
/** /**
* Mirror the image vertically (up-down) about the x-axis. * Mirror the image vertically (up-down) about the x-axis.
* This always occurs before rotation, if any. * This always occurs before rotation, if any.
@ -117,7 +138,7 @@ function flop (flop) {
* Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any. * Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.
* *
* You must provide an array of length 4 or a 2x2 affine transformation matrix. * You must provide an array of length 4 or a 2x2 affine transformation matrix.
* By default, new pixels are filled with a black background. You can provide a background color with the `background` option. * By default, new pixels are filled with a black background. You can provide a background colour with the `background` option.
* A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`. * A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`.
* *
* In the case of a 2x2 matrix, the transform is: * In the case of a 2x2 matrix, the transform is:
@ -367,23 +388,97 @@ function median (size) {
* .blur(5) * .blur(5)
* .toBuffer(); * .toBuffer();
* *
* @param {number} [sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. * @param {Object|number|Boolean} [options]
* @param {number} [options.sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
* @param {string} [options.precision='integer'] How accurate the operation should be, one of: integer, float, approximate.
* @param {number} [options.minAmplitude=0.2] A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask.
* @returns {Sharp} * @returns {Sharp}
* @throws {Error} Invalid parameters * @throws {Error} Invalid parameters
*/ */
function blur (sigma) { function blur (options) {
if (!is.defined(sigma)) { let sigma;
if (is.number(options)) {
sigma = options;
} else if (is.plainObject(options)) {
if (!is.number(options.sigma)) {
throw is.invalidParameterError('options.sigma', 'number between 0.3 and 1000', sigma);
}
sigma = options.sigma;
if ('precision' in options) {
if (is.string(vipsPrecision[options.precision])) {
this.options.precision = vipsPrecision[options.precision];
} else {
throw is.invalidParameterError('precision', 'one of: integer, float, approximate', options.precision);
}
}
if ('minAmplitude' in options) {
if (is.number(options.minAmplitude) && is.inRange(options.minAmplitude, 0.001, 1)) {
this.options.minAmpl = options.minAmplitude;
} else {
throw is.invalidParameterError('minAmplitude', 'number between 0.001 and 1', options.minAmplitude);
}
}
}
if (!is.defined(options)) {
// No arguments: default to mild blur // No arguments: default to mild blur
this.options.blurSigma = -1; this.options.blurSigma = -1;
} else if (is.bool(sigma)) { } else if (is.bool(options)) {
// Boolean argument: apply mild blur? // Boolean argument: apply mild blur?
this.options.blurSigma = sigma ? -1 : 0; this.options.blurSigma = options ? -1 : 0;
} else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) { } else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) {
// Numeric argument: specific sigma // Numeric argument: specific sigma
this.options.blurSigma = sigma; this.options.blurSigma = sigma;
} else { } else {
throw is.invalidParameterError('sigma', 'number between 0.3 and 1000', sigma); throw is.invalidParameterError('sigma', 'number between 0.3 and 1000', sigma);
} }
return this;
}
/**
* Expand foreground objects using the dilate morphological operator.
*
* @example
* const output = await sharp(input)
* .dilate()
* .toBuffer();
*
* @param {Number} [width=1] dilation width in pixels.
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
function dilate (width) {
if (!is.defined(width)) {
this.options.dilateWidth = 1;
} else if (is.integer(width) && width > 0) {
this.options.dilateWidth = width;
} else {
throw is.invalidParameterError('dilate', 'positive integer', dilate);
}
return this;
}
/**
* Shrink foreground objects using the erode morphological operator.
*
* @example
* const output = await sharp(input)
* .erode()
* .toBuffer();
*
* @param {Number} [width=1] erosion width in pixels.
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
function erode (width) {
if (!is.defined(width)) {
this.options.erodeWidth = 1;
} else if (is.integer(width) && width > 0) {
this.options.erodeWidth = width;
} else {
throw is.invalidParameterError('erode', 'positive integer', erode);
}
return this; return this;
} }
@ -787,24 +882,22 @@ function linear (a, b) {
* // With this example input, a sepia filter has been applied * // With this example input, a sepia filter has been applied
* }); * });
* *
* @param {Array<Array<number>>} inputMatrix - 3x3 Recombination matrix * @param {Array<Array<number>>} inputMatrix - 3x3 or 4x4 Recombination matrix
* @returns {Sharp} * @returns {Sharp}
* @throws {Error} Invalid parameters * @throws {Error} Invalid parameters
*/ */
function recomb (inputMatrix) { function recomb (inputMatrix) {
if (!Array.isArray(inputMatrix) || inputMatrix.length !== 3 || if (!Array.isArray(inputMatrix)) {
inputMatrix[0].length !== 3 || throw is.invalidParameterError('inputMatrix', 'array', inputMatrix);
inputMatrix[1].length !== 3 ||
inputMatrix[2].length !== 3
) {
// must pass in a kernel
throw new Error('Invalid recombination matrix');
} }
this.options.recombMatrix = [ if (inputMatrix.length !== 3 && inputMatrix.length !== 4) {
inputMatrix[0][0], inputMatrix[0][1], inputMatrix[0][2], throw is.invalidParameterError('inputMatrix', '3x3 or 4x4 array', inputMatrix.length);
inputMatrix[1][0], inputMatrix[1][1], inputMatrix[1][2], }
inputMatrix[2][0], inputMatrix[2][1], inputMatrix[2][2] const recombMatrix = inputMatrix.flat().map(Number);
].map(Number); if (recombMatrix.length !== 9 && recombMatrix.length !== 16) {
throw is.invalidParameterError('inputMatrix', 'cardinality of 9 or 16', recombMatrix.length);
}
this.options.recombMatrix = recombMatrix;
return this; return this;
} }
@ -893,15 +986,19 @@ function modulate (options) {
/** /**
* Decorate the Sharp prototype with operation-related functions. * Decorate the Sharp prototype with operation-related functions.
* @module Sharp
* @private * @private
*/ */
module.exports = function (Sharp) { module.exports = function (Sharp) {
Object.assign(Sharp.prototype, { Object.assign(Sharp.prototype, {
autoOrient,
rotate, rotate,
flip, flip,
flop, flop,
affine, affine,
sharpen, sharpen,
erode,
dilate,
median, median,
blur, blur,
flatten, flatten,

View File

@ -65,6 +65,7 @@ const bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math
* `channels` and `premultiplied` (indicating if premultiplication was used). * `channels` and `premultiplied` (indicating if premultiplication was used).
* When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
* When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region. * When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region.
* Animated output will also contain `pageHeight` and `pages`.
* May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.
* @returns {Promise<Object>} - when no callback is provided * @returns {Promise<Object>} - when no callback is provided
* @throws {Error} Invalid parameters * @throws {Error} Invalid parameters
@ -109,6 +110,7 @@ function toFile (fileOut, callback) {
* - `info` contains the output image `format`, `size` (bytes), `width`, `height`, * - `info` contains the output image `format`, `size` (bytes), `width`, `height`,
* `channels` and `premultiplied` (indicating if premultiplication was used). * `channels` and `premultiplied` (indicating if premultiplication was used).
* When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
* Animated output will also contain `pageHeight` and `pages`.
* May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.
* *
* A `Promise` is returned when `callback` is not provided. * A `Promise` is returned when `callback` is not provided.
@ -310,6 +312,59 @@ function withIccProfile (icc, options) {
return this; return this;
} }
/**
* Keep XMP metadata from the input image in the output image.
*
* @since 0.34.3
*
* @example
* const outputWithXmp = await sharp(inputWithXmp)
* .keepXmp()
* .toBuffer();
*
* @returns {Sharp}
*/
function keepXmp () {
this.options.keepMetadata |= 0b00010;
return this;
}
/**
* Set XMP metadata in the output image.
*
* Supported by PNG, JPEG, WebP, and TIFF output.
*
* @since 0.34.3
*
* @example
* const xmpString = `
* <?xml version="1.0"?>
* <x:xmpmeta xmlns:x="adobe:ns:meta/">
* <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
* <rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">
* <dc:creator><rdf:Seq><rdf:li>John Doe</rdf:li></rdf:Seq></dc:creator>
* </rdf:Description>
* </rdf:RDF>
* </x:xmpmeta>`;
*
* const data = await sharp(input)
* .withXmp(xmpString)
* .toBuffer();
*
* @param {string} xmp String containing XMP metadata to be embedded in the output image.
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
function withXmp (xmp) {
if (is.string(xmp) && xmp.length > 0) {
this.options.withXmp = xmp;
this.options.keepMetadata |= 0b00010;
} else {
throw is.invalidParameterError('xmp', 'non-empty string', xmp);
}
return this;
}
/** /**
* Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image. * Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image.
* *
@ -621,6 +676,7 @@ function png (options) {
* @param {boolean} [options.lossless=false] - use lossless compression mode * @param {boolean} [options.lossless=false] - use lossless compression mode
* @param {boolean} [options.nearLossless=false] - use near_lossless compression mode * @param {boolean} [options.nearLossless=false] - use near_lossless compression mode
* @param {boolean} [options.smartSubsample=false] - use high quality chroma subsampling * @param {boolean} [options.smartSubsample=false] - use high quality chroma subsampling
* @param {boolean} [options.smartDeblock=false] - auto-adjust the deblocking filter, can improve low contrast edges (slow)
* @param {string} [options.preset='default'] - named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text * @param {string} [options.preset='default'] - named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text
* @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 6 (slowest) * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 6 (slowest)
* @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation
@ -656,6 +712,9 @@ function webp (options) {
if (is.defined(options.smartSubsample)) { if (is.defined(options.smartSubsample)) {
this._setBooleanOption('webpSmartSubsample', options.smartSubsample); this._setBooleanOption('webpSmartSubsample', options.smartSubsample);
} }
if (is.defined(options.smartDeblock)) {
this._setBooleanOption('webpSmartDeblock', options.smartDeblock);
}
if (is.defined(options.preset)) { if (is.defined(options.preset)) {
if (is.string(options.preset) && is.inArray(options.preset, ['default', 'photo', 'picture', 'drawing', 'icon', 'text'])) { if (is.string(options.preset) && is.inArray(options.preset, ['default', 'photo', 'picture', 'drawing', 'icon', 'text'])) {
this.options.webpPreset = options.preset; this.options.webpPreset = options.preset;
@ -723,6 +782,7 @@ function webp (options) {
* @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) * @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most)
* @param {number} [options.interFrameMaxError=0] - maximum inter-frame error for transparency, between 0 (lossless) and 32 * @param {number} [options.interFrameMaxError=0] - maximum inter-frame error for transparency, between 0 (lossless) and 32
* @param {number} [options.interPaletteMaxError=3] - maximum inter-palette error for palette reuse, between 0 and 256 * @param {number} [options.interPaletteMaxError=3] - maximum inter-palette error for palette reuse, between 0 and 256
* @param {boolean} [options.keepDuplicateFrames=false] - keep duplicate frames in the output instead of combining them
* @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation
* @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds) * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)
* @param {boolean} [options.force=true] - force GIF output, otherwise attempt to use input format * @param {boolean} [options.force=true] - force GIF output, otherwise attempt to use input format
@ -773,6 +833,13 @@ function gif (options) {
throw is.invalidParameterError('interPaletteMaxError', 'number between 0.0 and 256.0', options.interPaletteMaxError); throw is.invalidParameterError('interPaletteMaxError', 'number between 0.0 and 256.0', options.interPaletteMaxError);
} }
} }
if (is.defined(options.keepDuplicateFrames)) {
if (is.bool(options.keepDuplicateFrames)) {
this._setBooleanOption('gifKeepDuplicateFrames', options.keepDuplicateFrames);
} else {
throw is.invalidParameterError('keepDuplicateFrames', 'boolean', options.keepDuplicateFrames);
}
}
} }
trySetAnimationOptions(options, this.options); trySetAnimationOptions(options, this.options);
return this._updateFormatOut('gif', options); return this._updateFormatOut('gif', options);
@ -1013,6 +1080,9 @@ function tiff (options) {
* AVIF image sequences are not supported. * AVIF image sequences are not supported.
* Prebuilt binaries support a bitdepth of 8 only. * Prebuilt binaries support a bitdepth of 8 only.
* *
* This feature is experimental on the Windows ARM64 platform
* and requires a CPU with ARM64v8.4 or later.
*
* @example * @example
* const data = await sharp(input) * const data = await sharp(input)
* .avif({ effort: 2 }) * .avif({ effort: 2 })
@ -1121,8 +1191,6 @@ function heif (options) {
* The prebuilt binaries do not include this - see * The prebuilt binaries do not include this - see
* {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}. * {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}.
* *
* Image metadata (EXIF, XMP) is unsupported.
*
* @since 0.31.3 * @since 0.31.3
* *
* @param {Object} [options] - output options * @param {Object} [options] - output options
@ -1130,7 +1198,9 @@ function heif (options) {
* @param {number} [options.quality] - calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified * @param {number} [options.quality] - calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified
* @param {number} [options.decodingTier=0] - target decode speed tier, between 0 (highest quality) and 4 (lowest quality) * @param {number} [options.decodingTier=0] - target decode speed tier, between 0 (highest quality) and 4 (lowest quality)
* @param {boolean} [options.lossless=false] - use lossless compression * @param {boolean} [options.lossless=false] - use lossless compression
* @param {number} [options.effort=7] - CPU effort, between 3 (fastest) and 9 (slowest) * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 9 (slowest)
* @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation
* @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)
* @returns {Sharp} * @returns {Sharp}
* @throws {Error} Invalid options * @throws {Error} Invalid options
*/ */
@ -1167,13 +1237,14 @@ function jxl (options) {
} }
} }
if (is.defined(options.effort)) { if (is.defined(options.effort)) {
if (is.integer(options.effort) && is.inRange(options.effort, 3, 9)) { if (is.integer(options.effort) && is.inRange(options.effort, 1, 9)) {
this.options.jxlEffort = options.effort; this.options.jxlEffort = options.effort;
} else { } else {
throw is.invalidParameterError('effort', 'integer between 3 and 9', options.effort); throw is.invalidParameterError('effort', 'integer between 1 and 9', options.effort);
} }
} }
} }
trySetAnimationOptions(options, this.options);
return this._updateFormatOut('jxl', options); return this._updateFormatOut('jxl', options);
} }
@ -1225,10 +1296,6 @@ function raw (options) {
* *
* The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`. * The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`.
* *
* Requires libvips compiled with support for libgsf.
* The prebuilt binaries do not include this - see
* {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}.
*
* @example * @example
* sharp('input.tiff') * sharp('input.tiff')
* .png() * .png()
@ -1549,6 +1616,7 @@ function _pipeline (callback, stack) {
/** /**
* Decorate the Sharp prototype with output-related functions. * Decorate the Sharp prototype with output-related functions.
* @module Sharp
* @private * @private
*/ */
module.exports = function (Sharp) { module.exports = function (Sharp) {
@ -1561,6 +1629,8 @@ module.exports = function (Sharp) {
withExifMerge, withExifMerge,
keepIccProfile, keepIccProfile,
withIccProfile, withIccProfile,
keepXmp,
withXmp,
keepMetadata, keepMetadata,
withMetadata, withMetadata,
toFormat, toFormat,

View File

@ -72,7 +72,9 @@ const kernel = {
cubic: 'cubic', cubic: 'cubic',
mitchell: 'mitchell', mitchell: 'mitchell',
lanczos2: 'lanczos2', lanczos2: 'lanczos2',
lanczos3: 'lanczos3' lanczos3: 'lanczos3',
mks2013: 'mks2013',
mks2021: 'mks2021'
}; };
/** /**
@ -105,7 +107,7 @@ const mapFitToCanvas = {
* @private * @private
*/ */
function isRotationExpected (options) { function isRotationExpected (options) {
return (options.angle % 360) !== 0 || options.useExifOrientation === true || options.rotationAngle !== 0; return (options.angle % 360) !== 0 || options.input.autoOrient === true || options.rotationAngle !== 0;
} }
/** /**
@ -127,7 +129,7 @@ function isResizeExpected (options) {
* *
* Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property. * Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property.
* *
* <img alt="Examples of various values for the fit property when resizing" width="100%" style="aspect-ratio: 998/243" src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/api-resize-fit.svg"> * <img alt="Examples of various values for the fit property when resizing" width="100%" style="aspect-ratio: 998/243" src="/api-resize-fit.svg">
* *
* When using a **fit** of `cover` or `contain`, the default **position** is `centre`. Other options are: * 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.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`.
@ -148,6 +150,8 @@ function isResizeExpected (options) {
* - `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf). * - `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf).
* - `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`. * - `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`.
* - `lanczos3`: Use a Lanczos kernel with `a=3` (the default). * - `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
* - `mks2013`: Use a [Magic Kernel Sharp](https://johncostella.com/magic/mks.pdf) 2013 kernel, as adopted by Facebook.
* - `mks2021`: Use a Magic Kernel Sharp 2021 kernel, with more accurate (reduced) sharpening than the 2013 version.
* *
* When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators. * When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators.
* Downsampling kernels without a matching upsampling interpolator map to `cubic`. * Downsampling kernels without a matching upsampling interpolator map to `cubic`.
@ -569,6 +573,7 @@ function trim (options) {
/** /**
* Decorate the Sharp prototype with resize-related functions. * Decorate the Sharp prototype with resize-related functions.
* @module Sharp
* @private * @private
*/ */
module.exports = function (Sharp) { module.exports = function (Sharp) {

View File

@ -17,9 +17,9 @@ const paths = [
'@img/sharp-wasm32/sharp.node' '@img/sharp-wasm32/sharp.node'
]; ];
let sharp; let path, sharp;
const errors = []; const errors = [];
for (const path of paths) { for (path of paths) {
try { try {
sharp = require(path); sharp = require(path);
break; break;
@ -29,6 +29,14 @@ for (const path of paths) {
} }
} }
/* istanbul ignore next */
if (sharp && path.startsWith('@img/sharp-linux-x64') && !sharp._isUsingX64V2()) {
const err = new Error('Prebuilt binaries for linux-x64 require v2 microarchitecture');
err.code = 'Unsupported CPU';
errors.push(err);
sharp = null;
}
/* istanbul ignore next */ /* istanbul ignore next */
if (sharp) { if (sharp) {
module.exports = sharp; module.exports = sharp;
@ -57,7 +65,6 @@ if (sharp) {
help.push( help.push(
'- Ensure optional dependencies can be installed:', '- Ensure optional dependencies can be installed:',
' npm install --include=optional sharp', ' npm install --include=optional sharp',
' yarn add sharp --ignore-engines',
'- Ensure your package manager supports multi-platform installation:', '- Ensure your package manager supports multi-platform installation:',
' See https://sharp.pixelplumbing.com/install#cross-platform', ' See https://sharp.pixelplumbing.com/install#cross-platform',
'- Add platform-specific dependencies:', '- Add platform-specific dependencies:',
@ -73,9 +80,9 @@ if (sharp) {
} }
if (isLinux && /(symbol not found|CXXABI_)/i.test(messages)) { if (isLinux && /(symbol not found|CXXABI_)/i.test(messages)) {
try { try {
const { engines } = require(`@img/sharp-libvips-${runtimePlatform}/package`); const { config } = require(`@img/sharp-libvips-${runtimePlatform}/package`);
const libcFound = `${familySync()} ${versionSync()}`; const libcFound = `${familySync()} ${versionSync()}`;
const libcRequires = `${engines.musl ? 'musl' : 'glibc'} ${engines.musl || engines.glibc}`; const libcRequires = `${config.musl ? 'musl' : 'glibc'} ${config.musl || config.glibc}`;
help.push( help.push(
'- Update your OS:', '- Update your OS:',
` Found ${libcFound}`, ` Found ${libcFound}`,

View File

@ -75,6 +75,13 @@ if (!libvipsVersion.isGlobal) {
} }
versions.sharp = require('../package.json').version; versions.sharp = require('../package.json').version;
/* istanbul ignore next */
if (versions.heif && format.heif) {
// Prebuilt binaries provide AV1
format.heif.input.fileSuffix = ['.avif'];
format.heif.output.alias = ['avif'];
}
/** /**
* 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. * Existing entries in the cache will be trimmed after any change in limits.
@ -128,15 +135,9 @@ cache(true);
* e.g. libaom manages its own 4 threads when encoding AVIF images, * e.g. libaom manages its own 4 threads when encoding AVIF images,
* and these are independent of the value set here. * and these are independent of the value set here.
* *
* The maximum number of images that sharp can process in parallel * :::note
* is controlled by libuv's `UV_THREADPOOL_SIZE` environment variable, * Further {@link /performance|control over performance} is available.
* which defaults to 4. * :::
*
* https://nodejs.org/api/cli.html#uv_threadpool_sizesize
*
* For example, by default, a machine with 8 CPU cores will process
* 4 images in parallel and use up to 8 threads per image,
* so there will be up to 32 concurrent threads.
* *
* @example * @example
* const threads = sharp.concurrency(); // 4 * const threads = sharp.concurrency(); // 4
@ -273,6 +274,7 @@ function unblock (options) {
/** /**
* Decorate the Sharp class with utility-related functions. * Decorate the Sharp class with utility-related functions.
* @module Sharp
* @private * @private
*/ */
module.exports = function (Sharp) { module.exports = function (Sharp) {

View File

@ -1,6 +1,6 @@
{ {
"name": "@img/sharp-darwin-arm64", "name": "@img/sharp-darwin-arm64",
"version": "0.33.4", "version": "0.34.3-rc.0",
"description": "Prebuilt sharp for use with macOS 64-bit ARM", "description": "Prebuilt sharp for use with macOS 64-bit ARM",
"author": "Lovell Fuller <npm@lovell.info>", "author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com", "homepage": "https://sharp.pixelplumbing.com",
@ -15,7 +15,7 @@
}, },
"preferUnplugged": true, "preferUnplugged": true,
"optionalDependencies": { "optionalDependencies": {
"@img/sharp-libvips-darwin-arm64": "1.0.2" "@img/sharp-libvips-darwin-arm64": "1.2.0"
}, },
"files": [ "files": [
"lib" "lib"
@ -29,11 +29,7 @@
"./package": "./package.json" "./package": "./package.json"
}, },
"engines": { "engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0", "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"npm": ">=9.6.5",
"yarn": ">=3.2.0",
"pnpm": ">=7.1.0",
"glibc": ">=2.26"
}, },
"os": [ "os": [
"darwin" "darwin"

View File

@ -1,6 +1,6 @@
{ {
"name": "@img/sharp-darwin-x64", "name": "@img/sharp-darwin-x64",
"version": "0.33.4", "version": "0.34.3-rc.0",
"description": "Prebuilt sharp for use with macOS x64", "description": "Prebuilt sharp for use with macOS x64",
"author": "Lovell Fuller <npm@lovell.info>", "author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com", "homepage": "https://sharp.pixelplumbing.com",
@ -15,7 +15,7 @@
}, },
"preferUnplugged": true, "preferUnplugged": true,
"optionalDependencies": { "optionalDependencies": {
"@img/sharp-libvips-darwin-x64": "1.0.2" "@img/sharp-libvips-darwin-x64": "1.2.0"
}, },
"files": [ "files": [
"lib" "lib"
@ -29,11 +29,7 @@
"./package": "./package.json" "./package": "./package.json"
}, },
"engines": { "engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0", "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"npm": ">=9.6.5",
"yarn": ">=3.2.0",
"pnpm": ">=7.1.0",
"glibc": ">=2.26"
}, },
"os": [ "os": [
"darwin" "darwin"

View File

@ -1,73 +0,0 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
// Populate contents of all packages with the current GitHub release
const { readFile, writeFile, appendFile, copyFile, rm } = require('node:fs/promises');
const path = require('node:path');
const { Readable } = require('node:stream');
const { pipeline } = require('node:stream/promises');
const { createGunzip } = require('node:zlib');
const { extract } = require('tar-fs');
const { workspaces } = require('./package.json');
const { version } = require('../package.json');
const mapTarballEntry = (header) => {
header.name = path.basename(header.name);
return header;
};
const licensing = `
## Licensing
Copyright 2013 Lovell Fuller and others.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
`;
workspaces.map(async platform => {
const prebuildPlatform = platform === 'wasm32' ? 'emscripten-wasm32' : platform;
const url = `https://github.com/lovell/sharp/releases/download/v${version}/sharp-v${version}-napi-v9-${prebuildPlatform}.tar.gz`;
const dir = path.join(__dirname, platform);
const response = await fetch(url);
if (!response.ok) {
console.log(`Skipping ${platform}: ${response.statusText}`);
return;
}
// Extract prebuild tarball
const lib = path.join(dir, 'lib');
await rm(lib, { force: true, recursive: true });
await pipeline(
Readable.fromWeb(response.body),
createGunzip(),
extract(lib, { map: mapTarballEntry })
);
// Generate README
const { name, description } = require(`./${platform}/package.json`);
await writeFile(path.join(dir, 'README.md'), `# \`${name}\`\n\n${description}.\n${licensing}`);
// Copy Apache-2.0 LICENSE
await copyFile(path.join(__dirname, '..', 'LICENSE'), path.join(dir, 'LICENSE'));
// Copy files for packages without an explicit sharp-libvips dependency (Windows, wasm)
if (platform.startsWith('win') || platform.startsWith('wasm')) {
const libvipsPlatform = platform === 'wasm32' ? 'dev-wasm32' : platform;
const sharpLibvipsDir = path.join(require(`@img/sharp-libvips-${libvipsPlatform}/lib`), '..');
// Copy versions.json
await copyFile(path.join(sharpLibvipsDir, 'versions.json'), path.join(dir, 'versions.json'));
// Append third party licensing to README
const readme = await readFile(path.join(sharpLibvipsDir, 'README.md'), { encoding: 'utf-8' });
const thirdParty = readme.substring(readme.indexOf('\nThis software contains'));
appendFile(path.join(dir, 'README.md'), thirdParty);
}
});

View File

@ -3,24 +3,62 @@
'use strict'; 'use strict';
// Populate contents of a single npm/sharpen-sharp-<build-platform> package // Populate the npm package for the current platform with the local build
// with the local/CI build directory for local/CI prebuild testing
const fs = require('node:fs'); const { copyFileSync, cpSync, readFileSync, writeFileSync, appendFileSync } = require('node:fs');
const path = require('node:path'); const { basename, join } = require('node:path');
const { buildPlatformArch } = require('../lib/libvips'); const { buildPlatformArch } = require('../lib/libvips');
const platform = buildPlatformArch();
const dest = path.join(__dirname, platform);
// Use same config as prebuild to copy binary files const licensing = `
const release = path.join(__dirname, '..', 'src', 'build', 'Release'); ## Licensing
const prebuildrc = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '.prebuildrc'), 'utf8'));
const include = new RegExp(prebuildrc['include-regex'], 'i'); Copyright 2013 Lovell Fuller and others.
fs.cpSync(release, path.join(dest, 'lib'), {
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
`;
const platform = buildPlatformArch();
const destDir = join(__dirname, platform);
console.log(`Populating npm package for platform: ${platform}`);
// Copy binaries
const releaseDir = join(__dirname, '..', 'src', 'build', 'Release');
const libDir = join(destDir, 'lib');
cpSync(releaseDir, libDir, {
recursive: true, recursive: true,
filter: (file) => { filter: (file) => {
const name = path.basename(file); const name = basename(file);
return name === 'Release' || include.test(name); return name === 'Release' ||
(name.startsWith('sharp-') && name.includes('.node')) ||
(name.startsWith('libvips-') && name.endsWith('.dll'));
} }
}); });
// Generate README
const { name, description } = require(`./${platform}/package.json`);
writeFileSync(join(destDir, 'README.md'), `# \`${name}\`\n\n${description}.\n${licensing}`);
// Copy Apache-2.0 LICENSE
copyFileSync(join(__dirname, '..', 'LICENSE'), join(destDir, 'LICENSE'));
// Copy files for packages without an explicit sharp-libvips dependency (Windows, wasm)
if (platform.startsWith('win') || platform.startsWith('wasm')) {
const libvipsPlatform = platform === 'wasm32' ? 'dev-wasm32' : platform;
const sharpLibvipsDir = join(require(`@img/sharp-libvips-${libvipsPlatform}/lib`), '..');
// Copy versions.json
copyFileSync(join(sharpLibvipsDir, 'versions.json'), join(destDir, 'versions.json'));
// Append third party licensing to README
const readme = readFileSync(join(sharpLibvipsDir, 'README.md'), { encoding: 'utf-8' });
const thirdParty = readme.substring(readme.indexOf('\nThis software contains'));
appendFileSync(join(destDir, 'README.md'), thirdParty);
}

View File

@ -1,6 +1,6 @@
{ {
"name": "@img/sharp-linux-arm", "name": "@img/sharp-linux-arm",
"version": "0.33.4", "version": "0.34.3-rc.0",
"description": "Prebuilt sharp for use with Linux (glibc) ARM (32-bit)", "description": "Prebuilt sharp for use with Linux (glibc) ARM (32-bit)",
"author": "Lovell Fuller <npm@lovell.info>", "author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com", "homepage": "https://sharp.pixelplumbing.com",
@ -15,7 +15,7 @@
}, },
"preferUnplugged": true, "preferUnplugged": true,
"optionalDependencies": { "optionalDependencies": {
"@img/sharp-libvips-linux-arm": "1.0.2" "@img/sharp-libvips-linux-arm": "1.2.0"
}, },
"files": [ "files": [
"lib" "lib"
@ -29,11 +29,10 @@
"./package": "./package.json" "./package": "./package.json"
}, },
"engines": { "engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0", "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"npm": ">=9.6.5", },
"yarn": ">=3.2.0", "config": {
"pnpm": ">=7.1.0", "glibc": ">=2.31"
"glibc": ">=2.28"
}, },
"os": [ "os": [
"linux" "linux"

View File

@ -1,6 +1,6 @@
{ {
"name": "@img/sharp-linux-arm64", "name": "@img/sharp-linux-arm64",
"version": "0.33.4", "version": "0.34.3-rc.0",
"description": "Prebuilt sharp for use with Linux (glibc) 64-bit ARM", "description": "Prebuilt sharp for use with Linux (glibc) 64-bit ARM",
"author": "Lovell Fuller <npm@lovell.info>", "author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com", "homepage": "https://sharp.pixelplumbing.com",
@ -15,7 +15,7 @@
}, },
"preferUnplugged": true, "preferUnplugged": true,
"optionalDependencies": { "optionalDependencies": {
"@img/sharp-libvips-linux-arm64": "1.0.2" "@img/sharp-libvips-linux-arm64": "1.2.0"
}, },
"files": [ "files": [
"lib" "lib"
@ -29,10 +29,9 @@
"./package": "./package.json" "./package": "./package.json"
}, },
"engines": { "engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0", "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"npm": ">=9.6.5", },
"yarn": ">=3.2.0", "config": {
"pnpm": ">=7.1.0",
"glibc": ">=2.26" "glibc": ">=2.26"
}, },
"os": [ "os": [

View File

@ -0,0 +1,46 @@
{
"name": "@img/sharp-linux-ppc64",
"version": "0.34.3-rc.0",
"description": "Prebuilt sharp for use with Linux (glibc) ppc64",
"author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com",
"repository": {
"type": "git",
"url": "git+https://github.com/lovell/sharp.git",
"directory": "npm/linux-ppc64"
},
"license": "Apache-2.0",
"funding": {
"url": "https://opencollective.com/libvips"
},
"preferUnplugged": true,
"optionalDependencies": {
"@img/sharp-libvips-linux-ppc64": "1.2.0"
},
"files": [
"lib"
],
"publishConfig": {
"access": "public"
},
"type": "commonjs",
"exports": {
"./sharp.node": "./lib/sharp-linux-ppc64.node",
"./package": "./package.json"
},
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"config": {
"glibc": ">=2.31"
},
"os": [
"linux"
],
"libc": [
"glibc"
],
"cpu": [
"ppc64"
]
}

View File

@ -1,6 +1,6 @@
{ {
"name": "@img/sharp-linux-s390x", "name": "@img/sharp-linux-s390x",
"version": "0.33.4", "version": "0.34.3-rc.0",
"description": "Prebuilt sharp for use with Linux (glibc) s390x", "description": "Prebuilt sharp for use with Linux (glibc) s390x",
"author": "Lovell Fuller <npm@lovell.info>", "author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com", "homepage": "https://sharp.pixelplumbing.com",
@ -15,7 +15,7 @@
}, },
"preferUnplugged": true, "preferUnplugged": true,
"optionalDependencies": { "optionalDependencies": {
"@img/sharp-libvips-linux-s390x": "1.0.2" "@img/sharp-libvips-linux-s390x": "1.2.0"
}, },
"files": [ "files": [
"lib" "lib"
@ -29,10 +29,9 @@
"./package": "./package.json" "./package": "./package.json"
}, },
"engines": { "engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0", "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"npm": ">=9.6.5", },
"yarn": ">=3.2.0", "config": {
"pnpm": ">=7.1.0",
"glibc": ">=2.31" "glibc": ">=2.31"
}, },
"os": [ "os": [

View File

@ -1,6 +1,6 @@
{ {
"name": "@img/sharp-linux-x64", "name": "@img/sharp-linux-x64",
"version": "0.33.4", "version": "0.34.3-rc.0",
"description": "Prebuilt sharp for use with Linux (glibc) x64", "description": "Prebuilt sharp for use with Linux (glibc) x64",
"author": "Lovell Fuller <npm@lovell.info>", "author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com", "homepage": "https://sharp.pixelplumbing.com",
@ -15,7 +15,7 @@
}, },
"preferUnplugged": true, "preferUnplugged": true,
"optionalDependencies": { "optionalDependencies": {
"@img/sharp-libvips-linux-x64": "1.0.2" "@img/sharp-libvips-linux-x64": "1.2.0"
}, },
"files": [ "files": [
"lib" "lib"
@ -29,10 +29,9 @@
"./package": "./package.json" "./package": "./package.json"
}, },
"engines": { "engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0", "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"npm": ">=9.6.5", },
"yarn": ">=3.2.0", "config": {
"pnpm": ">=7.1.0",
"glibc": ">=2.26" "glibc": ">=2.26"
}, },
"os": [ "os": [

View File

@ -1,6 +1,6 @@
{ {
"name": "@img/sharp-linuxmusl-arm64", "name": "@img/sharp-linuxmusl-arm64",
"version": "0.33.4", "version": "0.34.3-rc.0",
"description": "Prebuilt sharp for use with Linux (musl) 64-bit ARM", "description": "Prebuilt sharp for use with Linux (musl) 64-bit ARM",
"author": "Lovell Fuller <npm@lovell.info>", "author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com", "homepage": "https://sharp.pixelplumbing.com",
@ -15,7 +15,7 @@
}, },
"preferUnplugged": true, "preferUnplugged": true,
"optionalDependencies": { "optionalDependencies": {
"@img/sharp-libvips-linuxmusl-arm64": "1.0.2" "@img/sharp-libvips-linuxmusl-arm64": "1.2.0"
}, },
"files": [ "files": [
"lib" "lib"
@ -29,10 +29,9 @@
"./package": "./package.json" "./package": "./package.json"
}, },
"engines": { "engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0", "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"npm": ">=9.6.5", },
"yarn": ">=3.2.0", "config": {
"pnpm": ">=7.1.0",
"musl": ">=1.2.2" "musl": ">=1.2.2"
}, },
"os": [ "os": [

View File

@ -1,6 +1,6 @@
{ {
"name": "@img/sharp-linuxmusl-x64", "name": "@img/sharp-linuxmusl-x64",
"version": "0.33.4", "version": "0.34.3-rc.0",
"description": "Prebuilt sharp for use with Linux (musl) x64", "description": "Prebuilt sharp for use with Linux (musl) x64",
"author": "Lovell Fuller <npm@lovell.info>", "author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com", "homepage": "https://sharp.pixelplumbing.com",
@ -15,7 +15,7 @@
}, },
"preferUnplugged": true, "preferUnplugged": true,
"optionalDependencies": { "optionalDependencies": {
"@img/sharp-libvips-linuxmusl-x64": "1.0.2" "@img/sharp-libvips-linuxmusl-x64": "1.2.0"
}, },
"files": [ "files": [
"lib" "lib"
@ -29,10 +29,9 @@
"./package": "./package.json" "./package": "./package.json"
}, },
"engines": { "engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0", "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"npm": ">=9.6.5", },
"yarn": ">=3.2.0", "config": {
"pnpm": ">=7.1.0",
"musl": ">=1.2.2" "musl": ">=1.2.2"
}, },
"os": [ "os": [

View File

@ -1,17 +1,19 @@
{ {
"name": "@img/sharp", "name": "@img/sharp",
"version": "0.33.4", "version": "0.34.3-rc.0",
"private": "true", "private": "true",
"workspaces": [ "workspaces": [
"darwin-arm64", "darwin-arm64",
"darwin-x64", "darwin-x64",
"linux-arm", "linux-arm",
"linux-arm64", "linux-arm64",
"linux-ppc64",
"linux-s390x", "linux-s390x",
"linux-x64", "linux-x64",
"linuxmusl-arm64", "linuxmusl-arm64",
"linuxmusl-x64", "linuxmusl-x64",
"wasm32", "wasm32",
"win32-arm64",
"win32-ia32", "win32-ia32",
"win32-x64" "win32-x64"
] ]

View File

@ -1,6 +1,6 @@
{ {
"name": "@img/sharp-wasm32", "name": "@img/sharp-wasm32",
"version": "0.33.4", "version": "0.34.3-rc.0",
"description": "Prebuilt sharp for use with wasm32", "description": "Prebuilt sharp for use with wasm32",
"author": "Lovell Fuller <npm@lovell.info>", "author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com", "homepage": "https://sharp.pixelplumbing.com",
@ -28,13 +28,10 @@
"./versions": "./versions.json" "./versions": "./versions.json"
}, },
"engines": { "engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0", "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"npm": ">=9.6.5",
"yarn": ">=3.2.0",
"pnpm": ">=7.1.0"
}, },
"dependencies": { "dependencies": {
"@emnapi/runtime": "^1.1.1" "@emnapi/runtime": "^1.4.4"
}, },
"cpu": [ "cpu": [
"wasm32" "wasm32"

View File

@ -0,0 +1,39 @@
{
"name": "@img/sharp-win32-arm64",
"version": "0.34.3-rc.0",
"description": "Prebuilt sharp for use with Windows 64-bit ARM",
"author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com",
"repository": {
"type": "git",
"url": "git+https://github.com/lovell/sharp.git",
"directory": "npm/win32-arm64"
},
"license": "Apache-2.0 AND LGPL-3.0-or-later",
"funding": {
"url": "https://opencollective.com/libvips"
},
"preferUnplugged": true,
"files": [
"lib",
"versions.json"
],
"publishConfig": {
"access": "public"
},
"type": "commonjs",
"exports": {
"./sharp.node": "./lib/sharp-win32-arm64.node",
"./package": "./package.json",
"./versions": "./versions.json"
},
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"os": [
"win32"
],
"cpu": [
"arm64"
]
}

View File

@ -1,6 +1,6 @@
{ {
"name": "@img/sharp-win32-ia32", "name": "@img/sharp-win32-ia32",
"version": "0.33.4", "version": "0.34.3-rc.0",
"description": "Prebuilt sharp for use with Windows x86 (32-bit)", "description": "Prebuilt sharp for use with Windows x86 (32-bit)",
"author": "Lovell Fuller <npm@lovell.info>", "author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com", "homepage": "https://sharp.pixelplumbing.com",
@ -28,10 +28,7 @@
"./versions": "./versions.json" "./versions": "./versions.json"
}, },
"engines": { "engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0", "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"npm": ">=9.6.5",
"yarn": ">=3.2.0",
"pnpm": ">=7.1.0"
}, },
"os": [ "os": [
"win32" "win32"

View File

@ -1,6 +1,6 @@
{ {
"name": "@img/sharp-win32-x64", "name": "@img/sharp-win32-x64",
"version": "0.33.4", "version": "0.34.3-rc.0",
"description": "Prebuilt sharp for use with Windows x64", "description": "Prebuilt sharp for use with Windows x64",
"author": "Lovell Fuller <npm@lovell.info>", "author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com", "homepage": "https://sharp.pixelplumbing.com",
@ -28,10 +28,7 @@
"./versions": "./versions.json" "./versions": "./versions.json"
}, },
"engines": { "engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0", "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"npm": ">=9.6.5",
"yarn": ">=3.2.0",
"pnpm": ">=7.1.0"
}, },
"os": [ "os": [
"win32" "win32"

View File

@ -1,7 +1,7 @@
{ {
"name": "sharp", "name": "sharp",
"description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images", "description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images",
"version": "0.33.4", "version": "0.34.3-rc.0",
"author": "Lovell Fuller <npm@lovell.info>", "author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com", "homepage": "https://sharp.pixelplumbing.com",
"contributors": [ "contributors": [
@ -88,10 +88,11 @@
"Mart Jansink <m.jansink@gmail.com>", "Mart Jansink <m.jansink@gmail.com>",
"Lachlan Newman <lachnewman007@gmail.com>", "Lachlan Newman <lachnewman007@gmail.com>",
"Dennis Beatty <dennis@dcbeatty.com>", "Dennis Beatty <dennis@dcbeatty.com>",
"Ingvar Stepanyan <me@rreverser.com>" "Ingvar Stepanyan <me@rreverser.com>",
"Don Denton <don@happycollision.com>"
], ],
"scripts": { "scripts": {
"install": "node install/check", "install": "node install/check.js",
"clean": "rm -rf src/build/ .nyc_output/ coverage/ test/fixtures/output.*", "clean": "rm -rf src/build/ .nyc_output/ coverage/ test/fixtures/output.*",
"test": "npm run test-lint && npm run test-unit && npm run test-licensing && npm run test-types", "test": "npm run test-lint && npm run test-unit && npm run test-licensing && npm run test-types",
"test-lint": "semistandard && cpplint", "test-lint": "semistandard && cpplint",
@ -99,11 +100,10 @@
"test-licensing": "license-checker --production --summary --onlyAllow=\"Apache-2.0;BSD;ISC;LGPL-3.0-or-later;MIT\"", "test-licensing": "license-checker --production --summary --onlyAllow=\"Apache-2.0;BSD;ISC;LGPL-3.0-or-later;MIT\"",
"test-leak": "./test/leak/leak.sh", "test-leak": "./test/leak/leak.sh",
"test-types": "tsd", "test-types": "tsd",
"package-from-local-build": "node npm/from-local-build", "package-from-local-build": "node npm/from-local-build.js",
"package-from-github-release": "node npm/from-github-release", "docs-build": "node docs/build.mjs",
"docs-build": "node docs/build && node docs/search-index/build", "docs-serve": "cd docs && npm start",
"docs-serve": "cd docs && npx serve", "docs-publish": "cd docs && npm run build && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp"
"docs-publish": "cd docs && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp"
}, },
"type": "commonjs", "type": "commonjs",
"main": "lib/index.js", "main": "lib/index.js",
@ -137,66 +137,66 @@
], ],
"dependencies": { "dependencies": {
"color": "^4.2.3", "color": "^4.2.3",
"detect-libc": "^2.0.3", "detect-libc": "^2.0.4",
"semver": "^7.6.0" "semver": "^7.7.2"
}, },
"optionalDependencies": { "optionalDependencies": {
"@img/sharp-darwin-arm64": "0.33.4", "@img/sharp-darwin-arm64": "0.34.3-rc.0",
"@img/sharp-darwin-x64": "0.33.4", "@img/sharp-darwin-x64": "0.34.3-rc.0",
"@img/sharp-libvips-darwin-arm64": "1.0.2", "@img/sharp-libvips-darwin-arm64": "1.2.0",
"@img/sharp-libvips-darwin-x64": "1.0.2", "@img/sharp-libvips-darwin-x64": "1.2.0",
"@img/sharp-libvips-linux-arm": "1.0.2", "@img/sharp-libvips-linux-arm": "1.2.0",
"@img/sharp-libvips-linux-arm64": "1.0.2", "@img/sharp-libvips-linux-arm64": "1.2.0",
"@img/sharp-libvips-linux-s390x": "1.0.2", "@img/sharp-libvips-linux-ppc64": "1.2.0",
"@img/sharp-libvips-linux-x64": "1.0.2", "@img/sharp-libvips-linux-s390x": "1.2.0",
"@img/sharp-libvips-linuxmusl-arm64": "1.0.2", "@img/sharp-libvips-linux-x64": "1.2.0",
"@img/sharp-libvips-linuxmusl-x64": "1.0.2", "@img/sharp-libvips-linuxmusl-arm64": "1.2.0",
"@img/sharp-linux-arm": "0.33.4", "@img/sharp-libvips-linuxmusl-x64": "1.2.0",
"@img/sharp-linux-arm64": "0.33.4", "@img/sharp-linux-arm": "0.34.3-rc.0",
"@img/sharp-linux-s390x": "0.33.4", "@img/sharp-linux-arm64": "0.34.3-rc.0",
"@img/sharp-linux-x64": "0.33.4", "@img/sharp-linux-ppc64": "0.34.3-rc.0",
"@img/sharp-linuxmusl-arm64": "0.33.4", "@img/sharp-linux-s390x": "0.34.3-rc.0",
"@img/sharp-linuxmusl-x64": "0.33.4", "@img/sharp-linux-x64": "0.34.3-rc.0",
"@img/sharp-wasm32": "0.33.4", "@img/sharp-linuxmusl-arm64": "0.34.3-rc.0",
"@img/sharp-win32-ia32": "0.33.4", "@img/sharp-linuxmusl-x64": "0.34.3-rc.0",
"@img/sharp-win32-x64": "0.33.4" "@img/sharp-wasm32": "0.34.3-rc.0",
"@img/sharp-win32-arm64": "0.34.3-rc.0",
"@img/sharp-win32-ia32": "0.34.3-rc.0",
"@img/sharp-win32-x64": "0.34.3-rc.0"
}, },
"devDependencies": { "devDependencies": {
"@emnapi/runtime": "^1.1.1", "@emnapi/runtime": "^1.4.4",
"@img/sharp-libvips-dev": "1.0.2", "@img/sharp-libvips-dev": "1.2.0",
"@img/sharp-libvips-dev-wasm32": "1.0.3", "@img/sharp-libvips-dev-wasm32": "1.2.0",
"@img/sharp-libvips-win32-ia32": "1.0.2", "@img/sharp-libvips-win32-arm64": "1.2.0",
"@img/sharp-libvips-win32-x64": "1.0.2", "@img/sharp-libvips-win32-ia32": "1.2.0",
"@img/sharp-libvips-win32-x64": "1.2.0",
"@types/node": "*", "@types/node": "*",
"async": "^3.2.5",
"cc": "^3.0.1", "cc": "^3.0.1",
"emnapi": "^1.1.1", "emnapi": "^1.4.4",
"exif-reader": "^2.0.1", "exif-reader": "^2.0.2",
"extract-zip": "^2.0.1", "extract-zip": "^2.0.1",
"icc": "^3.0.0", "icc": "^3.0.0",
"jsdoc-to-markdown": "^8.0.1", "jsdoc-to-markdown": "^9.1.1",
"license-checker": "^25.0.1", "license-checker": "^25.0.1",
"mocha": "^10.4.0", "mocha": "^11.7.1",
"node-addon-api": "^8.0.0", "node-addon-api": "^8.4.0",
"nyc": "^15.1.0", "node-gyp": "^11.2.0",
"prebuild": "^13.0.1", "nyc": "^17.1.0",
"semistandard": "^17.0.0", "semistandard": "^17.0.0",
"tar-fs": "^3.0.6", "tar-fs": "^3.1.0",
"tsd": "^0.31.0" "tsd": "^0.32.0"
}, },
"license": "Apache-2.0", "license": "Apache-2.0",
"engines": { "engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0", "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"libvips": ">=8.15.2" },
"config": {
"libvips": ">=8.17.1"
}, },
"funding": { "funding": {
"url": "https://opencollective.com/libvips" "url": "https://opencollective.com/libvips"
}, },
"binary": {
"napi_versions": [
9
]
},
"semistandard": { "semistandard": {
"env": [ "env": [
"mocha" "mocha"

View File

@ -12,14 +12,17 @@
'sharp_libvips_lib_dir': '<!(node -p "require(\'../lib/libvips\').buildSharpLibvipsLibDir()")' 'sharp_libvips_lib_dir': '<!(node -p "require(\'../lib/libvips\').buildSharpLibvipsLibDir()")'
}, },
'targets': [{ 'targets': [{
'target_name': 'libvips-cpp', 'target_name': 'libvips-cpp-<(vips_version)',
'conditions': [ 'conditions': [
['OS == "win"', { ['OS == "win"', {
# Build libvips C++ binding for Windows due to MSVC std library ABI changes # Build libvips C++ binding for Windows due to MSVC std library ABI changes
'type': 'shared_library', 'type': 'shared_library',
'defines': [ 'defines': [
'VIPS_CPLUSPLUS_EXPORTS', '_VIPS_PUBLIC=__declspec(dllexport)',
'_ALLOW_KEYWORD_MACROS' '_ALLOW_KEYWORD_MACROS',
'G_DISABLE_ASSERT',
'G_DISABLE_CAST_CHECKS',
'G_DISABLE_CHECKS'
], ],
'sources': [ 'sources': [
'<(sharp_libvips_cplusplus_dir)/VConnection.cpp', '<(sharp_libvips_cplusplus_dir)/VConnection.cpp',
@ -45,6 +48,9 @@
'Release': { 'Release': {
'msvs_settings': { 'msvs_settings': {
'VCCLCompilerTool': { 'VCCLCompilerTool': {
"AdditionalOptions": [
"/std:c++17"
],
'ExceptionHandling': 1, 'ExceptionHandling': 1,
'Optimization': 1, 'Optimization': 1,
'WholeProgramOptimization': 'true' 'WholeProgramOptimization': 'true'
@ -77,13 +83,16 @@
}, { }, {
'target_name': 'sharp-<(platform_and_arch)', 'target_name': 'sharp-<(platform_and_arch)',
'defines': [ 'defines': [
'G_DISABLE_ASSERT',
'G_DISABLE_CAST_CHECKS',
'G_DISABLE_CHECKS',
'NAPI_VERSION=9', 'NAPI_VERSION=9',
'NODE_ADDON_API_DISABLE_DEPRECATED', 'NODE_ADDON_API_DISABLE_DEPRECATED',
'NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS' 'NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS'
], ],
'dependencies': [ 'dependencies': [
'<!(node -p "require(\'node-addon-api\').gyp")', '<!(node -p "require(\'node-addon-api\').gyp")',
'libvips-cpp' 'libvips-cpp-<(vips_version)'
], ],
'variables': { 'variables': {
'conditions': [ 'conditions': [
@ -149,11 +158,13 @@
['OS == "mac"', { ['OS == "mac"', {
'link_settings': { 'link_settings': {
'libraries': [ 'libraries': [
'libvips-cpp.42.dylib' 'libvips-cpp.<(vips_version).dylib'
] ]
}, },
'xcode_settings': { 'xcode_settings': {
'OTHER_LDFLAGS': [ 'OTHER_LDFLAGS': [
'-Wl,-s',
'-Wl,-dead_strip',
# Ensure runtime linking is relative to sharp.node # Ensure runtime linking is relative to sharp.node
'-Wl,-rpath,\'@loader_path/../../sharp-libvips-<(platform_and_arch)/lib\'', '-Wl,-rpath,\'@loader_path/../../sharp-libvips-<(platform_and_arch)/lib\'',
'-Wl,-rpath,\'@loader_path/../../../sharp-libvips-<(platform_and_arch)/<(sharp_libvips_version)/lib\'', '-Wl,-rpath,\'@loader_path/../../../sharp-libvips-<(platform_and_arch)/<(sharp_libvips_version)/lib\'',
@ -167,14 +178,19 @@
'defines': [ 'defines': [
'_GLIBCXX_USE_CXX11_ABI=1' '_GLIBCXX_USE_CXX11_ABI=1'
], ],
'cflags_cc': [
'<!(node -p "require(\'detect-libc\').isNonGlibcLinuxSync() ? \'\' : \'-flto=auto\'")'
],
'link_settings': { 'link_settings': {
'libraries': [ 'libraries': [
'-l:libvips-cpp.so.42' '-l:libvips-cpp.so.<(vips_version)'
], ],
'ldflags': [ 'ldflags': [
'-lstdc++fs',
'-Wl,-s', '-Wl,-s',
'-Wl,--disable-new-dtags', '-Wl,--disable-new-dtags',
'-Wl,-z,nodelete', '-Wl,-z,nodelete',
'-Wl,-Bsymbolic-functions',
'-Wl,-rpath=\'$$ORIGIN/../../sharp-libvips-<(platform_and_arch)/lib\'', '-Wl,-rpath=\'$$ORIGIN/../../sharp-libvips-<(platform_and_arch)/lib\'',
'-Wl,-rpath=\'$$ORIGIN/../../../sharp-libvips-<(platform_and_arch)/<(sharp_libvips_version)/lib\'', '-Wl,-rpath=\'$$ORIGIN/../../../sharp-libvips-<(platform_and_arch)/<(sharp_libvips_version)/lib\'',
'-Wl,-rpath=\'$$ORIGIN/../../node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\'', '-Wl,-rpath=\'$$ORIGIN/../../node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\'',
@ -192,7 +208,7 @@
'-Oz', '-Oz',
'-sALLOW_MEMORY_GROWTH', '-sALLOW_MEMORY_GROWTH',
'-sENVIRONMENT=node', '-sENVIRONMENT=node',
'-sEXPORTED_FUNCTIONS=["_vips_shutdown", "_uv_library_shutdown"]', '-sEXPORTED_FUNCTIONS=["emnapiInit", "_vips_shutdown", "_uv_library_shutdown"]',
'-sNODERAWFS', '-sNODERAWFS',
'-sTEXTDECODER=0', '-sTEXTDECODER=0',
'-sWASM_ASYNC_COMPILATION=0', '-sWASM_ASYNC_COMPILATION=0',
@ -207,14 +223,14 @@
}] }]
], ],
'cflags_cc': [ 'cflags_cc': [
'-std=c++0x', '-std=c++17',
'-fexceptions', '-fexceptions',
'-Wall', '-Wall',
'-Os' '-Os'
], ],
'xcode_settings': { 'xcode_settings': {
'CLANG_CXX_LANGUAGE_STANDARD': 'c++11', 'CLANG_CXX_LANGUAGE_STANDARD': 'c++17',
'MACOSX_DEPLOYMENT_TARGET': '10.13', 'MACOSX_DEPLOYMENT_TARGET': '10.15',
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
'GCC_ENABLE_CPP_RTTI': 'YES', 'GCC_ENABLE_CPP_RTTI': 'YES',
'OTHER_CPLUSPLUSFLAGS': [ 'OTHER_CPLUSPLUSFLAGS': [
@ -234,6 +250,9 @@
['OS == "win"', { ['OS == "win"', {
'msvs_settings': { 'msvs_settings': {
'VCCLCompilerTool': { 'VCCLCompilerTool': {
"AdditionalOptions": [
"/std:c++17"
],
'ExceptionHandling': 1, 'ExceptionHandling': 1,
'Optimization': 1, 'Optimization': 1,
'WholeProgramOptimization': 'true' 'WholeProgramOptimization': 'true'

View File

@ -93,6 +93,7 @@ namespace sharp {
descriptor->rawWidth = AttrAsUint32(input, "rawWidth"); descriptor->rawWidth = AttrAsUint32(input, "rawWidth");
descriptor->rawHeight = AttrAsUint32(input, "rawHeight"); descriptor->rawHeight = AttrAsUint32(input, "rawHeight");
descriptor->rawPremultiplied = AttrAsBool(input, "rawPremultiplied"); descriptor->rawPremultiplied = AttrAsBool(input, "rawPremultiplied");
descriptor->rawPageHeight = AttrAsUint32(input, "rawPageHeight");
} }
// Multi-page input (GIF, TIFF, PDF) // Multi-page input (GIF, TIFF, PDF)
if (HasAttr(input, "pages")) { if (HasAttr(input, "pages")) {
@ -101,19 +102,35 @@ namespace sharp {
if (HasAttr(input, "page")) { if (HasAttr(input, "page")) {
descriptor->page = AttrAsUint32(input, "page"); descriptor->page = AttrAsUint32(input, "page");
} }
// SVG
if (HasAttr(input, "svgStylesheet")) {
descriptor->svgStylesheet = AttrAsStr(input, "svgStylesheet");
}
if (HasAttr(input, "svgHighBitdepth")) {
descriptor->svgHighBitdepth = AttrAsBool(input, "svgHighBitdepth");
}
// Multi-level input (OpenSlide) // Multi-level input (OpenSlide)
if (HasAttr(input, "level")) { if (HasAttr(input, "openSlideLevel")) {
descriptor->level = AttrAsUint32(input, "level"); descriptor->openSlideLevel = AttrAsUint32(input, "openSlideLevel");
} }
// subIFD (OME-TIFF) // subIFD (OME-TIFF)
if (HasAttr(input, "subifd")) { if (HasAttr(input, "subifd")) {
descriptor->subifd = AttrAsInt32(input, "subifd"); descriptor->tiffSubifd = AttrAsInt32(input, "tiffSubifd");
}
// // PDF background color
if (HasAttr(input, "pdfBackground")) {
descriptor->pdfBackground = AttrAsVectorOfDouble(input, "pdfBackground");
}
// Use JPEG 2000 oneshot mode?
if (HasAttr(input, "jp2Oneshot")) {
descriptor->jp2Oneshot = AttrAsBool(input, "jp2Oneshot");
} }
// Create new image // Create new image
if (HasAttr(input, "createChannels")) { if (HasAttr(input, "createChannels")) {
descriptor->createChannels = AttrAsUint32(input, "createChannels"); descriptor->createChannels = AttrAsUint32(input, "createChannels");
descriptor->createWidth = AttrAsUint32(input, "createWidth"); descriptor->createWidth = AttrAsUint32(input, "createWidth");
descriptor->createHeight = AttrAsUint32(input, "createHeight"); descriptor->createHeight = AttrAsUint32(input, "createHeight");
descriptor->createPageHeight = AttrAsUint32(input, "createPageHeight");
if (HasAttr(input, "createNoiseType")) { if (HasAttr(input, "createNoiseType")) {
descriptor->createNoiseType = AttrAsStr(input, "createNoiseType"); descriptor->createNoiseType = AttrAsStr(input, "createNoiseType");
descriptor->createNoiseMean = AttrAsDouble(input, "createNoiseMean"); descriptor->createNoiseMean = AttrAsDouble(input, "createNoiseMean");
@ -156,12 +173,34 @@ namespace sharp {
descriptor->textWrap = AttrAsEnum<VipsTextWrap>(input, "textWrap", VIPS_TYPE_TEXT_WRAP); descriptor->textWrap = AttrAsEnum<VipsTextWrap>(input, "textWrap", VIPS_TYPE_TEXT_WRAP);
} }
} }
// Join images together
if (HasAttr(input, "joinAnimated")) {
descriptor->joinAnimated = AttrAsBool(input, "joinAnimated");
}
if (HasAttr(input, "joinAcross")) {
descriptor->joinAcross = AttrAsUint32(input, "joinAcross");
}
if (HasAttr(input, "joinShim")) {
descriptor->joinShim = AttrAsUint32(input, "joinShim");
}
if (HasAttr(input, "joinBackground")) {
descriptor->joinBackground = AttrAsVectorOfDouble(input, "joinBackground");
}
if (HasAttr(input, "joinHalign")) {
descriptor->joinHalign = AttrAsEnum<VipsAlign>(input, "joinHalign", VIPS_TYPE_ALIGN);
}
if (HasAttr(input, "joinValign")) {
descriptor->joinValign = AttrAsEnum<VipsAlign>(input, "joinValign", VIPS_TYPE_ALIGN);
}
// Limit input images to a given number of pixels, where pixels = width * height // Limit input images to a given number of pixels, where pixels = width * height
descriptor->limitInputPixels = static_cast<uint64_t>(AttrAsInt64(input, "limitInputPixels")); descriptor->limitInputPixels = static_cast<uint64_t>(AttrAsInt64(input, "limitInputPixels"));
// Allow switch from random to sequential access if (HasAttr(input, "access")) {
descriptor->access = AttrAsBool(input, "sequentialRead") ? VIPS_ACCESS_SEQUENTIAL : VIPS_ACCESS_RANDOM; descriptor->access = AttrAsBool(input, "sequentialRead") ? VIPS_ACCESS_SEQUENTIAL : VIPS_ACCESS_RANDOM;
}
// Remove safety features and allow unlimited input // Remove safety features and allow unlimited input
descriptor->unlimited = AttrAsBool(input, "unlimited"); descriptor->unlimited = AttrAsBool(input, "unlimited");
// Use the EXIF orientation to auto orient the image
descriptor->autoOrient = AttrAsBool(input, "autoOrient");
return descriptor; return descriptor;
} }
@ -244,6 +283,8 @@ namespace sharp {
case ImageType::FITS: id = "fits"; break; case ImageType::FITS: id = "fits"; break;
case ImageType::EXR: id = "exr"; break; case ImageType::EXR: id = "exr"; break;
case ImageType::JXL: id = "jxl"; break; case ImageType::JXL: id = "jxl"; break;
case ImageType::RAD: id = "rad"; break;
case ImageType::DCRAW: id = "dcraw"; break;
case ImageType::VIPS: id = "vips"; break; case ImageType::VIPS: id = "vips"; break;
case ImageType::RAW: id = "raw"; break; case ImageType::RAW: id = "raw"; break;
case ImageType::UNKNOWN: id = "unknown"; break; case ImageType::UNKNOWN: id = "unknown"; break;
@ -290,6 +331,10 @@ namespace sharp {
{ "VipsForeignLoadOpenexr", ImageType::EXR }, { "VipsForeignLoadOpenexr", ImageType::EXR },
{ "VipsForeignLoadJxlFile", ImageType::JXL }, { "VipsForeignLoadJxlFile", ImageType::JXL },
{ "VipsForeignLoadJxlBuffer", ImageType::JXL }, { "VipsForeignLoadJxlBuffer", ImageType::JXL },
{ "VipsForeignLoadRadFile", ImageType::RAD },
{ "VipsForeignLoadRadBuffer", ImageType::RAD },
{ "VipsForeignLoadDcRawFile", ImageType::DCRAW },
{ "VipsForeignLoadDcRawBuffer", ImageType::DCRAW },
{ "VipsForeignLoadVips", ImageType::VIPS }, { "VipsForeignLoadVips", ImageType::VIPS },
{ "VipsForeignLoadVipsFile", ImageType::VIPS }, { "VipsForeignLoadVipsFile", ImageType::VIPS },
{ "VipsForeignLoadRaw", ImageType::RAW } { "VipsForeignLoadRaw", ImageType::RAW }
@ -354,6 +399,48 @@ namespace sharp {
imageType == ImageType::HEIF; imageType == ImageType::HEIF;
} }
/*
Format-specific options builder
*/
vips::VOption* GetOptionsForImageType(ImageType imageType, InputDescriptor *descriptor) {
vips::VOption *option = VImage::option()
->set("access", descriptor->access)
->set("fail_on", descriptor->failOn);
if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {
option->set("unlimited", true);
}
if (ImageTypeSupportsPage(imageType)) {
option->set("n", descriptor->pages);
option->set("page", descriptor->page);
}
switch (imageType) {
case ImageType::SVG:
option->set("dpi", descriptor->density)
->set("stylesheet", descriptor->svgStylesheet.data())
->set("high_bitdepth", descriptor->svgHighBitdepth);
break;
case ImageType::TIFF:
option->set("tiffSubifd", descriptor->tiffSubifd);
break;
case ImageType::PDF:
option->set("dpi", descriptor->density)
->set("background", descriptor->pdfBackground);
break;
case ImageType::OPENSLIDE:
option->set("openSlideLevel", descriptor->openSlideLevel);
break;
case ImageType::JP2:
option->set("oneshot", descriptor->jp2Oneshot);
break;
case ImageType::MAGICK:
option->set("density", std::to_string(descriptor->density).data());
break;
default:
break;
}
return option;
}
/* /*
Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data) Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data)
*/ */
@ -371,6 +458,10 @@ namespace sharp {
} else { } else {
image.get_image()->Type = is8bit ? VIPS_INTERPRETATION_sRGB : VIPS_INTERPRETATION_RGB16; image.get_image()->Type = is8bit ? VIPS_INTERPRETATION_sRGB : VIPS_INTERPRETATION_RGB16;
} }
if (descriptor->rawPageHeight > 0) {
image.set(VIPS_META_PAGE_HEIGHT, descriptor->rawPageHeight);
image.set(VIPS_META_N_PAGES, static_cast<int>(descriptor->rawHeight / descriptor->rawPageHeight));
}
if (descriptor->rawPremultiplied) { if (descriptor->rawPremultiplied) {
image = image.unpremultiply(); image = image.unpremultiply();
} }
@ -380,28 +471,7 @@ namespace sharp {
imageType = DetermineImageType(descriptor->buffer, descriptor->bufferLength); imageType = DetermineImageType(descriptor->buffer, descriptor->bufferLength);
if (imageType != ImageType::UNKNOWN) { if (imageType != ImageType::UNKNOWN) {
try { try {
vips::VOption *option = VImage::option() vips::VOption *option = GetOptionsForImageType(imageType, descriptor);
->set("access", descriptor->access)
->set("fail_on", descriptor->failOn);
if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {
option->set("unlimited", true);
}
if (imageType == ImageType::SVG || imageType == ImageType::PDF) {
option->set("dpi", descriptor->density);
}
if (imageType == ImageType::MAGICK) {
option->set("density", std::to_string(descriptor->density).data());
}
if (ImageTypeSupportsPage(imageType)) {
option->set("n", descriptor->pages);
option->set("page", descriptor->page);
}
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); image = VImage::new_from_buffer(descriptor->buffer, descriptor->bufferLength, nullptr, option);
if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) { if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) {
image = SetDensity(image, descriptor->density); image = SetDensity(image, descriptor->density);
@ -441,6 +511,10 @@ namespace sharp {
channels < 3 ? VIPS_INTERPRETATION_B_W : VIPS_INTERPRETATION_sRGB)) channels < 3 ? VIPS_INTERPRETATION_B_W : VIPS_INTERPRETATION_sRGB))
.new_from_image(background); .new_from_image(background);
} }
if (descriptor->createPageHeight > 0) {
image.set(VIPS_META_PAGE_HEIGHT, descriptor->createPageHeight);
image.set(VIPS_META_N_PAGES, static_cast<int>(descriptor->createHeight / descriptor->createPageHeight));
}
image = image.cast(VIPS_FORMAT_UCHAR); image = image.cast(VIPS_FORMAT_UCHAR);
imageType = ImageType::RAW; imageType = ImageType::RAW;
} else if (descriptor->textValue.length() > 0) { } else if (descriptor->textValue.length() > 0) {
@ -484,28 +558,7 @@ namespace sharp {
} }
if (imageType != ImageType::UNKNOWN) { if (imageType != ImageType::UNKNOWN) {
try { try {
vips::VOption *option = VImage::option() vips::VOption *option = GetOptionsForImageType(imageType, descriptor);
->set("access", descriptor->access)
->set("fail_on", descriptor->failOn);
if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {
option->set("unlimited", true);
}
if (imageType == ImageType::SVG || imageType == ImageType::PDF) {
option->set("dpi", descriptor->density);
}
if (imageType == ImageType::MAGICK) {
option->set("density", std::to_string(descriptor->density).data());
}
if (ImageTypeSupportsPage(imageType)) {
option->set("n", descriptor->pages);
option->set("page", descriptor->page);
}
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); image = VImage::new_from_file(descriptor->file.data(), option);
if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) { if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) {
image = SetDensity(image, descriptor->density); image = SetDensity(image, descriptor->density);
@ -560,14 +613,6 @@ namespace sharp {
return image; return image;
} }
/*
Does this image have an alpha channel?
Uses colour space interpretation with number of channels to guess this.
*/
bool HasAlpha(VImage image) {
return image.has_alpha();
}
static void* RemoveExifCallback(VipsImage *image, char const *field, GValue *value, void *data) { static void* RemoveExifCallback(VipsImage *image, char const *field, GValue *value, void *data) {
std::vector<std::string> *fieldNames = static_cast<std::vector<std::string> *>(data); std::vector<std::string> *fieldNames = static_cast<std::vector<std::string> *>(data);
std::string fieldName(field); std::string fieldName(field);
@ -624,22 +669,21 @@ namespace sharp {
*/ */
VImage SetAnimationProperties(VImage image, int nPages, int pageHeight, std::vector<int> delay, int loop) { VImage SetAnimationProperties(VImage image, int nPages, int pageHeight, std::vector<int> delay, int loop) {
bool hasDelay = !delay.empty(); bool hasDelay = !delay.empty();
// Avoid a copy if none of the animation properties are needed.
if (nPages == 1 && !hasDelay && loop == -1) return image;
if (delay.size() == 1) {
// We have just one delay, repeat that value for all frames.
delay.insert(delay.end(), nPages - 1, delay[0]);
}
// Attaching metadata, need to copy the image.
VImage copy = image.copy(); VImage copy = image.copy();
// Only set page-height if we have more than one page, or this could // Only set page-height if we have more than one page, or this could
// accidentally turn into an animated image later. // accidentally turn into an animated image later.
if (nPages > 1) copy.set(VIPS_META_PAGE_HEIGHT, pageHeight); if (nPages > 1) copy.set(VIPS_META_PAGE_HEIGHT, pageHeight);
if (hasDelay) copy.set("delay", delay); if (hasDelay) {
if (delay.size() == 1) {
// We have just one delay, repeat that value for all frames.
delay.insert(delay.end(), nPages - 1, delay[0]);
}
copy.set("delay", delay);
}
if (nPages == 1 && !hasDelay && loop == -1) {
loop = 1;
}
if (loop != -1) copy.set("loop", loop); if (loop != -1) copy.set("loop", loop);
return copy; return copy;
@ -925,14 +969,6 @@ namespace sharp {
return interpretation == VIPS_INTERPRETATION_RGB16 || interpretation == VIPS_INTERPRETATION_GREY16; return interpretation == VIPS_INTERPRETATION_RGB16 || interpretation == VIPS_INTERPRETATION_GREY16;
} }
/*
Return the image alpha maximum. Useful for combining alpha bands. scRGB
images are 0 - 1 for image data, but the alpha is 0 - 255.
*/
double MaximumImageAlpha(VipsInterpretation const interpretation) {
return Is16Bit(interpretation) ? 65535.0 : 255.0;
}
/* /*
Convert RGBA value to another colourspace Convert RGBA value to another colourspace
*/ */
@ -975,25 +1011,25 @@ namespace sharp {
0.0722 * colour[2]) 0.0722 * colour[2])
}; };
} }
// Add alpha channel to alphaColour colour // Add alpha channel(s) to alphaColour colour
if (colour[3] < 255.0 || HasAlpha(image)) { if (colour[3] < 255.0 || image.has_alpha()) {
alphaColour.push_back(colour[3] * multiplier); int extraBands = image.bands() > 4 ? image.bands() - 3 : 1;
alphaColour.insert(alphaColour.end(), extraBands, colour[3] * multiplier);
} }
// Ensure alphaColour colour uses correct colourspace // Ensure alphaColour colour uses correct colourspace
alphaColour = sharp::GetRgbaAsColourspace(alphaColour, image.interpretation(), premultiply); alphaColour = sharp::GetRgbaAsColourspace(alphaColour, image.interpretation(), premultiply);
// Add non-transparent alpha channel, if required // Add non-transparent alpha channel, if required
if (colour[3] < 255.0 && !HasAlpha(image)) { if (colour[3] < 255.0 && !image.has_alpha()) {
image = image.bandjoin( image = image.bandjoin_const({ 255 * multiplier });
VImage::new_matrix(image.width(), image.height()).new_from_image(255 * multiplier).cast(image.format()));
} }
return std::make_tuple(image, alphaColour); return std::make_tuple(image, alphaColour);
} }
/* /*
Removes alpha channel, if any. Removes alpha channels, if any.
*/ */
VImage RemoveAlpha(VImage image) { VImage RemoveAlpha(VImage image) {
if (HasAlpha(image)) { while (image.bands() > 1 && image.has_alpha()) {
image = image.extract_band(0, VImage::option()->set("n", image.bands() - 1)); image = image.extract_band(0, VImage::option()->set("n", image.bands() - 1));
} }
return image; return image;
@ -1003,10 +1039,8 @@ namespace sharp {
Ensures alpha channel, if missing. Ensures alpha channel, if missing.
*/ */
VImage EnsureAlpha(VImage image, double const value) { VImage EnsureAlpha(VImage image, double const value) {
if (!HasAlpha(image)) { if (!image.has_alpha()) {
std::vector<double> alpha; image = image.bandjoin_const({ value * vips_interpretation_max_alpha(image.interpretation()) });
alpha.push_back(value * sharp::MaximumImageAlpha(image.interpretation()));
image = image.bandjoin_const(alpha);
} }
return image; return image;
} }

View File

@ -15,18 +15,14 @@
// Verify platform and compiler compatibility // Verify platform and compiler compatibility
#if (VIPS_MAJOR_VERSION < 8) || \ #if (VIPS_MAJOR_VERSION < 8) || \
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION < 15) || \ (VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION < 17) || \
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION == 15 && VIPS_MICRO_VERSION < 2) (VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION == 17 && VIPS_MICRO_VERSION < 1)
#error "libvips version 8.15.2+ is required - please see https://sharp.pixelplumbing.com/install" #error "libvips version 8.17.1+ is required - please see https://sharp.pixelplumbing.com/install"
#endif #endif
#if ((!defined(__clang__)) && defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 6))) #if defined(__has_include)
#error "GCC version 4.6+ is required for C++11 features - please see https://sharp.pixelplumbing.com/install" #if !__has_include(<filesystem>)
#endif #error "C++17 compiler required - please see https://sharp.pixelplumbing.com/install"
#if (defined(__clang__) && defined(__has_feature))
#if (!__has_feature(cxx_range_for))
#error "clang version 3.0+ is required for C++11 features - please see https://sharp.pixelplumbing.com/install"
#endif #endif
#endif #endif
@ -37,6 +33,7 @@ namespace sharp {
struct InputDescriptor { // NOLINT(runtime/indentation_namespace) struct InputDescriptor { // NOLINT(runtime/indentation_namespace)
std::string name; std::string name;
std::string file; std::string file;
bool autoOrient;
char *buffer; char *buffer;
VipsFailOn failOn; VipsFailOn failOn;
uint64_t limitInputPixels; uint64_t limitInputPixels;
@ -51,13 +48,13 @@ namespace sharp {
int rawWidth; int rawWidth;
int rawHeight; int rawHeight;
bool rawPremultiplied; bool rawPremultiplied;
int rawPageHeight;
int pages; int pages;
int page; int page;
int level;
int subifd;
int createChannels; int createChannels;
int createWidth; int createWidth;
int createHeight; int createHeight;
int createPageHeight;
std::vector<double> createBackground; std::vector<double> createBackground;
std::string createNoiseType; std::string createNoiseType;
double createNoiseMean; double createNoiseMean;
@ -74,13 +71,26 @@ namespace sharp {
int textSpacing; int textSpacing;
VipsTextWrap textWrap; VipsTextWrap textWrap;
int textAutofitDpi; int textAutofitDpi;
bool joinAnimated;
int joinAcross;
int joinShim;
std::vector<double> joinBackground;
VipsAlign joinHalign;
VipsAlign joinValign;
std::string svgStylesheet;
bool svgHighBitdepth;
int tiffSubifd;
int openSlideLevel;
std::vector<double> pdfBackground;
bool jp2Oneshot;
InputDescriptor(): InputDescriptor():
autoOrient(false),
buffer(nullptr), buffer(nullptr),
failOn(VIPS_FAIL_ON_WARNING), failOn(VIPS_FAIL_ON_WARNING),
limitInputPixels(0x3FFF * 0x3FFF), limitInputPixels(0x3FFF * 0x3FFF),
unlimited(false), unlimited(false),
access(VIPS_ACCESS_RANDOM), access(VIPS_ACCESS_SEQUENTIAL),
bufferLength(0), bufferLength(0),
isBuffer(false), isBuffer(false),
density(72.0), density(72.0),
@ -90,13 +100,13 @@ namespace sharp {
rawWidth(0), rawWidth(0),
rawHeight(0), rawHeight(0),
rawPremultiplied(false), rawPremultiplied(false),
rawPageHeight(0),
pages(1), pages(1),
page(0), page(0),
level(0),
subifd(-1),
createChannels(0), createChannels(0),
createWidth(0), createWidth(0),
createHeight(0), createHeight(0),
createPageHeight(0),
createBackground{ 0.0, 0.0, 0.0, 255.0 }, createBackground{ 0.0, 0.0, 0.0, 255.0 },
createNoiseMean(0.0), createNoiseMean(0.0),
createNoiseSigma(0.0), createNoiseSigma(0.0),
@ -108,7 +118,18 @@ namespace sharp {
textRgba(false), textRgba(false),
textSpacing(0), textSpacing(0),
textWrap(VIPS_TEXT_WRAP_WORD), textWrap(VIPS_TEXT_WRAP_WORD),
textAutofitDpi(0) {} textAutofitDpi(0),
joinAnimated(false),
joinAcross(1),
joinShim(0),
joinBackground{ 0.0, 0.0, 0.0, 255.0 },
joinHalign(VIPS_ALIGN_LOW),
joinValign(VIPS_ALIGN_LOW),
svgHighBitdepth(false),
tiffSubifd(-1),
openSlideLevel(0),
pdfBackground{ 255.0, 255.0, 255.0, 255.0 },
jp2Oneshot(false) {}
}; };
// Convenience methods to access the attributes of a Napi::Object // Convenience methods to access the attributes of a Napi::Object
@ -147,6 +168,8 @@ namespace sharp {
FITS, FITS,
EXR, EXR,
JXL, JXL,
RAD,
DCRAW,
VIPS, VIPS,
RAW, RAW,
UNKNOWN, UNKNOWN,
@ -203,14 +226,9 @@ namespace sharp {
ImageType DetermineImageType(char const *file); ImageType DetermineImageType(char const *file);
/* /*
Does this image type support multiple pages? Format-specific options builder
*/ */
bool ImageTypeSupportsPage(ImageType imageType); vips::VOption* GetOptionsForImageType(ImageType imageType, InputDescriptor *descriptor);
/*
Does this image type support removal of safety limits?
*/
bool ImageTypeSupportsUnlimited(ImageType imageType);
/* /*
Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data) Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data)
@ -232,12 +250,6 @@ namespace sharp {
*/ */
VImage SetProfile(VImage image, std::pair<char*, size_t> icc); VImage SetProfile(VImage image, std::pair<char*, size_t> icc);
/*
Does this image have an alpha channel?
Uses colour space interpretation with number of channels to guess this.
*/
bool HasAlpha(VImage image);
/* /*
Remove all EXIF-related image fields. Remove all EXIF-related image fields.
*/ */
@ -350,12 +362,6 @@ namespace sharp {
*/ */
bool Is16Bit(VipsInterpretation const interpretation); bool Is16Bit(VipsInterpretation const interpretation);
/*
Return the image alpha maximum. Useful for combining alpha bands. scRGB
images are 0 - 1 for image data, but the alpha is 0 - 255.
*/
double MaximumImageAlpha(VipsInterpretation const interpretation);
/* /*
Convert RGBA value to another colourspace Convert RGBA value to another colourspace
*/ */
@ -368,7 +374,7 @@ namespace sharp {
std::tuple<VImage, std::vector<double>> ApplyAlpha(VImage image, std::vector<double> colour, bool premultiply); std::tuple<VImage, std::vector<double>> ApplyAlpha(VImage image, std::vector<double> colour, bool premultiply);
/* /*
Removes alpha channel, if any. Removes alpha channels, if any.
*/ */
VImage RemoveAlpha(VImage image); VImage RemoveAlpha(VImage image);

View File

@ -9,8 +9,7 @@
'default_configuration': 'Release', 'default_configuration': 'Release',
'type': 'executable', 'type': 'executable',
'cflags': [ 'cflags': [
'-pthread', '-pthread'
'-sDEFAULT_TO_CXX=0'
], ],
'cflags_cc': [ 'cflags_cc': [
'-pthread' '-pthread'
@ -19,6 +18,7 @@
'--js-library=<!(node -p "require(\'emnapi\').js_library")', '--js-library=<!(node -p "require(\'emnapi\').js_library")',
'-sAUTO_JS_LIBRARIES=0', '-sAUTO_JS_LIBRARIES=0',
'-sAUTO_NATIVE_LIBRARIES=0', '-sAUTO_NATIVE_LIBRARIES=0',
'-sDEFAULT_TO_CXX=0',
'-sNODEJS_CATCH_EXIT=0', '-sNODEJS_CATCH_EXIT=0',
'-sNODEJS_CATCH_REJECTION=0' '-sNODEJS_CATCH_REJECTION=0'
], ],
@ -28,7 +28,7 @@
'EMNAPI_WORKER_POOL_SIZE=1' 'EMNAPI_WORKER_POOL_SIZE=1'
], ],
'include_dirs': [ 'include_dirs': [
'<!(node -p "require(\'emnapi\').include")' '<!(node -p "require(\'emnapi\').include_dir")'
], ],
'sources': [ 'sources': [
'<!@(node -p "require(\'emnapi\').sources.map(x => JSON.stringify(path.relative(process.cwd(), x))).join(\' \')")' '<!@(node -p "require(\'emnapi\').sources.map(x => JSON.stringify(path.relative(process.cwd(), x))).join(\' \')")'

View File

@ -3,6 +3,7 @@
#include <numeric> #include <numeric>
#include <vector> #include <vector>
#include <cmath>
#include <napi.h> #include <napi.h>
#include <vips/vips8> #include <vips/vips8>
@ -10,6 +11,8 @@
#include "common.h" #include "common.h"
#include "metadata.h" #include "metadata.h"
static void* readPNGComment(VipsImage *image, const char *field, GValue *value, void *p);
class MetadataWorker : public Napi::AsyncWorker { class MetadataWorker : public Napi::AsyncWorker {
public: public:
MetadataWorker(Napi::Function callback, MetadataBaton *baton, Napi::Function debuglog) : MetadataWorker(Napi::Function callback, MetadataBaton *baton, Napi::Function debuglog) :
@ -45,8 +48,11 @@ class MetadataWorker : public Napi::AsyncWorker {
if (image.get_typeof("interlaced") == G_TYPE_INT) { if (image.get_typeof("interlaced") == G_TYPE_INT) {
baton->isProgressive = image.get_int("interlaced") == 1; baton->isProgressive = image.get_int("interlaced") == 1;
} }
if (image.get_typeof("palette-bit-depth") == G_TYPE_INT) { if (image.get_typeof(VIPS_META_PALETTE) == G_TYPE_INT) {
baton->paletteBitDepth = image.get_int("palette-bit-depth"); baton->isPalette = image.get_int(VIPS_META_PALETTE);
}
if (image.get_typeof(VIPS_META_BITS_PER_SAMPLE) == G_TYPE_INT) {
baton->bitsPerSample = image.get_int(VIPS_META_BITS_PER_SAMPLE);
} }
if (image.get_typeof(VIPS_META_N_PAGES) == G_TYPE_INT) { if (image.get_typeof(VIPS_META_N_PAGES) == G_TYPE_INT) {
baton->pages = image.get_int(VIPS_META_N_PAGES); baton->pages = image.get_int(VIPS_META_N_PAGES);
@ -89,7 +95,7 @@ class MetadataWorker : public Napi::AsyncWorker {
baton->background = image.get_array_double("background"); baton->background = image.get_array_double("background");
} }
// Derived attributes // Derived attributes
baton->hasAlpha = sharp::HasAlpha(image); baton->hasAlpha = image.has_alpha();
baton->orientation = sharp::ExifOrientation(image); baton->orientation = sharp::ExifOrientation(image);
// EXIF // EXIF
if (image.get_typeof(VIPS_META_EXIF_NAME) == VIPS_TYPE_BLOB) { if (image.get_typeof(VIPS_META_EXIF_NAME) == VIPS_TYPE_BLOB) {
@ -131,6 +137,8 @@ class MetadataWorker : public Napi::AsyncWorker {
memcpy(baton->tifftagPhotoshop, tifftagPhotoshop, tifftagPhotoshopLength); memcpy(baton->tifftagPhotoshop, tifftagPhotoshop, tifftagPhotoshopLength);
baton->tifftagPhotoshopLength = tifftagPhotoshopLength; baton->tifftagPhotoshopLength = tifftagPhotoshopLength;
} }
// PNG comments
vips_image_map(image.get_image(), readPNGComment, &baton->comments);
} }
// Clean up // Clean up
@ -167,8 +175,13 @@ class MetadataWorker : public Napi::AsyncWorker {
info.Set("chromaSubsampling", baton->chromaSubsampling); info.Set("chromaSubsampling", baton->chromaSubsampling);
} }
info.Set("isProgressive", baton->isProgressive); info.Set("isProgressive", baton->isProgressive);
if (baton->paletteBitDepth > 0) { info.Set("isPalette", baton->isPalette);
info.Set("paletteBitDepth", baton->paletteBitDepth); if (baton->bitsPerSample > 0) {
info.Set("bitsPerSample", baton->bitsPerSample);
if (baton->isPalette) {
// Deprecated, remove with libvips 8.17.0
info.Set("paletteBitDepth", baton->bitsPerSample);
}
} }
if (baton->pages > 0) { if (baton->pages > 0) {
info.Set("pages", baton->pages); info.Set("pages", baton->pages);
@ -214,21 +227,30 @@ class MetadataWorker : public Napi::AsyncWorker {
info.Set("subifds", baton->subifds); info.Set("subifds", baton->subifds);
} }
if (!baton->background.empty()) { if (!baton->background.empty()) {
if (baton->background.size() == 3) {
Napi::Object background = Napi::Object::New(env); Napi::Object background = Napi::Object::New(env);
if (baton->background.size() == 3) {
background.Set("r", baton->background[0]); background.Set("r", baton->background[0]);
background.Set("g", baton->background[1]); background.Set("g", baton->background[1]);
background.Set("b", baton->background[2]); background.Set("b", baton->background[2]);
info.Set("background", background);
} else { } else {
info.Set("background", baton->background[0]); background.Set("gray", round(baton->background[0] * 100 / 255));
} }
info.Set("background", background);
} }
info.Set("hasProfile", baton->hasProfile); info.Set("hasProfile", baton->hasProfile);
info.Set("hasAlpha", baton->hasAlpha); info.Set("hasAlpha", baton->hasAlpha);
if (baton->orientation > 0) { if (baton->orientation > 0) {
info.Set("orientation", baton->orientation); info.Set("orientation", baton->orientation);
} }
Napi::Object autoOrient = Napi::Object::New(env);
info.Set("autoOrient", autoOrient);
if (baton->orientation >= 5) {
autoOrient.Set("width", baton->height);
autoOrient.Set("height", baton->width);
} else {
autoOrient.Set("width", baton->width);
autoOrient.Set("height", baton->height);
}
if (baton->exifLength > 0) { if (baton->exifLength > 0) {
info.Set("exif", Napi::Buffer<char>::NewOrCopy(env, baton->exif, baton->exifLength, sharp::FreeCallback)); info.Set("exif", Napi::Buffer<char>::NewOrCopy(env, baton->exif, baton->exifLength, sharp::FreeCallback));
} }
@ -240,12 +262,27 @@ class MetadataWorker : public Napi::AsyncWorker {
} }
if (baton->xmpLength > 0) { if (baton->xmpLength > 0) {
info.Set("xmp", Napi::Buffer<char>::NewOrCopy(env, baton->xmp, baton->xmpLength, sharp::FreeCallback)); info.Set("xmp", Napi::Buffer<char>::NewOrCopy(env, baton->xmp, baton->xmpLength, sharp::FreeCallback));
if (g_utf8_validate(static_cast<char const *>(baton->xmp), baton->xmpLength, nullptr)) {
info.Set("xmpAsString",
Napi::String::New(env, static_cast<char const *>(baton->xmp), baton->xmpLength));
}
} }
if (baton->tifftagPhotoshopLength > 0) { if (baton->tifftagPhotoshopLength > 0) {
info.Set("tifftagPhotoshop", info.Set("tifftagPhotoshop",
Napi::Buffer<char>::NewOrCopy(env, baton->tifftagPhotoshop, Napi::Buffer<char>::NewOrCopy(env, baton->tifftagPhotoshop,
baton->tifftagPhotoshopLength, sharp::FreeCallback)); baton->tifftagPhotoshopLength, sharp::FreeCallback));
} }
if (baton->comments.size() > 0) {
int i = 0;
Napi::Array comments = Napi::Array::New(env, baton->comments.size());
for (auto &c : baton->comments) {
Napi::Object comment = Napi::Object::New(env);
comment.Set("keyword", c.first);
comment.Set("text", c.second);
comments.Set(i++, comment);
}
info.Set("comments", comments);
}
Callback().Call(Receiver().Value(), { env.Null(), info }); Callback().Call(Receiver().Value(), { env.Null(), info });
} else { } else {
Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() }); Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() });
@ -285,3 +322,21 @@ Napi::Value metadata(const Napi::CallbackInfo& info) {
return info.Env().Undefined(); return info.Env().Undefined();
} }
const char *PNG_COMMENT_START = "png-comment-";
const int PNG_COMMENT_START_LEN = strlen(PNG_COMMENT_START);
static void* readPNGComment(VipsImage *image, const char *field, GValue *value, void *p) {
MetadataComments *comments = static_cast<MetadataComments *>(p);
if (vips_isprefix(PNG_COMMENT_START, field)) {
const char *keyword = strchr(field + PNG_COMMENT_START_LEN, '-');
const char *str;
if (keyword != NULL && !vips_image_get_string(image, field, &str)) {
keyword++; // Skip the hyphen
comments->push_back(std::make_pair(keyword, str));
}
}
return NULL;
}

View File

@ -9,6 +9,8 @@
#include "./common.h" #include "./common.h"
typedef std::vector<std::pair<std::string, std::string>> MetadataComments;
struct MetadataBaton { struct MetadataBaton {
// Input // Input
sharp::InputDescriptor *input; sharp::InputDescriptor *input;
@ -22,7 +24,8 @@ struct MetadataBaton {
int density; int density;
std::string chromaSubsampling; std::string chromaSubsampling;
bool isProgressive; bool isProgressive;
int paletteBitDepth; bool isPalette;
int bitsPerSample;
int pages; int pages;
int pageHeight; int pageHeight;
int loop; int loop;
@ -47,6 +50,7 @@ struct MetadataBaton {
size_t xmpLength; size_t xmpLength;
char *tifftagPhotoshop; char *tifftagPhotoshop;
size_t tifftagPhotoshopLength; size_t tifftagPhotoshopLength;
MetadataComments comments;
std::string err; std::string err;
MetadataBaton(): MetadataBaton():
@ -56,7 +60,8 @@ struct MetadataBaton {
channels(0), channels(0),
density(0), density(0),
isProgressive(false), isProgressive(false),
paletteBitDepth(0), isPalette(false),
bitsPerSample(0),
pages(0), pages(0),
pageHeight(0), pageHeight(0),
loop(-1), loop(-1),

View File

@ -40,7 +40,7 @@ namespace sharp {
typeBeforeTint = VIPS_INTERPRETATION_sRGB; typeBeforeTint = VIPS_INTERPRETATION_sRGB;
} }
// Apply lookup table // Apply lookup table
if (HasAlpha(image)) { if (image.has_alpha()) {
VImage alpha = image[image.bands() - 1]; VImage alpha = image[image.bands() - 1];
image = RemoveAlpha(image) image = RemoveAlpha(image)
.colourspace(VIPS_INTERPRETATION_B_W) .colourspace(VIPS_INTERPRETATION_B_W)
@ -83,7 +83,7 @@ namespace sharp {
// Scale luminance, join to chroma, convert back to original colourspace // Scale luminance, join to chroma, convert back to original colourspace
VImage normalized = luminance.linear(f, a).bandjoin(chroma).colourspace(typeBeforeNormalize); VImage normalized = luminance.linear(f, a).bandjoin(chroma).colourspace(typeBeforeNormalize);
// Attach original alpha channel, if any // Attach original alpha channel, if any
if (HasAlpha(image)) { if (image.has_alpha()) {
// Extract original alpha channel // Extract original alpha channel
VImage alpha = image[image.bands() - 1]; VImage alpha = image[image.bands() - 1];
// Join alpha channel to normalised image // Join alpha channel to normalised image
@ -106,7 +106,7 @@ namespace sharp {
* Gamma encoding/decoding * Gamma encoding/decoding
*/ */
VImage Gamma(VImage image, double const exponent) { VImage Gamma(VImage image, double const exponent) {
if (HasAlpha(image)) { if (image.has_alpha()) {
// Separate alpha channel // Separate alpha channel
VImage alpha = image[image.bands() - 1]; VImage alpha = image[image.bands() - 1];
return RemoveAlpha(image).gamma(VImage::option()->set("exponent", exponent)).bandjoin(alpha); return RemoveAlpha(image).gamma(VImage::option()->set("exponent", exponent)).bandjoin(alpha);
@ -132,7 +132,7 @@ namespace sharp {
* Produce the "negative" of the image. * Produce the "negative" of the image.
*/ */
VImage Negate(VImage image, bool const negateAlpha) { VImage Negate(VImage image, bool const negateAlpha) {
if (HasAlpha(image) && !negateAlpha) { if (image.has_alpha() && !negateAlpha) {
// Separate alpha channel // Separate alpha channel
VImage alpha = image[image.bands() - 1]; VImage alpha = image[image.bands() - 1];
return RemoveAlpha(image).invert().bandjoin(alpha); return RemoveAlpha(image).invert().bandjoin(alpha);
@ -144,7 +144,7 @@ namespace sharp {
/* /*
* Gaussian blur. Use sigma of -1.0 for fast blur. * Gaussian blur. Use sigma of -1.0 for fast blur.
*/ */
VImage Blur(VImage image, double const sigma) { VImage Blur(VImage image, double const sigma, VipsPrecision precision, double const minAmpl) {
if (sigma == -1.0) { if (sigma == -1.0) {
// Fast, mild blur - averages neighbouring pixels // Fast, mild blur - averages neighbouring pixels
VImage blur = VImage::new_matrixv(3, 3, VImage blur = VImage::new_matrixv(3, 3,
@ -155,7 +155,9 @@ namespace sharp {
return image.conv(blur); return image.conv(blur);
} else { } else {
// Slower, accurate Gaussian blur // Slower, accurate Gaussian blur
return StaySequential(image).gaussblur(sigma); return StaySequential(image).gaussblur(sigma, VImage::option()
->set("precision", precision)
->set("min_ampl", minAmpl));
} }
} }
@ -164,10 +166,10 @@ namespace sharp {
*/ */
VImage Convolve(VImage image, int const width, int const height, VImage Convolve(VImage image, int const width, int const height,
double const scale, double const offset, double const scale, double const offset,
std::unique_ptr<double[]> const &kernel_v std::vector<double> const &kernel_v
) { ) {
VImage kernel = VImage::new_from_memory( VImage kernel = VImage::new_from_memory(
kernel_v.get(), static_cast<void*>(const_cast<double*>(kernel_v.data())),
width * height * sizeof(double), width * height * sizeof(double),
width, width,
height, height,
@ -183,25 +185,27 @@ namespace sharp {
* Recomb with a Matrix of the given bands/channel size. * Recomb with a Matrix of the given bands/channel size.
* Eg. RGB will be a 3x3 matrix. * Eg. RGB will be a 3x3 matrix.
*/ */
VImage Recomb(VImage image, std::unique_ptr<double[]> const &matrix) { VImage Recomb(VImage image, std::vector<double> const& matrix) {
double *m = matrix.get(); double* m = const_cast<double*>(matrix.data());
image = image.colourspace(VIPS_INTERPRETATION_sRGB); image = image.colourspace(VIPS_INTERPRETATION_sRGB);
if (matrix.size() == 9) {
return image return image
.recomb(image.bands() == 3 .recomb(image.bands() == 3
? VImage::new_from_memory( ? VImage::new_matrix(3, 3, m, 9)
m, 9 * sizeof(double), 3, 3, 1, VIPS_FORMAT_DOUBLE
)
: VImage::new_matrixv(4, 4, : VImage::new_matrixv(4, 4,
m[0], m[1], m[2], 0.0, m[0], m[1], m[2], 0.0,
m[3], m[4], m[5], 0.0, m[3], m[4], m[5], 0.0,
m[6], m[7], m[8], 0.0, m[6], m[7], m[8], 0.0,
0.0, 0.0, 0.0, 1.0)); 0.0, 0.0, 0.0, 1.0));
} else {
return image.recomb(VImage::new_matrix(4, 4, m, 16));
}
} }
VImage Modulate(VImage image, double const brightness, double const saturation, VImage Modulate(VImage image, double const brightness, double const saturation,
int const hue, double const lightness) { int const hue, double const lightness) {
VipsInterpretation colourspaceBeforeModulate = image.interpretation(); VipsInterpretation colourspaceBeforeModulate = image.interpretation();
if (HasAlpha(image)) { if (image.has_alpha()) {
// Separate alpha channel // Separate alpha channel
VImage alpha = image[image.bands() - 1]; VImage alpha = image[image.bands() - 1];
return RemoveAlpha(image) return RemoveAlpha(image)
@ -293,7 +297,7 @@ namespace sharp {
threshold *= 256.0; threshold *= 256.0;
} }
std::vector<double> backgroundAlpha({ background.back() }); std::vector<double> backgroundAlpha({ background.back() });
if (HasAlpha(image)) { if (image.has_alpha()) {
background.pop_back(); background.pop_back();
} else { } else {
background.resize(image.bands()); background.resize(image.bands());
@ -303,7 +307,7 @@ namespace sharp {
->set("background", background) ->set("background", background)
->set("line_art", lineArt) ->set("line_art", lineArt)
->set("threshold", threshold)); ->set("threshold", threshold));
if (HasAlpha(image)) { if (image.has_alpha()) {
// Search alpha channel (A) // Search alpha channel (A)
int leftA, topA, widthA, heightA; int leftA, topA, widthA, heightA;
VImage alpha = image[image.bands() - 1]; VImage alpha = image[image.bands() - 1];
@ -340,7 +344,7 @@ namespace sharp {
throw VError("Band expansion using linear is unsupported"); throw VError("Band expansion using linear is unsupported");
} }
bool const uchar = !Is16Bit(image.interpretation()); bool const uchar = !Is16Bit(image.interpretation());
if (HasAlpha(image) && a.size() != bands && (a.size() == 1 || a.size() == bands - 1 || bands - 1 == 1)) { if (image.has_alpha() && a.size() != bands && (a.size() == 1 || a.size() == bands - 1 || bands - 1 == 1)) {
// Separate alpha channel // Separate alpha channel
VImage alpha = image[bands - 1]; VImage alpha = image[bands - 1];
return RemoveAlpha(image).linear(a, b, VImage::option()->set("uchar", uchar)).bandjoin(alpha); return RemoveAlpha(image).linear(a, b, VImage::option()->set("uchar", uchar)).bandjoin(alpha);
@ -353,7 +357,7 @@ namespace sharp {
* Unflatten * Unflatten
*/ */
VImage Unflatten(VImage image) { VImage Unflatten(VImage image) {
if (HasAlpha(image)) { if (image.has_alpha()) {
VImage alpha = image[image.bands() - 1]; VImage alpha = image[image.bands() - 1];
VImage noAlpha = RemoveAlpha(image); VImage noAlpha = RemoveAlpha(image);
return noAlpha.bandjoin(alpha & (noAlpha.colourspace(VIPS_INTERPRETATION_B_W) < 255)); return noAlpha.bandjoin(alpha & (noAlpha.colourspace(VIPS_INTERPRETATION_B_W) < 255));
@ -468,4 +472,26 @@ namespace sharp {
} }
} }
/*
* Dilate an image
*/
VImage Dilate(VImage image, int const width) {
int const maskWidth = 2 * width + 1;
VImage mask = VImage::new_matrix(maskWidth, maskWidth);
return image.morph(
mask,
VIPS_OPERATION_MORPHOLOGY_DILATE).invert();
}
/*
* Erode an image
*/
VImage Erode(VImage image, int const width) {
int const maskWidth = 2 * width + 1;
VImage mask = VImage::new_matrix(maskWidth, maskWidth);
return image.morph(
mask,
VIPS_OPERATION_MORPHOLOGY_ERODE).invert();
}
} // namespace sharp } // namespace sharp

View File

@ -47,13 +47,13 @@ namespace sharp {
/* /*
* Gaussian blur. Use sigma of -1.0 for fast blur. * Gaussian blur. Use sigma of -1.0 for fast blur.
*/ */
VImage Blur(VImage image, double const sigma); VImage Blur(VImage image, double const sigma, VipsPrecision precision, double const minAmpl);
/* /*
* Convolution with a kernel. * Convolution with a kernel.
*/ */
VImage Convolve(VImage image, int const width, int const height, VImage Convolve(VImage image, int const width, int const height,
double const scale, double const offset, std::unique_ptr<double[]> const &kernel_v); double const scale, double const offset, std::vector<double> const &kernel_v);
/* /*
* Sharpen flat and jagged areas. Use sigma of -1.0 for fast sharpen. * Sharpen flat and jagged areas. Use sigma of -1.0 for fast sharpen.
@ -95,7 +95,7 @@ namespace sharp {
* Recomb with a Matrix of the given bands/channel size. * Recomb with a Matrix of the given bands/channel size.
* Eg. RGB will be a 3x3 matrix. * Eg. RGB will be a 3x3 matrix.
*/ */
VImage Recomb(VImage image, std::unique_ptr<double[]> const &matrix); VImage Recomb(VImage image, std::vector<double> const &matrix);
/* /*
* Modulate brightness, saturation, hue and lightness * Modulate brightness, saturation, hue and lightness
@ -120,6 +120,15 @@ namespace sharp {
VImage EmbedMultiPage(VImage image, int left, int top, int width, int height, VImage EmbedMultiPage(VImage image, int left, int top, int width, int height,
VipsExtend extendWith, std::vector<double> background, int nPages, int *pageHeight); VipsExtend extendWith, std::vector<double> background, int nPages, int *pageHeight);
/*
* Dilate an image
*/
VImage Dilate(VImage image, int const maskWidth);
/*
* Erode an image
*/
VImage Erode(VImage image, int const maskWidth);
} // namespace sharp } // namespace sharp
#endif // SRC_OPERATIONS_H_ #endif // SRC_OPERATIONS_H_

View File

@ -3,6 +3,7 @@
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
#include <filesystem>
#include <map> #include <map>
#include <memory> #include <memory>
#include <numeric> #include <numeric>
@ -20,17 +21,6 @@
#include "operations.h" #include "operations.h"
#include "pipeline.h" #include "pipeline.h"
#ifdef _WIN32
#define STAT64_STRUCT __stat64
#define STAT64_FUNCTION _stat64
#elif defined(_LARGEFILE64_SOURCE)
#define STAT64_STRUCT stat64
#define STAT64_FUNCTION stat64
#else
#define STAT64_STRUCT stat
#define STAT64_FUNCTION stat
#endif
class PipelineWorker : public Napi::AsyncWorker { class PipelineWorker : public Napi::AsyncWorker {
public: public:
PipelineWorker(Napi::Function callback, PipelineBaton *baton, PipelineWorker(Napi::Function callback, PipelineBaton *baton,
@ -52,7 +42,39 @@ class PipelineWorker : public Napi::AsyncWorker {
// Open input // Open input
vips::VImage image; vips::VImage image;
sharp::ImageType inputImageType; sharp::ImageType inputImageType;
if (baton->join.empty()) {
std::tie(image, inputImageType) = sharp::OpenInput(baton->input); std::tie(image, inputImageType) = sharp::OpenInput(baton->input);
} else {
std::vector<VImage> images;
bool hasAlpha = false;
for (auto &join : baton->join) {
std::tie(image, inputImageType) = sharp::OpenInput(join);
image = sharp::EnsureColourspace(image, baton->colourspacePipeline);
images.push_back(image);
hasAlpha |= image.has_alpha();
}
if (hasAlpha) {
for (auto &image : images) {
if (!image.has_alpha()) {
image = sharp::EnsureAlpha(image, 1);
}
}
} else {
baton->input->joinBackground.pop_back();
}
inputImageType = sharp::ImageType::PNG;
image = VImage::arrayjoin(images, VImage::option()
->set("across", baton->input->joinAcross)
->set("shim", baton->input->joinShim)
->set("background", baton->input->joinBackground)
->set("halign", baton->input->joinHalign)
->set("valign", baton->input->joinValign));
if (baton->input->joinAnimated) {
image = image.copy();
image.set(VIPS_META_N_PAGES, static_cast<int>(images.size()));
image.set(VIPS_META_PAGE_HEIGHT, static_cast<int>(image.height() / images.size()));
}
}
VipsAccess access = baton->input->access; VipsAccess access = baton->input->access;
image = sharp::EnsureColourspace(image, baton->colourspacePipeline); image = sharp::EnsureColourspace(image, baton->colourspacePipeline);
@ -73,14 +95,14 @@ class PipelineWorker : public Napi::AsyncWorker {
bool autoFlip = false; bool autoFlip = false;
bool autoFlop = false; bool autoFlop = false;
if (baton->useExifOrientation) { if (baton->input->autoOrient) {
// Rotate and flip image according to Exif orientation // Rotate and flip image according to Exif orientation
std::tie(autoRotation, autoFlip, autoFlop) = CalculateExifRotationAndFlip(sharp::ExifOrientation(image)); std::tie(autoRotation, autoFlip, autoFlop) = CalculateExifRotationAndFlip(sharp::ExifOrientation(image));
image = sharp::RemoveExifOrientation(image); image = sharp::RemoveExifOrientation(image);
} else {
rotation = CalculateAngleRotation(baton->angle);
} }
rotation = CalculateAngleRotation(baton->angle);
// Rotate pre-extract // Rotate pre-extract
bool const shouldRotateBefore = baton->rotateBeforePreExtract && bool const shouldRotateBefore = baton->rotateBeforePreExtract &&
(rotation != VIPS_ANGLE_D0 || autoRotation != VIPS_ANGLE_D0 || (rotation != VIPS_ANGLE_D0 || autoRotation != VIPS_ANGLE_D0 ||
@ -102,18 +124,14 @@ class PipelineWorker : public Napi::AsyncWorker {
image = image.rot(autoRotation); image = image.rot(autoRotation);
autoRotation = VIPS_ANGLE_D0; autoRotation = VIPS_ANGLE_D0;
} }
if (autoFlip) { if (autoFlip != baton->flip) {
image = image.flip(VIPS_DIRECTION_VERTICAL); image = image.flip(VIPS_DIRECTION_VERTICAL);
autoFlip = false; autoFlip = false;
} else if (baton->flip) {
image = image.flip(VIPS_DIRECTION_VERTICAL);
baton->flip = false; baton->flip = false;
} }
if (autoFlop) { if (autoFlop != baton->flop) {
image = image.flip(VIPS_DIRECTION_HORIZONTAL); image = image.flip(VIPS_DIRECTION_HORIZONTAL);
autoFlop = false; autoFlop = false;
} else if (baton->flop) {
image = image.flip(VIPS_DIRECTION_HORIZONTAL);
baton->flop = false; baton->flop = false;
} }
if (rotation != VIPS_ANGLE_D0) { if (rotation != VIPS_ANGLE_D0) {
@ -223,11 +241,7 @@ class PipelineWorker : public Napi::AsyncWorker {
// factor for jpegload*, a double scale factor for webpload*, // factor for jpegload*, a double scale factor for webpload*,
// pdfload* and svgload* // pdfload* and svgload*
if (jpegShrinkOnLoad > 1) { if (jpegShrinkOnLoad > 1) {
vips::VOption *option = VImage::option() vips::VOption *option = GetOptionsForImageType(inputImageType, baton->input)->set("shrink", jpegShrinkOnLoad);
->set("access", access)
->set("shrink", jpegShrinkOnLoad)
->set("unlimited", baton->input->unlimited)
->set("fail_on", baton->input->failOn);
if (baton->input->buffer != nullptr) { if (baton->input->buffer != nullptr) {
// Reload JPEG buffer // Reload JPEG buffer
VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength); VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength);
@ -238,14 +252,8 @@ class PipelineWorker : public Napi::AsyncWorker {
image = VImage::jpegload(const_cast<char*>(baton->input->file.data()), option); image = VImage::jpegload(const_cast<char*>(baton->input->file.data()), option);
} }
} else if (scale != 1.0) { } else if (scale != 1.0) {
vips::VOption *option = VImage::option() vips::VOption *option = GetOptionsForImageType(inputImageType, baton->input)->set("scale", scale);
->set("access", access)
->set("scale", scale)
->set("fail_on", baton->input->failOn);
if (inputImageType == sharp::ImageType::WEBP) { if (inputImageType == sharp::ImageType::WEBP) {
option->set("n", baton->input->pages);
option->set("page", baton->input->page);
if (baton->input->buffer != nullptr) { if (baton->input->buffer != nullptr) {
// Reload WebP buffer // Reload WebP buffer
VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength); VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength);
@ -256,9 +264,6 @@ class PipelineWorker : public Napi::AsyncWorker {
image = VImage::webpload(const_cast<char*>(baton->input->file.data()), option); image = VImage::webpload(const_cast<char*>(baton->input->file.data()), option);
} }
} else if (inputImageType == sharp::ImageType::SVG) { } else if (inputImageType == sharp::ImageType::SVG) {
option->set("unlimited", baton->input->unlimited);
option->set("dpi", baton->input->density);
if (baton->input->buffer != nullptr) { if (baton->input->buffer != nullptr) {
// Reload SVG buffer // Reload SVG buffer
VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength); VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength);
@ -273,10 +278,6 @@ class PipelineWorker : public Napi::AsyncWorker {
throw vips::VError("Input SVG image will exceed 32767x32767 pixel limit when scaled"); throw vips::VError("Input SVG image will exceed 32767x32767 pixel limit when scaled");
} }
} else if (inputImageType == sharp::ImageType::PDF) { } else if (inputImageType == sharp::ImageType::PDF) {
option->set("n", baton->input->pages);
option->set("page", baton->input->page);
option->set("dpi", baton->input->density);
if (baton->input->buffer != nullptr) { if (baton->input->buffer != nullptr) {
// Reload PDF buffer // Reload PDF buffer
VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength); VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength);
@ -286,7 +287,6 @@ class PipelineWorker : public Napi::AsyncWorker {
// Reload PDF file // Reload PDF file
image = VImage::pdfload(const_cast<char*>(baton->input->file.data()), option); image = VImage::pdfload(const_cast<char*>(baton->input->file.data()), option);
} }
sharp::SetDensity(image, baton->input->density); sharp::SetDensity(image, baton->input->density);
} }
} else { } else {
@ -325,6 +325,7 @@ class PipelineWorker : public Napi::AsyncWorker {
if ((baton->keepMetadata & VIPS_FOREIGN_KEEP_ICC) && baton->withIccProfile.empty()) { if ((baton->keepMetadata & VIPS_FOREIGN_KEEP_ICC) && baton->withIccProfile.empty()) {
// Cache input profile for use with output // Cache input profile for use with output
inputProfile = sharp::GetProfile(image); inputProfile = sharp::GetProfile(image);
baton->input->ignoreIcc = true;
} }
char const *processingProfile = image.interpretation() == VIPS_INTERPRETATION_RGB16 ? "p3" : "srgb"; char const *processingProfile = image.interpretation() == VIPS_INTERPRETATION_RGB16 ? "p3" : "srgb";
if ( if (
@ -353,7 +354,7 @@ class PipelineWorker : public Napi::AsyncWorker {
} }
// Flatten image to remove alpha channel // Flatten image to remove alpha channel
if (baton->flatten && sharp::HasAlpha(image)) { if (baton->flatten && image.has_alpha()) {
image = sharp::Flatten(image, baton->flattenBackground); image = sharp::Flatten(image, baton->flattenBackground);
} }
@ -373,12 +374,12 @@ class PipelineWorker : public Napi::AsyncWorker {
bool const shouldSharpen = baton->sharpenSigma != 0.0; bool const shouldSharpen = baton->sharpenSigma != 0.0;
bool const shouldComposite = !baton->composite.empty(); bool const shouldComposite = !baton->composite.empty();
if (shouldComposite && !sharp::HasAlpha(image)) { if (shouldComposite && !image.has_alpha()) {
image = sharp::EnsureAlpha(image, 1); image = sharp::EnsureAlpha(image, 1);
} }
VipsBandFormat premultiplyFormat = image.format(); VipsBandFormat premultiplyFormat = image.format();
bool const shouldPremultiplyAlpha = sharp::HasAlpha(image) && bool const shouldPremultiplyAlpha = image.has_alpha() &&
(shouldResize || shouldBlur || shouldConv || shouldSharpen); (shouldResize || shouldBlur || shouldConv || shouldSharpen);
if (shouldPremultiplyAlpha) { if (shouldPremultiplyAlpha) {
@ -405,11 +406,11 @@ class PipelineWorker : public Napi::AsyncWorker {
image = image.rot(autoRotation); image = image.rot(autoRotation);
} }
// Mirror vertically (up-down) about the x-axis // Mirror vertically (up-down) about the x-axis
if (baton->flip || autoFlip) { if (baton->flip != autoFlip) {
image = image.flip(VIPS_DIRECTION_VERTICAL); image = image.flip(VIPS_DIRECTION_VERTICAL);
} }
// Mirror horizontally (left-right) about the y-axis // Mirror horizontally (left-right) about the y-axis
if (baton->flop || autoFlop) { if (baton->flop != autoFlop) {
image = image.flip(VIPS_DIRECTION_HORIZONTAL); image = image.flip(VIPS_DIRECTION_HORIZONTAL);
} }
// Rotate post-extract 90-angle // Rotate post-extract 90-angle
@ -590,9 +591,19 @@ class PipelineWorker : public Napi::AsyncWorker {
image = sharp::Threshold(image, baton->threshold, baton->thresholdGrayscale); image = sharp::Threshold(image, baton->threshold, baton->thresholdGrayscale);
} }
// Dilate - must happen before blurring, due to the utility of dilating after thresholding
if (baton->dilateWidth != 0) {
image = sharp::Dilate(image, baton->dilateWidth);
}
// Erode - must happen before blurring, due to the utility of eroding after thresholding
if (baton->erodeWidth != 0) {
image = sharp::Erode(image, baton->erodeWidth);
}
// Blur // Blur
if (shouldBlur) { if (shouldBlur) {
image = sharp::Blur(image, baton->blurSigma); image = sharp::Blur(image, baton->blurSigma, baton->precision, baton->minAmpl);
} }
// Unflatten the image // Unflatten the image
@ -609,7 +620,7 @@ class PipelineWorker : public Napi::AsyncWorker {
} }
// Recomb // Recomb
if (baton->recombMatrix != NULL) { if (!baton->recombMatrix.empty()) {
image = sharp::Recomb(image, baton->recombMatrix); image = sharp::Recomb(image, baton->recombMatrix);
} }
@ -639,7 +650,30 @@ class PipelineWorker : public Napi::AsyncWorker {
sharp::ImageType compositeImageType = sharp::ImageType::UNKNOWN; sharp::ImageType compositeImageType = sharp::ImageType::UNKNOWN;
composite->input->access = access; composite->input->access = access;
std::tie(compositeImage, compositeImageType) = sharp::OpenInput(composite->input); std::tie(compositeImage, compositeImageType) = sharp::OpenInput(composite->input);
compositeImage = sharp::EnsureColourspace(compositeImage, baton->colourspacePipeline);
if (composite->input->autoOrient) {
// Respect EXIF Orientation
VipsAngle compositeAutoRotation = VIPS_ANGLE_D0;
bool compositeAutoFlip = false;
bool compositeAutoFlop = false;
std::tie(compositeAutoRotation, compositeAutoFlip, compositeAutoFlop) =
CalculateExifRotationAndFlip(sharp::ExifOrientation(compositeImage));
compositeImage = sharp::RemoveExifOrientation(compositeImage);
compositeImage = sharp::StaySequential(compositeImage,
compositeAutoRotation != VIPS_ANGLE_D0 || compositeAutoFlip);
if (compositeAutoRotation != VIPS_ANGLE_D0) {
compositeImage = compositeImage.rot(compositeAutoRotation);
}
if (compositeAutoFlip) {
compositeImage = compositeImage.flip(VIPS_DIRECTION_VERTICAL);
}
if (compositeAutoFlop) {
compositeImage = compositeImage.flip(VIPS_DIRECTION_HORIZONTAL);
}
}
// Verify within current dimensions // Verify within current dimensions
if (compositeImage.width() > image.width() || compositeImage.height() > image.height()) { if (compositeImage.width() > image.width() || compositeImage.height() > image.height()) {
throw vips::VError("Image to composite must have same dimensions or smaller"); throw vips::VError("Image to composite must have same dimensions or smaller");
@ -680,11 +714,8 @@ class PipelineWorker : public Napi::AsyncWorker {
// gravity was used for extract_area, set it back to its default value of 0 // gravity was used for extract_area, set it back to its default value of 0
composite->gravity = 0; composite->gravity = 0;
} }
// Ensure image to composite is sRGB with unpremultiplied alpha // Ensure image to composite is with unpremultiplied alpha
compositeImage = compositeImage.colourspace(VIPS_INTERPRETATION_sRGB);
if (!sharp::HasAlpha(compositeImage)) {
compositeImage = sharp::EnsureAlpha(compositeImage, 1); compositeImage = sharp::EnsureAlpha(compositeImage, 1);
}
if (composite->premultiplied) compositeImage = compositeImage.unpremultiply(); if (composite->premultiplied) compositeImage = compositeImage.unpremultiply();
// Calculate position // Calculate position
int left; int left;
@ -708,7 +739,12 @@ class PipelineWorker : public Napi::AsyncWorker {
xs.push_back(left); xs.push_back(left);
ys.push_back(top); ys.push_back(top);
} }
image = VImage::composite(images, modes, VImage::option()->set("x", xs)->set("y", ys)); image = VImage::composite(images, modes, VImage::option()
->set("compositing_space", baton->colourspacePipeline == VIPS_INTERPRETATION_LAST
? VIPS_INTERPRETATION_sRGB
: baton->colourspacePipeline)
->set("x", xs)
->set("y", ys));
image = sharp::RemoveGifPalette(image); image = sharp::RemoveGifPalette(image);
} }
@ -785,7 +821,7 @@ class PipelineWorker : public Napi::AsyncWorker {
// Extract channel // Extract channel
if (baton->extractChannel > -1) { if (baton->extractChannel > -1) {
if (baton->extractChannel >= image.bands()) { if (baton->extractChannel >= image.bands()) {
if (baton->extractChannel == 3 && sharp::HasAlpha(image)) { if (baton->extractChannel == 3 && image.has_alpha()) {
baton->extractChannel = image.bands() - 1; baton->extractChannel = image.bands() - 1;
} else { } else {
(baton->err) (baton->err)
@ -840,7 +876,12 @@ class PipelineWorker : public Napi::AsyncWorker {
image.set(s.first.data(), s.second.data()); image.set(s.first.data(), s.second.data());
} }
} }
// XMP buffer
if ((baton->keepMetadata & VIPS_FOREIGN_KEEP_XMP) && !baton->withXmp.empty()) {
image = image.copy();
image.set(VIPS_META_XMP_NAME, nullptr,
const_cast<void*>(static_cast<void const*>(baton->withXmp.c_str())), baton->withXmp.size());
}
// Number of channels used in output image // Number of channels used in output image
baton->channels = image.bands(); baton->channels = image.bands();
baton->width = image.width(); baton->width = image.width();
@ -849,6 +890,11 @@ class PipelineWorker : public Napi::AsyncWorker {
image = sharp::SetAnimationProperties( image = sharp::SetAnimationProperties(
image, nPages, targetPageHeight, baton->delay, baton->loop); image, nPages, targetPageHeight, baton->delay, baton->loop);
if (image.get_typeof(VIPS_META_PAGE_HEIGHT) == G_TYPE_INT) {
baton->pageHeightOut = image.get_int(VIPS_META_PAGE_HEIGHT);
baton->pagesOut = image.get_int(VIPS_META_N_PAGES);
}
// Output // Output
sharp::SetTimeout(image, baton->timeoutSeconds); sharp::SetTimeout(image, baton->timeoutSeconds);
if (baton->fileOut.empty()) { if (baton->fileOut.empty()) {
@ -923,6 +969,7 @@ class PipelineWorker : public Napi::AsyncWorker {
->set("lossless", baton->webpLossless) ->set("lossless", baton->webpLossless)
->set("near_lossless", baton->webpNearLossless) ->set("near_lossless", baton->webpNearLossless)
->set("smart_subsample", baton->webpSmartSubsample) ->set("smart_subsample", baton->webpSmartSubsample)
->set("smart_deblock", baton->webpSmartDeblock)
->set("preset", baton->webpPreset) ->set("preset", baton->webpPreset)
->set("effort", baton->webpEffort) ->set("effort", baton->webpEffort)
->set("min_size", baton->webpMinSize) ->set("min_size", baton->webpMinSize)
@ -945,6 +992,7 @@ class PipelineWorker : public Napi::AsyncWorker {
->set("interlace", baton->gifProgressive) ->set("interlace", baton->gifProgressive)
->set("interframe_maxerror", baton->gifInterFrameMaxError) ->set("interframe_maxerror", baton->gifInterFrameMaxError)
->set("interpalette_maxerror", baton->gifInterPaletteMaxError) ->set("interpalette_maxerror", baton->gifInterPaletteMaxError)
->set("keep_duplicate_frames", baton->gifKeepDuplicateFrames)
->set("dither", baton->gifDither))); ->set("dither", baton->gifDither)));
baton->bufferOut = static_cast<char*>(area->data); baton->bufferOut = static_cast<char*>(area->data);
baton->bufferOutLength = area->length; baton->bufferOutLength = area->length;
@ -985,7 +1033,7 @@ class PipelineWorker : public Napi::AsyncWorker {
(baton->formatOut == "input" && inputImageType == sharp::ImageType::HEIF)) { (baton->formatOut == "input" && inputImageType == sharp::ImageType::HEIF)) {
// Write HEIF to buffer // Write HEIF to buffer
sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF); sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF);
image = sharp::RemoveAnimationProperties(image).cast(VIPS_FORMAT_UCHAR); image = sharp::RemoveAnimationProperties(image);
VipsArea *area = reinterpret_cast<VipsArea*>(image.heifsave_buffer(VImage::option() VipsArea *area = reinterpret_cast<VipsArea*>(image.heifsave_buffer(VImage::option()
->set("keep", baton->keepMetadata) ->set("keep", baton->keepMetadata)
->set("Q", baton->heifQuality) ->set("Q", baton->heifQuality)
@ -1003,7 +1051,7 @@ class PipelineWorker : public Napi::AsyncWorker {
} else if (baton->formatOut == "dz") { } else if (baton->formatOut == "dz") {
// Write DZ to buffer // Write DZ to buffer
baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP; baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP;
if (!sharp::HasAlpha(image)) { if (!image.has_alpha()) {
baton->tileBackground.pop_back(); baton->tileBackground.pop_back();
} }
image = sharp::StaySequential(image, baton->tileAngle != 0); image = sharp::StaySequential(image, baton->tileAngle != 0);
@ -1052,6 +1100,7 @@ class PipelineWorker : public Napi::AsyncWorker {
// Unsupported output format // Unsupported output format
(baton->err).append("Unsupported output format "); (baton->err).append("Unsupported output format ");
if (baton->formatOut == "input") { if (baton->formatOut == "input") {
(baton->err).append("when trying to match input format of ");
(baton->err).append(ImageTypeId(inputImageType)); (baton->err).append(ImageTypeId(inputImageType));
} else { } else {
(baton->err).append(baton->formatOut); (baton->err).append(baton->formatOut);
@ -1130,6 +1179,7 @@ class PipelineWorker : public Napi::AsyncWorker {
->set("lossless", baton->webpLossless) ->set("lossless", baton->webpLossless)
->set("near_lossless", baton->webpNearLossless) ->set("near_lossless", baton->webpNearLossless)
->set("smart_subsample", baton->webpSmartSubsample) ->set("smart_subsample", baton->webpSmartSubsample)
->set("smart_deblock", baton->webpSmartDeblock)
->set("preset", baton->webpPreset) ->set("preset", baton->webpPreset)
->set("effort", baton->webpEffort) ->set("effort", baton->webpEffort)
->set("min_size", baton->webpMinSize) ->set("min_size", baton->webpMinSize)
@ -1146,6 +1196,9 @@ class PipelineWorker : public Napi::AsyncWorker {
->set("effort", baton->gifEffort) ->set("effort", baton->gifEffort)
->set("reuse", baton->gifReuse) ->set("reuse", baton->gifReuse)
->set("interlace", baton->gifProgressive) ->set("interlace", baton->gifProgressive)
->set("interframe_maxerror", baton->gifInterFrameMaxError)
->set("interpalette_maxerror", baton->gifInterPaletteMaxError)
->set("keep_duplicate_frames", baton->gifKeepDuplicateFrames)
->set("dither", baton->gifDither)); ->set("dither", baton->gifDither));
baton->formatOut = "gif"; baton->formatOut = "gif";
} else if (baton->formatOut == "tiff" || (mightMatchInput && isTiff) || } else if (baton->formatOut == "tiff" || (mightMatchInput && isTiff) ||
@ -1178,7 +1231,7 @@ class PipelineWorker : public Napi::AsyncWorker {
(willMatchInput && inputImageType == sharp::ImageType::HEIF)) { (willMatchInput && inputImageType == sharp::ImageType::HEIF)) {
// Write HEIF to file // Write HEIF to file
sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF); sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF);
image = sharp::RemoveAnimationProperties(image).cast(VIPS_FORMAT_UCHAR); image = sharp::RemoveAnimationProperties(image);
image.heifsave(const_cast<char*>(baton->fileOut.data()), VImage::option() image.heifsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
->set("keep", baton->keepMetadata) ->set("keep", baton->keepMetadata)
->set("Q", baton->heifQuality) ->set("Q", baton->heifQuality)
@ -1205,7 +1258,7 @@ class PipelineWorker : public Napi::AsyncWorker {
if (isDzZip) { if (isDzZip) {
baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP; baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP;
} }
if (!sharp::HasAlpha(image)) { if (!image.has_alpha()) {
baton->tileBackground.pop_back(); baton->tileBackground.pop_back();
} }
image = sharp::StaySequential(image, baton->tileAngle != 0); image = sharp::StaySequential(image, baton->tileAngle != 0);
@ -1284,6 +1337,10 @@ class PipelineWorker : public Napi::AsyncWorker {
if (baton->input->textAutofitDpi) { if (baton->input->textAutofitDpi) {
info.Set("textAutofitDpi", static_cast<uint32_t>(baton->input->textAutofitDpi)); info.Set("textAutofitDpi", static_cast<uint32_t>(baton->input->textAutofitDpi));
} }
if (baton->pageHeightOut) {
info.Set("pageHeight", static_cast<int32_t>(baton->pageHeightOut));
info.Set("pages", static_cast<int32_t>(baton->pagesOut));
}
if (baton->bufferOutLength > 0) { if (baton->bufferOutLength > 0) {
// Add buffer size to info // Add buffer size to info
@ -1294,9 +1351,12 @@ class PipelineWorker : public Napi::AsyncWorker {
Callback().Call(Receiver().Value(), { env.Null(), data, info }); Callback().Call(Receiver().Value(), { env.Null(), data, info });
} else { } else {
// Add file size to info // Add file size to info
struct STAT64_STRUCT st; if (baton->formatOut != "dz" || sharp::IsDzZip(baton->fileOut)) {
if (STAT64_FUNCTION(baton->fileOut.data(), &st) == 0) { try {
info.Set("size", static_cast<uint32_t>(st.st_size)); uint32_t const size = static_cast<uint32_t>(
std::filesystem::file_size(std::filesystem::u8path(baton->fileOut)));
info.Set("size", size);
} catch (...) {}
} }
Callback().Call(Receiver().Value(), { env.Null(), info }); Callback().Call(Receiver().Value(), { env.Null(), info });
} }
@ -1314,6 +1374,9 @@ class PipelineWorker : public Napi::AsyncWorker {
for (sharp::InputDescriptor *input : baton->joinChannelIn) { for (sharp::InputDescriptor *input : baton->joinChannelIn) {
delete input; delete input;
} }
for (sharp::InputDescriptor *input : baton->join) {
delete input;
}
delete baton; delete baton;
// Decrement processing task counter // Decrement processing task counter
@ -1409,6 +1472,7 @@ class PipelineWorker : public Napi::AsyncWorker {
{"lossless", baton->webpLossless ? "true" : "false"}, {"lossless", baton->webpLossless ? "true" : "false"},
{"near_lossless", baton->webpNearLossless ? "true" : "false"}, {"near_lossless", baton->webpNearLossless ? "true" : "false"},
{"smart_subsample", baton->webpSmartSubsample ? "true" : "false"}, {"smart_subsample", baton->webpSmartSubsample ? "true" : "false"},
{"smart_deblock", baton->webpSmartDeblock ? "true" : "false"},
{"preset", vips_enum_nick(VIPS_TYPE_FOREIGN_WEBP_PRESET, baton->webpPreset)}, {"preset", vips_enum_nick(VIPS_TYPE_FOREIGN_WEBP_PRESET, baton->webpPreset)},
{"min_size", baton->webpMinSize ? "true" : "false"}, {"min_size", baton->webpMinSize ? "true" : "false"},
{"mixed", baton->webpMixed ? "true" : "false"}, {"mixed", baton->webpMixed ? "true" : "false"},
@ -1470,6 +1534,14 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
// Input // Input
baton->input = sharp::CreateInputDescriptor(options.Get("input").As<Napi::Object>()); baton->input = sharp::CreateInputDescriptor(options.Get("input").As<Napi::Object>());
// Join images together
if (sharp::HasAttr(options, "join")) {
Napi::Array join = options.Get("join").As<Napi::Array>();
for (unsigned int i = 0; i < join.Length(); i++) {
baton->join.push_back(
sharp::CreateInputDescriptor(join.Get(i).As<Napi::Object>()));
}
}
// Extract image options // Extract image options
baton->topOffsetPre = sharp::AttrAsInt32(options, "topOffsetPre"); baton->topOffsetPre = sharp::AttrAsInt32(options, "topOffsetPre");
baton->leftOffsetPre = sharp::AttrAsInt32(options, "leftOffsetPre"); baton->leftOffsetPre = sharp::AttrAsInt32(options, "leftOffsetPre");
@ -1532,6 +1604,8 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
baton->negate = sharp::AttrAsBool(options, "negate"); baton->negate = sharp::AttrAsBool(options, "negate");
baton->negateAlpha = sharp::AttrAsBool(options, "negateAlpha"); baton->negateAlpha = sharp::AttrAsBool(options, "negateAlpha");
baton->blurSigma = sharp::AttrAsDouble(options, "blurSigma"); baton->blurSigma = sharp::AttrAsDouble(options, "blurSigma");
baton->precision = sharp::AttrAsEnum<VipsPrecision>(options, "precision", VIPS_TYPE_PRECISION);
baton->minAmpl = sharp::AttrAsDouble(options, "minAmpl");
baton->brightness = sharp::AttrAsDouble(options, "brightness"); baton->brightness = sharp::AttrAsDouble(options, "brightness");
baton->saturation = sharp::AttrAsDouble(options, "saturation"); baton->saturation = sharp::AttrAsDouble(options, "saturation");
baton->hue = sharp::AttrAsInt32(options, "hue"); baton->hue = sharp::AttrAsInt32(options, "hue");
@ -1552,6 +1626,8 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
baton->gammaOut = sharp::AttrAsDouble(options, "gammaOut"); baton->gammaOut = sharp::AttrAsDouble(options, "gammaOut");
baton->linearA = sharp::AttrAsVectorOfDouble(options, "linearA"); baton->linearA = sharp::AttrAsVectorOfDouble(options, "linearA");
baton->linearB = sharp::AttrAsVectorOfDouble(options, "linearB"); baton->linearB = sharp::AttrAsVectorOfDouble(options, "linearB");
baton->dilateWidth = sharp::AttrAsUint32(options, "dilateWidth");
baton->erodeWidth = sharp::AttrAsUint32(options, "erodeWidth");
baton->greyscale = sharp::AttrAsBool(options, "greyscale"); baton->greyscale = sharp::AttrAsBool(options, "greyscale");
baton->normalise = sharp::AttrAsBool(options, "normalise"); baton->normalise = sharp::AttrAsBool(options, "normalise");
baton->normaliseLower = sharp::AttrAsUint32(options, "normaliseLower"); baton->normaliseLower = sharp::AttrAsUint32(options, "normaliseLower");
@ -1560,7 +1636,6 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
baton->claheWidth = sharp::AttrAsUint32(options, "claheWidth"); baton->claheWidth = sharp::AttrAsUint32(options, "claheWidth");
baton->claheHeight = sharp::AttrAsUint32(options, "claheHeight"); baton->claheHeight = sharp::AttrAsUint32(options, "claheHeight");
baton->claheMaxSlope = sharp::AttrAsUint32(options, "claheMaxSlope"); baton->claheMaxSlope = sharp::AttrAsUint32(options, "claheMaxSlope");
baton->useExifOrientation = sharp::AttrAsBool(options, "useExifOrientation");
baton->angle = sharp::AttrAsInt32(options, "angle"); baton->angle = sharp::AttrAsInt32(options, "angle");
baton->rotationAngle = sharp::AttrAsDouble(options, "rotationAngle"); baton->rotationAngle = sharp::AttrAsDouble(options, "rotationAngle");
baton->rotationBackground = sharp::AttrAsVectorOfDouble(options, "rotationBackground"); baton->rotationBackground = sharp::AttrAsVectorOfDouble(options, "rotationBackground");
@ -1597,16 +1672,17 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
baton->convKernelScale = sharp::AttrAsDouble(kernel, "scale"); baton->convKernelScale = sharp::AttrAsDouble(kernel, "scale");
baton->convKernelOffset = sharp::AttrAsDouble(kernel, "offset"); baton->convKernelOffset = sharp::AttrAsDouble(kernel, "offset");
size_t const kernelSize = static_cast<size_t>(baton->convKernelWidth * baton->convKernelHeight); size_t const kernelSize = static_cast<size_t>(baton->convKernelWidth * baton->convKernelHeight);
baton->convKernel = std::unique_ptr<double[]>(new double[kernelSize]); baton->convKernel.resize(kernelSize);
Napi::Array kdata = kernel.Get("kernel").As<Napi::Array>(); Napi::Array kdata = kernel.Get("kernel").As<Napi::Array>();
for (unsigned int i = 0; i < kernelSize; i++) { for (unsigned int i = 0; i < kernelSize; i++) {
baton->convKernel[i] = sharp::AttrAsDouble(kdata, i); baton->convKernel[i] = sharp::AttrAsDouble(kdata, i);
} }
} }
if (options.Has("recombMatrix")) { if (options.Has("recombMatrix")) {
baton->recombMatrix = std::unique_ptr<double[]>(new double[9]);
Napi::Array recombMatrix = options.Get("recombMatrix").As<Napi::Array>(); Napi::Array recombMatrix = options.Get("recombMatrix").As<Napi::Array>();
for (unsigned int i = 0; i < 9; i++) { unsigned int matrixElements = recombMatrix.Length();
baton->recombMatrix.resize(matrixElements);
for (unsigned int i = 0; i < matrixElements; i++) {
baton->recombMatrix[i] = sharp::AttrAsDouble(recombMatrix, i); baton->recombMatrix[i] = sharp::AttrAsDouble(recombMatrix, i);
} }
} }
@ -1635,7 +1711,10 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
} }
} }
baton->withExifMerge = sharp::AttrAsBool(options, "withExifMerge"); baton->withExifMerge = sharp::AttrAsBool(options, "withExifMerge");
baton->withXmp = sharp::AttrAsStr(options, "withXmp");
baton->timeoutSeconds = sharp::AttrAsUint32(options, "timeoutSeconds"); baton->timeoutSeconds = sharp::AttrAsUint32(options, "timeoutSeconds");
baton->loop = sharp::AttrAsUint32(options, "loop");
baton->delay = sharp::AttrAsInt32Vector(options, "delay");
// Format-specific // Format-specific
baton->jpegQuality = sharp::AttrAsUint32(options, "jpegQuality"); baton->jpegQuality = sharp::AttrAsUint32(options, "jpegQuality");
baton->jpegProgressive = sharp::AttrAsBool(options, "jpegProgressive"); baton->jpegProgressive = sharp::AttrAsBool(options, "jpegProgressive");
@ -1663,6 +1742,7 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
baton->webpLossless = sharp::AttrAsBool(options, "webpLossless"); baton->webpLossless = sharp::AttrAsBool(options, "webpLossless");
baton->webpNearLossless = sharp::AttrAsBool(options, "webpNearLossless"); baton->webpNearLossless = sharp::AttrAsBool(options, "webpNearLossless");
baton->webpSmartSubsample = sharp::AttrAsBool(options, "webpSmartSubsample"); baton->webpSmartSubsample = sharp::AttrAsBool(options, "webpSmartSubsample");
baton->webpSmartDeblock = sharp::AttrAsBool(options, "webpSmartDeblock");
baton->webpPreset = sharp::AttrAsEnum<VipsForeignWebpPreset>(options, "webpPreset", VIPS_TYPE_FOREIGN_WEBP_PRESET); baton->webpPreset = sharp::AttrAsEnum<VipsForeignWebpPreset>(options, "webpPreset", VIPS_TYPE_FOREIGN_WEBP_PRESET);
baton->webpEffort = sharp::AttrAsUint32(options, "webpEffort"); baton->webpEffort = sharp::AttrAsUint32(options, "webpEffort");
baton->webpMinSize = sharp::AttrAsBool(options, "webpMinSize"); baton->webpMinSize = sharp::AttrAsBool(options, "webpMinSize");
@ -1672,6 +1752,7 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
baton->gifDither = sharp::AttrAsDouble(options, "gifDither"); baton->gifDither = sharp::AttrAsDouble(options, "gifDither");
baton->gifInterFrameMaxError = sharp::AttrAsDouble(options, "gifInterFrameMaxError"); baton->gifInterFrameMaxError = sharp::AttrAsDouble(options, "gifInterFrameMaxError");
baton->gifInterPaletteMaxError = sharp::AttrAsDouble(options, "gifInterPaletteMaxError"); baton->gifInterPaletteMaxError = sharp::AttrAsDouble(options, "gifInterPaletteMaxError");
baton->gifKeepDuplicateFrames = sharp::AttrAsBool(options, "gifKeepDuplicateFrames");
baton->gifReuse = sharp::AttrAsBool(options, "gifReuse"); baton->gifReuse = sharp::AttrAsBool(options, "gifReuse");
baton->gifProgressive = sharp::AttrAsBool(options, "gifProgressive"); baton->gifProgressive = sharp::AttrAsBool(options, "gifProgressive");
baton->tiffQuality = sharp::AttrAsUint32(options, "tiffQuality"); baton->tiffQuality = sharp::AttrAsUint32(options, "tiffQuality");
@ -1704,13 +1785,6 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
baton->jxlEffort = sharp::AttrAsUint32(options, "jxlEffort"); baton->jxlEffort = sharp::AttrAsUint32(options, "jxlEffort");
baton->jxlLossless = sharp::AttrAsBool(options, "jxlLossless"); baton->jxlLossless = sharp::AttrAsBool(options, "jxlLossless");
baton->rawDepth = sharp::AttrAsEnum<VipsBandFormat>(options, "rawDepth", VIPS_TYPE_BAND_FORMAT); baton->rawDepth = sharp::AttrAsEnum<VipsBandFormat>(options, "rawDepth", VIPS_TYPE_BAND_FORMAT);
// Animated output properties
if (sharp::HasAttr(options, "loop")) {
baton->loop = sharp::AttrAsUint32(options, "loop");
}
if (sharp::HasAttr(options, "delay")) {
baton->delay = sharp::AttrAsInt32Vector(options, "delay");
}
baton->tileSize = sharp::AttrAsUint32(options, "tileSize"); baton->tileSize = sharp::AttrAsUint32(options, "tileSize");
baton->tileOverlap = sharp::AttrAsUint32(options, "tileOverlap"); baton->tileOverlap = sharp::AttrAsUint32(options, "tileOverlap");
baton->tileAngle = sharp::AttrAsInt32(options, "tileAngle"); baton->tileAngle = sharp::AttrAsInt32(options, "tileAngle");

View File

@ -39,10 +39,13 @@ struct Composite {
struct PipelineBaton { struct PipelineBaton {
sharp::InputDescriptor *input; sharp::InputDescriptor *input;
std::vector<sharp::InputDescriptor *> join;
std::string formatOut; std::string formatOut;
std::string fileOut; std::string fileOut;
void *bufferOut; void *bufferOut;
size_t bufferOutLength; size_t bufferOutLength;
int pageHeightOut;
int pagesOut;
std::vector<Composite *> composite; std::vector<Composite *> composite;
std::vector<sharp::InputDescriptor *> joinChannelIn; std::vector<sharp::InputDescriptor *> joinChannelIn;
int topOffsetPre; int topOffsetPre;
@ -76,6 +79,8 @@ struct PipelineBaton {
bool negate; bool negate;
bool negateAlpha; bool negateAlpha;
double blurSigma; double blurSigma;
VipsPrecision precision;
double minAmpl;
double brightness; double brightness;
double saturation; double saturation;
int hue; int hue;
@ -96,6 +101,8 @@ struct PipelineBaton {
int trimOffsetTop; int trimOffsetTop;
std::vector<double> linearA; std::vector<double> linearA;
std::vector<double> linearB; std::vector<double> linearB;
int dilateWidth;
int erodeWidth;
double gamma; double gamma;
double gammaOut; double gammaOut;
bool greyscale; bool greyscale;
@ -105,7 +112,6 @@ struct PipelineBaton {
int claheWidth; int claheWidth;
int claheHeight; int claheHeight;
int claheMaxSlope; int claheMaxSlope;
bool useExifOrientation;
int angle; int angle;
double rotationAngle; double rotationAngle;
std::vector<double> rotationBackground; std::vector<double> rotationBackground;
@ -153,6 +159,7 @@ struct PipelineBaton {
bool webpNearLossless; bool webpNearLossless;
bool webpLossless; bool webpLossless;
bool webpSmartSubsample; bool webpSmartSubsample;
bool webpSmartDeblock;
VipsForeignWebpPreset webpPreset; VipsForeignWebpPreset webpPreset;
int webpEffort; int webpEffort;
bool webpMinSize; bool webpMinSize;
@ -162,6 +169,7 @@ struct PipelineBaton {
double gifDither; double gifDither;
double gifInterFrameMaxError; double gifInterFrameMaxError;
double gifInterPaletteMaxError; double gifInterPaletteMaxError;
bool gifKeepDuplicateFrames;
bool gifReuse; bool gifReuse;
bool gifProgressive; bool gifProgressive;
int tiffQuality; int tiffQuality;
@ -194,8 +202,9 @@ struct PipelineBaton {
std::string withIccProfile; std::string withIccProfile;
std::unordered_map<std::string, std::string> withExif; std::unordered_map<std::string, std::string> withExif;
bool withExifMerge; bool withExifMerge;
std::string withXmp;
int timeoutSeconds; int timeoutSeconds;
std::unique_ptr<double[]> convKernel; std::vector<double> convKernel;
int convKernelWidth; int convKernelWidth;
int convKernelHeight; int convKernelHeight;
double convKernelScale; double convKernelScale;
@ -221,11 +230,13 @@ struct PipelineBaton {
VipsForeignDzDepth tileDepth; VipsForeignDzDepth tileDepth;
std::string tileId; std::string tileId;
std::string tileBasename; std::string tileBasename;
std::unique_ptr<double[]> recombMatrix; std::vector<double> recombMatrix;
PipelineBaton(): PipelineBaton():
input(nullptr), input(nullptr),
bufferOutLength(0), bufferOutLength(0),
pageHeightOut(0),
pagesOut(0),
topOffsetPre(-1), topOffsetPre(-1),
topOffsetPost(-1), topOffsetPost(-1),
channels(0), channels(0),
@ -267,6 +278,8 @@ struct PipelineBaton {
trimOffsetTop(0), trimOffsetTop(0),
linearA{}, linearA{},
linearB{}, linearB{},
dilateWidth(0),
erodeWidth(0),
gamma(0.0), gamma(0.0),
greyscale(false), greyscale(false),
normalise(false), normalise(false),
@ -275,7 +288,6 @@ struct PipelineBaton {
claheWidth(0), claheWidth(0),
claheHeight(0), claheHeight(0),
claheMaxSlope(3), claheMaxSlope(3),
useExifOrientation(false),
angle(0), angle(0),
rotationAngle(0.0), rotationAngle(0.0),
rotationBackground{ 0.0, 0.0, 0.0, 255.0 }, rotationBackground{ 0.0, 0.0, 0.0, 255.0 },
@ -322,6 +334,7 @@ struct PipelineBaton {
webpNearLossless(false), webpNearLossless(false),
webpLossless(false), webpLossless(false),
webpSmartSubsample(false), webpSmartSubsample(false),
webpSmartDeblock(false),
webpPreset(VIPS_FOREIGN_WEBP_PRESET_DEFAULT), webpPreset(VIPS_FOREIGN_WEBP_PRESET_DEFAULT),
webpEffort(4), webpEffort(4),
webpMinSize(false), webpMinSize(false),
@ -331,6 +344,7 @@ struct PipelineBaton {
gifDither(1.0), gifDither(1.0),
gifInterFrameMaxError(0.0), gifInterFrameMaxError(0.0),
gifInterPaletteMaxError(3.0), gifInterPaletteMaxError(3.0),
gifKeepDuplicateFrames(false),
gifReuse(true), gifReuse(true),
gifProgressive(false), gifProgressive(false),
tiffQuality(80), tiffQuality(80),

View File

@ -18,8 +18,10 @@ Napi::Object init(Napi::Env env, Napi::Object exports) {
vips_init("sharp"); vips_init("sharp");
}); });
g_log_set_handler("VIPS", static_cast<GLogLevelFlags>(G_LOG_LEVEL_WARNING), for (auto domain : { "VIPS", "vips2tiff" }) {
g_log_set_handler(domain, static_cast<GLogLevelFlags>(G_LOG_LEVEL_WARNING),
static_cast<GLogFunc>(sharp::VipsWarningCallback), nullptr); static_cast<GLogFunc>(sharp::VipsWarningCallback), nullptr);
}
// Methods available to JavaScript // Methods available to JavaScript
exports.Set("metadata", Napi::Function::New(env, metadata)); exports.Set("metadata", Napi::Function::New(env, metadata));
@ -33,6 +35,7 @@ Napi::Object init(Napi::Env env, Napi::Object exports) {
exports.Set("block", Napi::Function::New(env, block)); exports.Set("block", Napi::Function::New(env, block));
exports.Set("_maxColourDistance", Napi::Function::New(env, _maxColourDistance)); exports.Set("_maxColourDistance", Napi::Function::New(env, _maxColourDistance));
exports.Set("_isUsingJemalloc", Napi::Function::New(env, _isUsingJemalloc)); exports.Set("_isUsingJemalloc", Napi::Function::New(env, _isUsingJemalloc));
exports.Set("_isUsingX64V2", Napi::Function::New(env, _isUsingX64V2));
exports.Set("stats", Napi::Function::New(env, stats)); exports.Set("stats", Napi::Function::New(env, stats));
return exports; return exports;
} }

View File

@ -58,9 +58,9 @@ class StatsWorker : public Napi::AsyncWorker {
baton->channelStats.push_back(cStats); baton->channelStats.push_back(cStats);
} }
// Image is not opaque when alpha layer is present and contains a non-mamixa value // Image is not opaque when alpha layer is present and contains a non-mamixa value
if (sharp::HasAlpha(image)) { if (image.has_alpha()) {
double const minAlpha = static_cast<double>(stats.getpoint(STAT_MIN_INDEX, bands).front()); double const minAlpha = static_cast<double>(stats.getpoint(STAT_MIN_INDEX, bands).front());
if (minAlpha != sharp::MaximumImageAlpha(image.interpretation())) { if (minAlpha != vips_interpretation_max_alpha(image.interpretation())) {
baton->isOpaque = false; baton->isOpaque = false;
} }
} }

View File

@ -119,7 +119,7 @@ Napi::Value format(const Napi::CallbackInfo& info) {
Napi::Object format = Napi::Object::New(env); Napi::Object format = Napi::Object::New(env);
for (std::string const f : { for (std::string const f : {
"jpeg", "png", "webp", "tiff", "magick", "openslide", "dz", "jpeg", "png", "webp", "tiff", "magick", "openslide", "dz",
"ppm", "fits", "gif", "svg", "heif", "pdf", "vips", "jp2k", "jxl" "ppm", "fits", "gif", "svg", "heif", "pdf", "vips", "jp2k", "jxl", "rad", "dcraw"
}) { }) {
// Input // Input
const VipsObjectClass *oc = vips_class_find("VipsOperation", (f + "load").c_str()); const VipsObjectClass *oc = vips_class_find("VipsOperation", (f + "load").c_str());
@ -233,10 +233,10 @@ Napi::Value _maxColourDistance(const Napi::CallbackInfo& info) {
double maxColourDistance; double maxColourDistance;
try { try {
// Premultiply and remove alpha // Premultiply and remove alpha
if (sharp::HasAlpha(image1)) { if (image1.has_alpha()) {
image1 = image1.premultiply().extract_band(1, VImage::option()->set("n", image1.bands() - 1)); image1 = image1.premultiply().extract_band(1, VImage::option()->set("n", image1.bands() - 1));
} }
if (sharp::HasAlpha(image2)) { if (image2.has_alpha()) {
image2 = image2.premultiply().extract_band(1, VImage::option()->set("n", image2.bands() - 1)); image2 = image2.premultiply().extract_band(1, VImage::option()->set("n", image2.bands() - 1));
} }
// Calculate colour distance // Calculate colour distance
@ -267,3 +267,20 @@ Napi::Value _isUsingJemalloc(const Napi::CallbackInfo& info) {
return Napi::Boolean::New(env, false); return Napi::Boolean::New(env, false);
} }
#endif #endif
#if defined(__GNUC__) && defined(__x86_64__)
// Are SSE 4.2 intrinsics available at runtime?
Napi::Value _isUsingX64V2(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
unsigned int eax, ebx, ecx, edx;
__asm__ __volatile__("cpuid"
: "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx)
: "a"(1));
return Napi::Boolean::New(env, (ecx & 1U << 20) != 0);
}
#else
Napi::Value _isUsingX64V2(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
return Napi::Boolean::New(env, false);
}
#endif

View File

@ -15,5 +15,6 @@ Napi::Value format(const Napi::CallbackInfo& info);
void block(const Napi::CallbackInfo& info); void block(const Napi::CallbackInfo& info);
Napi::Value _maxColourDistance(const Napi::CallbackInfo& info); Napi::Value _maxColourDistance(const Napi::CallbackInfo& info);
Napi::Value _isUsingJemalloc(const Napi::CallbackInfo& info); Napi::Value _isUsingJemalloc(const Napi::CallbackInfo& info);
Napi::Value _isUsingX64V2(const Napi::CallbackInfo& info);
#endif // SRC_UTILITIES_H_ #endif // SRC_UTILITIES_H_

View File

@ -1,14 +1,13 @@
FROM ubuntu:23.10 FROM ubuntu:25.04
ARG BRANCH=main ARG BRANCH=main
# Install basic dependencies # Install basic dependencies
RUN apt-get -y update && apt-get install -y build-essential curl git ca-certificates gnupg RUN apt-get -y update && apt-get install -y build-essential curl git ca-certificates gnupg
# Install latest Node.js LTS # Install latest Node.js LTS
RUN mkdir -p /etc/apt/keyrings RUN curl -fsSL https://deb.nodesource.com/setup_24.x -o nodesource_setup.sh
RUN curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg RUN bash nodesource_setup.sh
RUN echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_20.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list RUN apt-get install -y nodejs
RUN apt-get -y update && apt-get install -y nodejs
# Install benchmark dependencies # Install benchmark dependencies
RUN apt-get install -y imagemagick libmagick++-dev graphicsmagick RUN apt-get install -y imagemagick libmagick++-dev graphicsmagick
@ -26,8 +25,4 @@ RUN node -v
WORKDIR /tmp/sharp/test/bench WORKDIR /tmp/sharp/test/bench
# Workaround for: https://github.com/emscripten-core/emscripten/pull/16917
# This could be removed once Squoosh is an optional dependency.
ENV NODE_OPTIONS="--no-experimental-fetch"
CMD [ "node", "perf" ] CMD [ "node", "perf" ]

View File

@ -8,16 +8,14 @@
"test": "node perf && node random && node parallel" "test": "node perf && node random && node parallel"
}, },
"dependencies": { "dependencies": {
"@squoosh/cli": "0.7.3", "async": "3.2.6",
"@squoosh/lib": "0.5.3",
"async": "3.2.5",
"benchmark": "2.1.4", "benchmark": "2.1.4",
"gm": "1.25.0", "gm": "1.25.1",
"imagemagick": "0.1.3", "imagemagick": "0.1.3",
"jimp": "0.22.10" "jimp": "1.6.0"
}, },
"optionalDependencies": { "optionalDependencies": {
"@tensorflow/tfjs-node": "4.13.0", "@tensorflow/tfjs-node": "4.22.0",
"mapnik": "4.5.9" "mapnik": "4.5.9"
}, },
"license": "Apache-2.0" "license": "Apache-2.0"

View File

@ -15,7 +15,6 @@ const width = 720;
const height = 480; const height = 480;
sharp.concurrency(1); sharp.concurrency(1);
sharp.simd(true);
const timer = setInterval(function () { const timer = setInterval(function () {
console.dir(sharp.counters()); console.dir(sharp.counters());

View File

@ -3,9 +3,8 @@
'use strict'; 'use strict';
const os = require('os');
const fs = require('fs'); const fs = require('fs');
const { exec, execSync } = require('child_process'); const { execSync } = require('child_process');
const async = require('async'); const async = require('async');
const Benchmark = require('benchmark'); const Benchmark = require('benchmark');
@ -22,8 +21,8 @@ const sharp = require('../../');
const gm = require('gm'); const gm = require('gm');
const imagemagick = require('imagemagick'); const imagemagick = require('imagemagick');
const mapnik = safeRequire('mapnik'); const mapnik = safeRequire('mapnik');
const jimp = require('jimp'); const { Jimp, JimpMime } = require('jimp');
const squoosh = require('@squoosh/lib');
process.env.TF_CPP_MIN_LOG_LEVEL = 1; process.env.TF_CPP_MIN_LOG_LEVEL = 1;
const tfjs = safeRequire('@tensorflow/tfjs-node'); const tfjs = safeRequire('@tensorflow/tfjs-node');
@ -52,104 +51,23 @@ async.series({
// jimp // jimp
jpegSuite.add('jimp-buffer-buffer', { jpegSuite.add('jimp-buffer-buffer', {
defer: true, defer: true,
fn: function (deferred) { fn: async function (deferred) {
jimp.read(inputJpgBuffer, function (err, image) { const image = await Jimp.read(inputJpgBuffer);
if (err) { await image
throw err; .resize({ w: width, h: height, mode: Jimp.RESIZE_BICUBIC })
} else { .getBuffer(JimpMime.jpeg, { quality: 80 });
image
.resize(width, height, jimp.RESIZE_BICUBIC)
.quality(80)
.getBuffer(jimp.MIME_JPEG, function (err) {
if (err) {
throw err;
} else {
deferred.resolve(); deferred.resolve();
} }
});
}
});
}
}).add('jimp-file-file', { }).add('jimp-file-file', {
defer: true, defer: true,
fn: function (deferred) { fn: async function (deferred) {
jimp.read(fixtures.inputJpg, function (err, image) { const image = await Jimp.read(fixtures.inputJpg);
if (err) { await image
throw err; .resize({ w: width, h: height, mode: Jimp.RESIZE_BICUBIC })
} else { .getBuffer(JimpMime.jpeg, { quality: 80 });
image
.resize(width, height, jimp.RESIZE_BICUBIC)
.quality(80)
.write(outputJpg, function (err) {
if (err) {
throw err;
} else {
deferred.resolve(); deferred.resolve();
} }
}); });
}
});
}
});
// squoosh-cli
jpegSuite.add('squoosh-cli-file-file', {
defer: true,
fn: function (deferred) {
exec(`./node_modules/.bin/squoosh-cli \
--output-dir ${os.tmpdir()} \
--resize '{"enabled":true,"width":${width},"height":${height},"method":"lanczos3","premultiply":false,"linearRGB":false}' \
--mozjpeg '{"quality":80,"progressive":false,"optimize_coding":true,"quant_table":0,"trellis_multipass":false,"chroma_subsample":2,"separate_chroma_quality":false}' \
"${fixtures.inputJpg}"`, function (err) {
if (err) {
throw err;
}
deferred.resolve();
});
}
});
// squoosh-lib (GPLv3)
jpegSuite.add('squoosh-lib-buffer-buffer', {
defer: true,
fn: function (deferred) {
const pool = new squoosh.ImagePool(os.cpus().length);
const image = pool.ingestImage(inputJpgBuffer);
image.decoded
.then(function () {
return image.preprocess({
resize: {
enabled: true,
width,
height,
method: 'lanczos3',
premultiply: false,
linearRGB: false
}
});
})
.then(function () {
return image.encode({
mozjpeg: {
quality: 80,
progressive: false,
optimize_coding: true,
quant_table: 0,
trellis_multipass: false,
chroma_subsample: 2,
separate_chroma_quality: false
}
});
})
.then(function () {
return pool.close();
})
.then(function () {
return image.encodedWith.mozjpeg;
})
.then(function () {
deferred.resolve();
});
}
});
// mapnik // mapnik
mapnik && jpegSuite.add('mapnik-file-file', { mapnik && jpegSuite.add('mapnik-file-file', {
defer: true, defer: true,
@ -634,6 +552,32 @@ async.series({
} }
}); });
} }
}).add('sharp-mks2013', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height, { kernel: 'mks2013' })
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-mks2021', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height, { kernel: 'mks2021' })
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).on('cycle', function (event) { }).on('cycle', function (event) {
console.log('kernels ' + String(event.target)); console.log('kernels ' + String(event.target));
}).on('complete', function () { }).on('complete', function () {
@ -648,100 +592,23 @@ async.series({
// jimp // jimp
pngSuite.add('jimp-buffer-buffer', { pngSuite.add('jimp-buffer-buffer', {
defer: true, defer: true,
fn: function (deferred) { fn: async function (deferred) {
jimp.read(inputPngBuffer, function (err, image) { const image = await Jimp.read(inputPngBuffer);
if (err) { await image
throw err; .resize({ w: width, h: heightPng, mode: Jimp.RESIZE_BICUBIC })
} else { .getBuffer(JimpMime.png, { deflateLevel: 6, filterType: 0 });
image
.resize(width, heightPng, jimp.RESIZE_BICUBIC)
.deflateLevel(6)
.filterType(0)
.getBuffer(jimp.MIME_PNG, function (err) {
if (err) {
throw err;
} else {
deferred.resolve(); deferred.resolve();
} }
});
}
});
}
}).add('jimp-file-file', { }).add('jimp-file-file', {
defer: true, defer: true,
fn: function (deferred) { fn: async function (deferred) {
jimp.read(fixtures.inputPngAlphaPremultiplicationLarge, function (err, image) { const image = await Jimp.read(fixtures.inputPngAlphaPremultiplicationLarge);
if (err) { await image
throw err; .resize({ w: width, h: heightPng, mode: Jimp.RESIZE_BICUBIC })
} else { .write(outputPng, { deflateLevel: 6, filterType: 0 });
image
.resize(width, heightPng, jimp.RESIZE_BICUBIC)
.deflateLevel(6)
.filterType(0)
.write(outputPng, function (err) {
if (err) {
throw err;
} else {
deferred.resolve(); deferred.resolve();
} }
}); });
}
});
}
});
// squoosh-cli
pngSuite.add('squoosh-cli-file-file', {
defer: true,
fn: function (deferred) {
exec(`./node_modules/.bin/squoosh-cli \
--output-dir ${os.tmpdir()} \
--resize '{"enabled":true,"width":${width},"height":${heightPng},"method":"lanczos3","premultiply":true,"linearRGB":false}' \
--oxipng '{"level":1}' \
"${fixtures.inputPngAlphaPremultiplicationLarge}"`, function (err) {
if (err) {
throw err;
}
deferred.resolve();
});
}
});
// squoosh-lib (GPLv3)
pngSuite.add('squoosh-lib-buffer-buffer', {
defer: true,
fn: function (deferred) {
const pool = new squoosh.ImagePool(os.cpus().length);
const image = pool.ingestImage(inputPngBuffer);
image.decoded
.then(function () {
return image.preprocess({
resize: {
enabled: true,
width,
height: heightPng,
method: 'lanczos3',
premultiply: true,
linearRGB: false
}
});
})
.then(function () {
return image.encode({
oxipng: {
level: 1
}
});
})
.then(function () {
return pool.close();
})
.then(function () {
return image.encodedWith.oxipng;
})
.then(function () {
deferred.resolve();
});
}
});
// mapnik // mapnik
mapnik && pngSuite.add('mapnik-file-file', { mapnik && pngSuite.add('mapnik-file-file', {
defer: true, defer: true,

View File

@ -12,7 +12,6 @@ const sharp = require('../../');
const fixtures = require('../fixtures'); const fixtures = require('../fixtures');
sharp.cache(false); sharp.cache(false);
sharp.simd(true);
const min = 320; const min = 320;
const max = 960; const max = 960;

BIN
test/fixtures/bgbn4a08.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 B

BIN
test/fixtures/bggn4a16.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

BIN
test/fixtures/d.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

BIN
test/fixtures/dot-and-lines.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 463 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Some files were not shown because too many files have changed in this diff Show More