Compare commits

..

198 Commits

Author SHA1 Message Date
Lovell Fuller
844deaf480 Release v0.31.3 2022-12-21 15:57:10 +00:00
Lovell Fuller
efbb0c22fd Docs: add image with examples of resize fit property 2022-12-21 15:47:39 +00:00
Lovell Fuller
da0b594900 Docs: update benchmarks for latest versions, add ARM64 results 2022-12-20 19:49:29 +00:00
Lovell Fuller
78dada9126 Tests: skip mapnik and tensorflow for Docker-run benchmarks
Maintainance of mapnik seems to have stalled, no ARM64 support
Memory requirements of Tensorflow too high, hangs/crashes on AMD64
2022-12-20 18:20:59 +00:00
Lovell Fuller
15f5cd4671 Tests: move mapnik to optional deps
It does not currently support ARM64
2022-12-19 19:47:46 +00:00
Lovell Fuller
9eb2e94404 Tests: update benchmark dependencies 2022-12-17 14:29:11 +00:00
Lovell Fuller
e40b068628 Tests: update leak suppresions for latest dependencies 2022-12-14 21:57:42 +00:00
Lovell Fuller
2c46528269 Docs refresh 2022-12-14 16:17:42 +00:00
Lovell Fuller
584807b4f5 Add runtime detection of V8 memory cage #3384
When using the V8 memory cage, Buffers cannot be wrapped and then
later freed via a callback. When the cage is detected via a throw,
instead fall back to copying Buffer contents to V8 memory.

This approach will be used by Electron 21+ and you should expect
reduced performance and increased memory consumption/fragmentation.
2022-12-14 16:06:04 +00:00
Lovell Fuller
a7fa7014ef Add experimental support for JPEG-XL, requires libvips with libjxl
The prebuilt binaries do not include support for this format.
2022-12-13 21:55:17 +00:00
Lovell Fuller
f92e33fbff Bump devDeps 2022-12-13 10:31:06 +00:00
Lovell Fuller
0f1e7ef6f6 Install: add support for Linux with glibc patch version #3423 2022-12-09 12:03:41 +00:00
Lennart
89e204d824 Docs: clarify failOn property applies to decoding pixel values (#3481) 2022-12-08 16:13:18 +00:00
Lovell Fuller
2a71f1830f Expand range of sharpen params to match libvips #3427 2022-12-07 09:28:01 +00:00
Lovell Fuller
def99a294a Install: log proxy use, if any, to aid with debugging 2022-12-06 19:35:47 +00:00
Lovell Fuller
9d760f3958 Improve perf of ops that introduce non-opaque background #3465 2022-12-05 20:40:41 +00:00
Lovell Fuller
0265d305fe Ensure integral output of linear op #3468 2022-12-04 21:41:15 +00:00
Lovell Fuller
a472aea025 Ignore sequentialRead option for stats #3462 2022-11-20 21:30:45 +00:00
Lovell Fuller
01ffa80338 Improve extractChannel support for 16-bit output #3453 2022-11-15 15:00:32 +00:00
Lovell Fuller
789d4851ea Tests: remove flaky font assertions
Probably due to Windows CI env font discovery
2022-11-15 10:08:43 +00:00
Lovell Fuller
4490a93430 Tests: simplify beforeEach configuration
Remove legacy settings for previous CI providers/hardware
2022-11-15 09:54:29 +00:00
Ingvar Stepanyan
ac0dc10bd5 Tests: convert mocha hooks (#3450) 2022-11-15 08:58:09 +00:00
Lovell Fuller
5740f4545e Expose GIF opts: interFrameMaxError, interPaletteMaxError #3401 2022-11-14 16:09:52 +00:00
Lovell Fuller
a9d692fb43 Reduce chance of race condition in test for... race condition 2022-11-13 10:16:47 +00:00
Lovell Fuller
df971207b8 Prevent possible race condition when reading metadata #3451 2022-11-13 10:04:55 +00:00
Ingvar Stepanyan
3a64a0529a Tests: run in parallel, move settings to config file (#3449)
This allows to easily invoke Mocha alone via `npx mocha`, or for e.g. VSCode Test Explorer to find and run tests with the correct settings automatically.
2022-11-10 21:48:18 +00:00
Peter Whidden
76cda885fb Docs: fix minor typo in resize properties (#3444) 2022-11-09 08:44:05 +00:00
Ingvar Stepanyan
1a563360c6 Fix errors for missing OpenJPEG (#3442)
Fixes couple of minor issues with JP2 errors:

1. The tests passed as false-positives even if regex is changed to arbitary pattern, because the promise returned from `assert.rejects` was ignored and the test ended prematurely. This is fixed by removing `{ ... }` around the test function body.
2. This, in turn, hid an issue with `toFile` not throwing the expected error message which was instead propagating `Error: VipsOperation: class "jp2ksave" not found` from libvips. This is now fixed by manually checking the extension before calling into libvips.
3. Pre-creating error instances like `errJp2Save` did is sometimes tempting, but is problematic for debugging because it hides the actual stacktrace of the error (the stacktrace is collected at the moment of `new Error` creation). This is now turned into a function that creates error with the right stack.
2022-11-08 19:53:14 +00:00
Lovell Fuller
ca22af203f Docs: canvas on Windows uses MSVCRT, conflicts with UCRT 2022-11-07 21:14:51 +00:00
Lovell Fuller
9fa516e849 Release v0.31.2 2022-11-04 09:44:37 +00:00
Lovell Fuller
12f472126d CI: Only pin Python version on x64 macOS and Windows
See commit 18be09f
2022-11-03 14:49:12 +00:00
Lovell Fuller
18be09f1d7 CI: Pin Python to 3.10
Python 3.11 removes support for opening files in
'universal newline' mode (e.g. 'rU'), however older
versions of node-gyp such as v6 still use it.
2022-11-03 14:40:16 +00:00
Lovell Fuller
b3c3290f90 Upgrade to libvips v8.13.3 2022-11-03 14:09:23 +00:00
Lovell Fuller
123f95c85a Bump devDeps 2022-11-03 12:50:58 +00:00
Lovell Fuller
5b0fba4c01 Ensure auto-rotate always works without resize #3422 2022-11-02 13:59:34 +00:00
Lovell Fuller
37f7ccfff4 CI: upgrade to checkout v3 2022-10-17 16:05:30 +01:00
Lovell Fuller
51811d06e2 Bump deps 2022-10-17 16:05:03 +01:00
Lovell Fuller
181731f8f4 Tests: increase timeout to 30s
Font discovery appears to be slooow on Windows
2022-10-17 15:54:43 +01:00
Gino Emiliozzi
ae79d26ead Docs: help clarify 'fit' is option name, not value (#3410) 2022-10-17 15:26:59 +01:00
Lovell Fuller
eacb8337fa Ensure manual flip, rotate, resize op order #3391 2022-10-01 11:55:29 +01:00
Lovell Fuller
99bf279de8 Release v0.31.1 2022-09-29 14:51:45 +01:00
Lovell Fuller
1b0eb6ab53 Tests: add assertion to existing scenario #3357 2022-09-29 14:21:37 +01:00
Lovell Fuller
891cf67d0b Upgrade to libvips v8.13.2 2022-09-29 14:19:58 +01:00
Lovell Fuller
eaf8a86bf2 Tests: increase timeout to 20s
Ignore unit coverage of fn used at install time
2022-09-27 14:25:34 +01:00
Lovell Fuller
3400976d61 Tests: ignore a branch for coverage check 2022-09-27 14:10:49 +01:00
Lovell Fuller
2d49f0e93e Tests: require 100% branch coverage to pass
Remove old coverage tooling, coveralls
2022-09-27 13:49:42 +01:00
Lovell Fuller
b0c69f1ee9 CI: use clearer job names 2022-09-27 10:02:20 +01:00
Lovell Fuller
27d0c35a01 CI: use clearer job names 2022-09-27 09:23:30 +01:00
Alex
32a22b5420 CI: GitHub Workflows security hardening (#3377)
Signed-off-by: Alex <aleksandrosansan@gmail.com>
2022-09-26 11:25:49 +01:00
Lovell Fuller
d1004eed02 Ensure greyscale images can be trimmed #3386 2022-09-26 10:15:25 +01:00
Lovell Fuller
70e6bb0162 Ensure close event occurs after end event #3313 2022-09-20 08:52:40 +01:00
Lovell Fuller
32aa3b4b20 Tests: bump/pin benchmark dependencies 2022-09-19 16:21:24 +01:00
Lovell Fuller
df24b30755 Tests: add tfjs to benchmark tests 2022-09-19 16:20:23 +01:00
Lovell Fuller
4de74bea94 Tests: remove assertions from benchmark code 2022-09-19 16:09:31 +01:00
Lovell Fuller
28b87db760 Ensure AVIF output is always 8-bit #3358 2022-09-14 13:33:47 +01:00
Lovell Fuller
fbd4970b57 Ensure auto-rotation works with shrink-on-load #3352
Fixes regression in 0.31.0
2022-09-07 14:17:40 +01:00
Lovell Fuller
f5da147a58 Docs: changelog and credit for #3349 2022-09-07 13:31:26 +01:00
Marcos Casagrande
eee0dd36d9 Ensure limitInputPixels uses uint64 (#3349) 2022-09-06 09:05:51 +01:00
Lovell Fuller
f7b29d7b59 CI: ensure prebuilds use Node API version 7 2022-09-05 10:14:40 +01:00
Lovell Fuller
0b806187fc Release v0.31.0 2022-09-05 09:55:27 +01:00
Lovell Fuller
c1393daa70 Expose unlimited option for HEIF input 2022-09-05 09:19:53 +01:00
Lovell Fuller
31c1cfb049 Docs: add note about GIF optimisation 2022-09-05 09:19:53 +01:00
Lovell Fuller
afc35c2208 Docs: update benchmark results for libvips v8.13.1 2022-09-05 09:19:53 +01:00
Lovell Fuller
6eb2add3bf Docs: refresh for 5cdb2b8 2022-09-04 13:17:02 +01:00
Lovell Fuller
5cdb2b83d5 Upgrade to libvips v8.13.1 2022-09-04 12:42:27 +01:00
Lovell Fuller
1eb66c0944 Tests: relax truncated PNG test assertion 2022-09-04 11:19:01 +01:00
Lovell Fuller
55c4d8807c Improve normalise op with use of histogram #200 2022-09-04 10:31:43 +01:00
Lovell Fuller
9a54a034e1 Tests: ensure truncated PNG test handles possible race 2022-09-04 10:28:24 +01:00
Lovell Fuller
f5109560d6 Standardise approach for string to enum conversion 2022-09-02 12:20:09 +01:00
Lovell Fuller
953a94885b Tests: run benchmarks in container via Docker 2022-09-01 14:58:39 +01:00
Lovell Fuller
0e3bd46ca3 Docs: clarify that metadata respects page/pages 2022-09-01 09:58:17 +01:00
Lovell Fuller
4b38f56d02 Docs: add avif and heif examples 2022-09-01 09:57:50 +01:00
Lovell Fuller
0fe857c5ac Docs: move serverless-esbuild to bundlers section 2022-08-24 17:42:56 +01:00
A. Sayef Reyadh
1bf06bd5b4 Docs: add info for serverless-esbuild users (#3235) 2022-08-24 17:37:58 +01:00
Lovell Fuller
6e3f4c3c92 Docs: changelog for #3332 2022-08-23 13:00:02 +01:00
Lovell Fuller
8583eb1235 Tests: update leak suppressions for latest versions 2022-08-23 12:32:39 +01:00
Mart
c3a852eecf Add trim option to provide a specific background colour (#3332)
Co-authored-by: Mart Jansink <mart@cinemait.nl>
2022-08-23 12:28:02 +01:00
Lovell Fuller
3a44748f49 Ensure PNG bitdepth can be set for non-palette output #3322 2022-08-22 14:57:12 +01:00
Lovell Fuller
e1bc8674fd Docs: clarify composite operation ordering 2022-08-21 19:53:04 +01:00
Lovell Fuller
a618ce7a15 Ensure image is unpremultiplied before composite #3334 2022-08-21 17:51:05 +01:00
Lovell Fuller
a44168c8c7 Docs: changelog and credit for #3303 2022-08-20 10:27:31 +01:00
Anton Marsden
74e3f73934 Expand linear operation to allow use of per-channel arrays #3303 2022-08-20 10:27:04 +01:00
Lovell Fuller
b9261c243c Bump devDeps, requires doc refresh 2022-08-20 09:23:24 +01:00
Lovell Fuller
cc9f91f37c Docs: note about macos fontconfig vs coretext 2022-08-18 16:41:33 +01:00
Lovell Fuller
212a6e7519 Ensure op ordering is respected where possible #3319
Emit warnings when previous ops might be ignored
Flip and flop now occur before rotate, if any
2022-08-18 16:41:33 +01:00
Kid
e547eaa180 Docs: fix broken link to Got stream documentation (#3323) 2022-08-07 14:25:36 +01:00
Lionel Tzatzkin
9a0d9eed74 Docs: correct syntax in sharpen example (#3310) 2022-07-29 12:11:16 +01:00
Lovell Fuller
dd56a9699e Docs: changelog and credit for #3252 2022-07-25 12:19:25 +01:00
brahima
ea7cf2a2ef Expose vips_text to create an image containing rendered text (#3252) 2022-07-25 11:32:10 +01:00
Lovell Fuller
76c4c51e2a Remove previously-deprecated reductionEffort and speed options 2022-07-24 11:18:16 +01:00
Lovell Fuller
b46ab510da Add Buffer and Stream support to tile output #2238 2022-07-24 11:06:41 +01:00
Lovell Fuller
3e327a586c Docs: add section about font discovery 2022-07-23 16:31:00 +01:00
Lovell Fuller
974fab946e Bump devDeps 2022-07-23 16:21:42 +01:00
Lovell Fuller
f998a8f249 Upgrade to libvips v8.13.0 2022-07-23 10:04:14 +01:00
Lovell Fuller
be331e958e CI: upgrade to macOS 11 2022-07-22 23:20:33 +01:00
Lovell Fuller
254944f8ab CI: install Noto font via package manager 2022-07-18 13:35:22 +01:00
Lovell Fuller
f1e640d231 Tests: catch potential failures during tile unzip 2022-07-14 11:13:59 +01:00
Lovell Fuller
c295f06a6f Ensure only props owned by EXIF Object are parsed #3292 2022-07-13 21:33:06 +01:00
Lovell Fuller
6288c7bced Expose reoptimise palette option for GIF output 2022-07-12 21:12:31 +01:00
Lovell Fuller
d247c02762 Add mixed and minSize animation options for WebP output 2022-07-12 14:51:03 +01:00
Lovell Fuller
1b84ccbbe9 Ensure fileSuffix supports suffix-less loaders 2022-07-11 20:56:19 +01:00
Lovell Fuller
e4160c684d Docs: add timeout example 2022-07-11 11:12:32 +01:00
Lovell Fuller
905518fab0 Add input fileSuffix and output alias to format #2642 2022-07-11 10:45:19 +01:00
Lovell Fuller
8ff33763ce Ensure OpenSlide+FITS input works with custom libvips #3226 2022-07-08 22:25:39 +01:00
Lovell Fuller
cbf741cac7 Ensure trim is no-op when it would reduce to nothing #3223 2022-07-08 21:06:58 +01:00
Lovell Fuller
6c2e2be41d CI: upgrade Linux arm64 environment to Node.js 14/18 2022-07-05 19:42:05 +01:00
Lovell Fuller
e0d3c6e05d Use bounding box of alpha+non-alpha for trim op #2166 2022-07-05 18:19:17 +01:00
Lovell Fuller
e3cab7f10f CI: fix path to gcc toolset 2022-06-29 12:40:04 +01:00
Lovell Fuller
204463ffbb CI: ensure gcc 11 toolset is available on the PATH 2022-06-29 12:26:16 +01:00
Lovell Fuller
1bcd3700c5 CI: Node.js 18 does not support CentOS 7, upgrade to Rocky 8 2022-06-29 12:18:41 +01:00
Lovell Fuller
c99a11cff5 CI: add Node.js 18, remove 12 2022-06-29 11:52:41 +01:00
Lovell Fuller
81c74f57e0 Re-introduce support for greyscale ICC profiles #3114 2022-06-29 11:41:36 +01:00
Lovell Fuller
7a8ab452c5 Add support for WebP and PackBits compression with TIFF output #3198 2022-06-29 11:35:58 +01:00
Lovell Fuller
bb91912883 Drop support for Node.js 12, now requires >= 14.15.0 2022-06-29 10:32:25 +01:00
Kleis Auke Wolthuizen
afc4c5bf79 Upgrade to libvips v8.13.0-rc1 (#3230)
* Switch from decompress-zip to extract-zip

The former seems to hang when unzipping a ZIP64 file that uses
the general purpose bit flag 3 as file entry.

See: https://github.com/thejoshwolfe/yauzl#no-streaming-unzip-api

* Prefer to call via static member instead

Makes it clearer that a static method is being called.

* `flatten-orange.jpg`: save without chroma subsampling

To ensure no down-scaling of the Cr/Cb channels.
2022-06-26 22:39:29 +01:00
Lovell Fuller
e40a881ab4 Release v0.30.7 2022-06-22 16:44:16 +01:00
Lovell Fuller
c1b13adac3 Bump deps 2022-06-22 11:53:22 +01:00
Lovell Fuller
29e09898f7 Docs: add examples of custom binary locations 2022-06-22 11:50:30 +01:00
Lovell Fuller
853a20358e Install: add help for possible worker thread problem #3268 2022-06-21 08:22:05 +01:00
Lovell Fuller
8bb30d7801 Docs: changelog and credit #3261 #3267 2022-06-21 07:35:28 +01:00
Blayne Chard
a333b87f5d Prevent upsampling via libwebp (#3267) 2022-06-20 10:49:53 +01:00
AlexanderTheGrey
4662527a17 Allow WebP encoding effort of 0 (#3261) 2022-06-17 08:22:51 +01:00
Lovell Fuller
b10d8f89ca Docs: add example of multi-arch within same install tree 2022-06-10 12:51:44 +01:00
Oleg Andreyev
f903e1465e Docs: clarify wording of resize background option 2022-06-08 12:56:29 +01:00
Lovell Fuller
a75718565c Ensure composite can tile with outside resize #3227 2022-06-08 12:39:00 +01:00
Fonger
4d82331bf6 docs(input): correct getNormalSize with EXIF orientation example (#3241) 2022-05-31 08:59:15 +01:00
Lovell Fuller
b91875d3d9 Release v0.30.6 2022-05-30 08:56:14 +01:00
Lovell Fuller
a0568ec0c3 Allow values for limitInputPixels larger than 32-bit #3238 2022-05-28 08:35:17 +01:00
Lovell Fuller
48e3ea5e29 Ensure brew-installed vips can be detected #3239 2022-05-26 22:58:24 +01:00
Lovell Fuller
93b29057e4 Docs: changelog and credit for #3160 2022-05-24 21:14:13 +01:00
Lovell Fuller
db654de385 Release v0.30.5 2022-05-23 12:19:02 +01:00
Lovell Fuller
a6aeef612b Install: pass PKG_CONFIG_PATH via env rather than substitution 2022-05-23 12:12:19 +01:00
Lovell Fuller
7bf6cbd669 Docs: correct links to libvips documentation 2022-05-22 12:14:24 +01:00
Lovell Fuller
04c31b35a7 Install: warn about filesystem owner running npm v8+ as root 2022-05-15 19:43:45 +01:00
Lovell Fuller
ee9cdb6598 Bump deps 2022-05-15 17:20:33 +01:00
Lovell Fuller
8960eb8309 Docs: changelog entry for #3218 2022-05-15 17:12:51 +01:00
jakob0fischl
54d9dc46f5 Fix rotate-then-extract for EXIF orientation 2 (#3218) 2022-05-15 12:26:57 +01:00
Joona Heinikoski
51b4a7c564 Add support for --libc flag to improve cross-platform install (#3160)
This deprecates the libc-as-suffix approach of --platform=linuxmusl
2022-04-28 11:24:45 +01:00
Lovell Fuller
5b03579e5c Docs: more details about concurrency, parallelism, threads 2022-04-25 14:40:55 +01:00
Lovell Fuller
58c2af3251 Docs: improve output format info for toBuffer 2022-04-25 11:41:06 +01:00
Lovell Fuller
ee948ac6fa Docs: changelog and credit for #3196 2022-04-25 11:33:05 +01:00
Ankur Parihar
66a3ce5e55 Allow installation of prebuilt libvips binary from filesystem (#3196) 2022-04-24 18:47:57 +01:00
David Humphrey
75e5afcd42 Docs: fix typo in gif example (#3201) 2022-04-22 16:09:28 +01:00
Lovell Fuller
d396a4e65d Release v0.30.4 2022-04-18 10:14:31 +01:00
Lovell Fuller
ae1dbcdf4e Bump deps 2022-04-18 10:11:30 +01:00
Lovell Fuller
4c29368b51 Docs: EXIF metadata unsupported for TIFF output #3074 2022-04-18 09:53:35 +01:00
Lovell Fuller
36e55969d2 Docs: mention npm's foreground-scripts option to aid debugging 2022-04-18 09:51:27 +01:00
Lovell Fuller
985e881e7a Bump deps 2022-04-05 21:14:09 +01:00
Lovell Fuller
0b116715aa Docs: changelog for #3178 2022-04-05 21:11:06 +01:00
Chris Hranj
9deac83322 Add missing file name to 'Input file is missing' error message (#3178) 2022-04-05 11:35:01 +01:00
Lovell Fuller
5d36f5f699 Improve error message for SVG render above limit #3167 2022-04-04 14:20:04 +01:00
Lovell Fuller
926572b41e Control sensitivity to invalid images via failOn
Deprecates failOnError, equivalent to failOn=warning
2022-04-04 12:27:45 +01:00
Lovell Fuller
d0c8e95641 Docs: expand info about use with worker threads 2022-03-30 10:09:15 +01:00
Lovell Fuller
b0ca23c3e7 Docs: changelog and credit for #3146 2022-03-28 21:32:38 +01:00
codepage949
c3a0d5f5d0 Add support for TypedArray input with byteOffset and length 2022-03-27 20:18:58 +01:00
Lovell Fuller
1d36936954 Ensure create has correct bit depth and colourspace #3139 2022-03-22 19:48:02 +00:00
Lovell Fuller
b609df4b48 Release v0.30.3 2022-03-14 11:54:15 +00:00
Lovell Fuller
c567d3b9ab Bump devDeps 2022-03-14 11:52:45 +00:00
Marvin ROGER
27d9fe2a4e Add additional debugging hint on symbol error (#3132) 2022-03-14 10:19:02 +00:00
Lovell Fuller
ac883c5215 Docs: composite image supports the animated property #3135 2022-03-14 08:53:00 +00:00
Lovell Fuller
e8720c9374 Docs: use SVG favicon with a PNG fallback
Remove unused apple-touch icons
2022-03-13 14:22:05 +00:00
Lovell Fuller
42e45d842a Docs: add more examples (composite, greyscale, tint) 2022-03-12 20:33:15 +00:00
Lovell Fuller
72fd8abe2c Docs: add section on (preventing) bundling with esbuild 2022-03-12 13:17:36 +00:00
Lovell Fuller
ac18bbbc7c Ensure backwards-compatibility of JSDoc introduced in ea599ad 2022-03-11 19:07:11 +00:00
Lovell Fuller
fcbe4e1e01 Tests: remove possible race condition
Simplify JP2 quality size check
2022-03-09 19:55:32 +00:00
Lovell Fuller
9280742385 CI: update FreeBSD environment 2022-03-09 19:26:43 +00:00
Lovell Fuller
7a1a1cf9e8 Docs: add/correct some operation examples 2022-03-09 19:18:41 +00:00
Lovell Fuller
ea599ade10 Allow sharpen options to be provided as an Object
Also exposes x1, y2, y3 parameters #2561 #2935
2022-03-09 19:07:08 +00:00
Lovell Fuller
1de49f3ed8 Docs: refresh for metadata example #3127 2022-03-09 16:02:27 +00:00
Rasmus Schultz
4ac65054bc Docs: add example of how to get the right-side-up width/height (#3127)
See #3124
2022-03-09 15:59:09 +00:00
Lovell Fuller
23033e2050 Prevent double unpremultiply with some composite blends 2022-03-04 23:17:07 +00:00
Lovell Fuller
dd3b78272a Docs: remove experimental status from existing stats properties 2022-03-04 07:58:03 +00:00
Lovell Fuller
80d169b7c2 Release v0.30.2 2022-03-02 11:24:35 +00:00
Lovell Fuller
003279a0b0 CI: switch 32-bit Windows from Appveyor to Actions 2022-03-02 11:16:21 +00:00
Lovell Fuller
af80d7e389 Improve error message for missing file that might be SVG 2022-03-02 09:58:55 +00:00
Lovell Fuller
21a960796c Ignore greyscale ICC profiles due to lcms bug #3112 2022-02-28 11:28:08 +00:00
Lovell Fuller
fc3b4a683d Expand pkgconfig search path for wider BSD support #3106 2022-02-27 09:39:21 +00:00
Lovell Fuller
808133e7dc Docs: changelog entry for #3110 2022-02-26 19:40:17 +00:00
Lovell Fuller
801b6fea6c Bump devDeps 2022-02-26 19:39:46 +00:00
Kleis Auke Wolthuizen
c2ecde6a16 Windows: ensure C++ runtime is linked statically (#3110)
And remove the empty invalid parameter handler, which should
be present in the C layer instead.

This partially reverts commit
659cdabd8e,
the added test case in that commit is still preserved.
2022-02-26 19:15:37 +00:00
Lovell Fuller
55efe5602b Bump deps 2022-02-16 19:12:27 +00:00
Lovell Fuller
c62002554b Improve performance and accuracy of multi-image composite #2286 2022-02-16 19:04:23 +00:00
Lovell Fuller
7f83ecd255 Issue templates: small formatting fixes 2022-02-15 10:54:36 +00:00
Lovell Fuller
dc5f4dcd28 Issue templates: improve guidance, increase filtering 2022-02-15 10:50:26 +00:00
Lovell Fuller
735793ba99 Release v0.30.1 2022-02-09 16:38:21 +00:00
Lovell Fuller
47792df689 Docs: update interpolator links 2022-02-09 15:45:05 +00:00
Lovell Fuller
5c6cdfaece Docs: changelog entry for #3083 2022-02-09 15:27:52 +00:00
Kleis Auke Wolthuizen
115a6b10f6 Ensure affineInterpolator is correctly finalised (#3083) 2022-02-09 14:45:11 +00:00
Lovell Fuller
4feee506cf Docs: changelog entry for #3081 2022-02-08 22:08:07 +00:00
Kleis Auke Wolthuizen
83db5f8a2a Ensure withoutReduction does not interfere with contain/crop/embed (#3081) 2022-02-08 21:22:23 +00:00
Kleis Auke Wolthuizen
7eb5efa3a3 Update tests and comments after 7faacd9 (#3080) 2022-02-08 21:12:38 +00:00
Lovell Fuller
5a9f89fe06 Docs: update references to default branch 2022-02-08 21:01:40 +00:00
Lovell Fuller
02e0c2dfc9 Tests: arm64 requires slight threshold increase 2022-02-08 21:00:30 +00:00
Lovell Fuller
968d9d7008 Bump devDeps 2022-02-08 18:29:25 +00:00
Kleis Auke Wolthuizen
7faacd91b0 Avoid fastShrinkOnLoad workaround 2022-02-08 18:20:25 +00:00
Lovell Fuller
154eaff4ec Issue template: include npm v8+ 2022-02-08 18:20:11 +00:00
Lovell Fuller
424660278d Allow use of toBuffer+toFile w/ same instance #3044 2022-02-03 22:01:46 +00:00
Lovell Fuller
2b01951306 Skip JPEG shrink-on-load for known rounding errors #3066
Co-authored-by: Kleis Auke Wolthuizen <github@kleisauke.nl>
2022-02-03 21:19:48 +00:00
137 changed files with 4476 additions and 1472 deletions

View File

@@ -3,76 +3,76 @@ version: 2.1
workflows: workflows:
build: build:
jobs: jobs:
- linux-arm64-glibc-node-12: - linux-arm64-glibc-node-14:
filters: filters:
tags: tags:
only: /^v.*/ only: /^v.*/
- linux-arm64-musl-node-12: - linux-arm64-musl-node-14:
filters: filters:
tags: tags:
only: /^v.*/ only: /^v.*/
- linux-arm64-glibc-node-16: - linux-arm64-glibc-node-18:
filters: filters:
tags: tags:
only: /^v.*/ only: /^v.*/
- linux-arm64-musl-node-16: - linux-arm64-musl-node-18:
filters: filters:
tags: tags:
only: /^v.*/ only: /^v.*/
jobs: jobs:
linux-arm64-glibc-node-12: linux-arm64-glibc-node-14:
resource_class: arm.medium resource_class: arm.medium
machine: machine:
image: ubuntu-2004:202101-01 image: ubuntu-2004:current
steps: steps:
- checkout - checkout
- run: | - run: |
sudo docker run -dit --name sharp --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp arm64v8/debian:bullseye sudo docker run -dit --name sharp --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp arm64v8/debian:bullseye
sudo docker exec sharp sh -c "apt-get update && apt-get install -y build-essential git python3 curl" sudo docker exec sharp sh -c "apt-get update && apt-get install -y build-essential git python3 curl fonts-noto-core"
sudo docker exec sharp sh -c "curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -" sudo docker exec sharp sh -c "curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -"
sudo docker exec sharp sh -c "echo 'deb https://deb.nodesource.com/node_12.x sid main' >/etc/apt/sources.list.d/nodesource.list" sudo docker exec sharp sh -c "echo 'deb https://deb.nodesource.com/node_14.x sid main' >/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 "apt-get update && apt-get install -y nodejs"
- run: sudo docker exec sharp sh -c "npm install --build-from-source --unsafe-perm" - run: sudo docker exec sharp sh -c "npm install --build-from-source --unsafe-perm"
- run: sudo docker exec sharp sh -c "npm test" - run: sudo docker exec sharp sh -c "npm test"
- run: "[[ -n $CIRCLE_TAG ]] && sudo docker exec --env prebuild_upload sharp sh -c \"npx prebuild --runtime napi --target 5 --upload=$prebuild_upload\" || true" - run: "[[ -n $CIRCLE_TAG ]] && sudo docker exec --env prebuild_upload sharp sh -c \"npx prebuild --runtime napi --target 7 --upload=$prebuild_upload\" || true"
linux-arm64-glibc-node-16: linux-arm64-glibc-node-18:
resource_class: arm.medium resource_class: arm.medium
machine: machine:
image: ubuntu-2004:202101-01 image: ubuntu-2004:current
steps: steps:
- checkout - checkout
- run: | - run: |
sudo docker run -dit --name sharp --workdir /mnt/sharp arm64v8/debian:bullseye 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" 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 "curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -" sudo docker exec sharp sh -c "curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -"
sudo docker exec sharp sh -c "echo 'deb https://deb.nodesource.com/node_16.x sid main' >/etc/apt/sources.list.d/nodesource.list" sudo docker exec sharp sh -c "echo 'deb https://deb.nodesource.com/node_18.x sid main' >/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 "apt-get update && apt-get install -y nodejs"
sudo docker exec sharp sh -c "mkdir -p /mnt/sharp" sudo docker exec sharp sh -c "mkdir -p /mnt/sharp"
sudo docker cp . sharp:/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 install --build-from-source"
- run: sudo docker exec sharp sh -c "npm test" - run: sudo docker exec sharp sh -c "npm test"
linux-arm64-musl-node-12: linux-arm64-musl-node-14:
resource_class: arm.medium resource_class: arm.medium
machine: machine:
image: ubuntu-2004:202101-01 image: ubuntu-2004:current
steps: steps:
- checkout - checkout
- run: | - run: |
sudo docker run -dit --name sharp --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp node:12-alpine3.11 sudo docker run -dit --name sharp --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp node:14-alpine3.12
sudo docker exec sharp sh -c "apk add build-base git python3 --update-cache" 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 --unsafe-perm" - run: sudo docker exec sharp sh -c "npm install --build-from-source --unsafe-perm"
- run: sudo docker exec sharp sh -c "npm test" - run: sudo docker exec sharp sh -c "npm test"
- run: "[[ -n $CIRCLE_TAG ]] && sudo docker exec --env prebuild_upload sharp sh -c \"npx prebuild --runtime napi --target 5 --upload=$prebuild_upload\" || true" - run: "[[ -n $CIRCLE_TAG ]] && sudo docker exec --env prebuild_upload sharp sh -c \"npx prebuild --runtime napi --target 7 --upload=$prebuild_upload\" || true"
linux-arm64-musl-node-16: linux-arm64-musl-node-18:
resource_class: arm.medium resource_class: arm.medium
machine: machine:
image: ubuntu-2004:202101-01 image: ubuntu-2004:current
steps: steps:
- checkout - checkout
- run: | - run: |
sudo docker run -dit --name sharp --workdir /mnt/sharp node:16-alpine3.11 sudo docker run -dit --name sharp --workdir /mnt/sharp node:18-alpine3.14
sudo docker exec sharp sh -c "apk add build-base git python3 --update-cache" 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 exec sharp sh -c "mkdir -p /mnt/sharp"
sudo docker cp . sharp:/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 install --build-from-source"

View File

@@ -1,15 +1,15 @@
freebsd_instance: freebsd_instance:
image_family: freebsd-13-0-snap image_family: freebsd-14-0-snap
task: task:
name: FreeBSD 13.0 name: FreeBSD
env: env:
IGNORE_OSVERSION: yes IGNORE_OSVERSION: yes
skip_notifications: true skip_notifications: true
prerequisites_script: prerequisites_script:
- pkg update -f - pkg update -f
- pkg upgrade -y - pkg upgrade -y
- pkg install -y pkgconf vips node npm - pkg install -y devel/pkgconf graphics/vips www/node16 www/npm
install_script: install_script:
- npm install --build-from-source --unsafe-perm - npm install --build-from-source --unsafe-perm
test_script: test_script:

View File

@@ -16,29 +16,29 @@ If a [similar request](https://github.com/lovell/sharp/labels/enhancement) exist
it's probably fastest to add a comment to it about your requirement. it's probably fastest to add a comment to it about your requirement.
Implementation is usually straightforward if libvips Implementation is usually straightforward if libvips
[already supports](https://libvips.github.io/libvips/API/current/func-list.html) [already supports](https://www.libvips.org/API/current/func-list.html)
the feature you need. the feature you need.
## Submit a Pull Request to fix a bug ## Submit a Pull Request to fix a bug
Thank you! To prevent the problem occurring again, please add unit tests that would have failed. Thank you! To prevent the problem occurring again, please add unit tests that would have failed.
Please select the `master` branch as the destination for your Pull Request so your fix can be included in the next minor release. Please select the `main` branch as the destination for your Pull Request so your fix can be included in the next minor release.
Please squash your changes into a single commit using a command like `git rebase -i upstream/master`. Please squash your changes into a single commit using a command like `git rebase -i upstream/main`.
To test C++ changes, you can compile the module using `npm install --build-from-source` and then run the tests using `npm test`. To test C++ changes, you can compile the module using `npm install --build-from-source` and then run the tests using `npm test`.
## Submit a Pull Request with a new feature ## Submit a Pull Request with a new feature
Please add JavaScript [unit tests](https://github.com/lovell/sharp/tree/master/test/unit) to cover your new feature. Please add JavaScript [unit tests](https://github.com/lovell/sharp/tree/main/test/unit) to cover your new feature.
A test coverage report for the JavaScript code is generated in the `coverage/lcov-report` directory. A test coverage report for the JavaScript code is generated in the `coverage/lcov-report` directory.
Where possible, the functional tests use gradient-based perceptual hashes Where possible, the functional tests use gradient-based perceptual hashes
based on [dHash](http://www.hackerfactor.com/blog/index.php?/archives/529-Kind-of-Like-That.html) based on [dHash](http://www.hackerfactor.com/blog/index.php?/archives/529-Kind-of-Like-That.html)
to compare expected vs actual images. to compare expected vs actual images.
You deserve to add your details to the [list of contributors](https://github.com/lovell/sharp/blob/master/package.json#L5). You deserve to add your details to the [list of contributors](https://github.com/lovell/sharp/blob/main/package.json#L5).
Any change that modifies the existing public API should be added to the relevant work-in-progress branch for inclusion in the next major release. Any change that modifies the existing public API should be added to the relevant work-in-progress branch for inclusion in the next major release.
@@ -93,5 +93,5 @@ Please feel free to ask any questions via a
[new issue](https://github.com/lovell/sharp/issues/new). [new issue](https://github.com/lovell/sharp/issues/new).
If you're unable to post details publicly, please If you're unable to post details publicly, please
[e-mail](https://github.com/lovell/sharp/blob/master/package.json#L5) [e-mail](https://github.com/lovell/sharp/blob/main/package.json#L5)
for private, paid consulting. for private, paid consulting.

View File

@@ -5,12 +5,24 @@ labels: enhancement
--- ---
What are you trying to achieve? ## Feature request
Have you searched for similar feature requests? ### What are you trying to achieve?
What would you expect the API to look like? <!-- Please provide context here. -->
What alternatives have you considered? ### When you searched for similar feature requests, what did you find that might be related?
Is there a sample image that helps explain? <!-- Please demonstrate your research here. -->
### What would you expect the API to look like?
<!-- Please provide your suggestions here. -->
### What alternatives have you considered?
<!-- Please provide your ideas here. -->
### Please provide sample image(s) that help explain this feature
<!-- Please provide links to one or more images here. -->

View File

@@ -5,18 +5,41 @@ labels: installation
--- ---
Did you see the [documentation relating to installation](https://sharp.pixelplumbing.com/install)? <!-- Please try to answer as many of these questions as possible. -->
Have you ensured the architecture and platform of Node.js used for `npm install` is the same as the architecture and platform of Node.js used at runtime? ## Possible install-time or require-time problem
Are you using the latest version? Is the version currently in use as reported by `npm ls sharp` the same as the latest version as reported by `npm view sharp dist-tags.latest`? <!-- Please place an [x] in the box to confirm. -->
- [ ] I have read the [documentation relating to installation](https://sharp.pixelplumbing.com/install).
- [ ] I have ensured that the architecture and platform of Node.js used for `npm install` is the same as the architecture and platform of Node.js used at runtime.
### Are you using the latest version of sharp?
<!-- Please place an [x] in the box to confirm. -->
- [ ] I am using the latest version of `sharp` as reported by `npm view sharp dist-tags.latest`.
If you cannot confirm this, please upgrade to the latest version and try again before opening an issue.
If you are using another package which depends on a version of `sharp` that is not the latest, please open an issue against that package instead.
### Is this a problem with filesystem permissions?
If you are using npm v6 or earlier and installing as a `root` or `sudo` user, have you tried with the `npm install --unsafe-perm` flag? If you are using npm v6 or earlier and installing as a `root` or `sudo` user, have you tried with the `npm install --unsafe-perm` flag?
If you are using npm v7, does the user running `npm install` own the directory it is run in? If you are using npm v7 or later, does the user running `npm install` own the directory it is run in?
If you are using the `ignore-scripts` feature of `npm`, have you tried with the `npm install --ignore-scripts=false` flag? If you are using the `ignore-scripts` feature of `npm`, have you tried with the `npm install --ignore-scripts=false` flag?
What is the complete output of running `npm install --verbose sharp`? Have you checked this output for useful error messages? ### What is the complete output of running `npm install --verbose --foreground-scripts sharp` in an empty directory?
What is the output of running `npx envinfo --binaries --system`? <details>
<!-- Please provide output of `npm install --verbose --foreground-scripts sharp` in an empty directory here. -->
</details>
### What is the output of running `npx envinfo --binaries --system --npmPackages=sharp --npmGlobalPackages=sharp`?
<!-- Please provide output of `npx envinfo --binaries --system --npmPackages=sharp --npmGlobalPackages=sharp` here. -->

View File

@@ -7,14 +7,43 @@ labels: triage
<!-- If this issue relates to installation, please use https://github.com/lovell/sharp/issues/new?labels=installation&template=installation.md instead. --> <!-- If this issue relates to installation, please use https://github.com/lovell/sharp/issues/new?labels=installation&template=installation.md instead. -->
Are you using the latest version? Is the version currently in use as reported by `npm ls sharp` the same as the latest version as reported by `npm view sharp dist-tags.latest`? ## Possible bug
What are the steps to reproduce? ### Is this a possible bug in a feature of sharp, unrelated to installation?
What is the expected behaviour? <!-- Please place an [x] in the box to confirm. -->
Are you able to provide a minimal, standalone code sample, without other dependencies, that demonstrates this problem? - [ ] Running `npm install sharp` completes without error.
- [ ] Running `node -e "require('sharp')"` completes without error.
Are you able to provide a sample image that helps explain the problem? If you cannot confirm both of these, please open an [installation issue](https://github.com/lovell/sharp/issues/new?labels=installation&template=installation.md) instead.
What is the output of running `npx envinfo --binaries --system`? ### Are you using the latest version of sharp?
<!-- Please place an [x] in the box to confirm. -->
- [ ] I am using the latest version of `sharp` as reported by `npm view sharp dist-tags.latest`.
If you cannot confirm this, please upgrade to the latest version and try again before opening an issue.
If you are using another package which depends on a version of `sharp` that is not the latest, please open an issue against that package instead.
### What is the output of running `npx envinfo --binaries --system --npmPackages=sharp --npmGlobalPackages=sharp`?
<!-- Please provide output of the above command here. -->
### What are the steps to reproduce?
<!-- Please enter steps to reproduce here. -->
### What is the expected behaviour?
<!-- Please enter the expected behaviour here. -->
### Please provide a minimal, standalone code sample, without other dependencies, that demonstrates this problem
<!-- Please provide either formatted code or a link to a repo/gist that allows someone else to reproduce here. -->
### Please provide sample image(s) that help explain this problem
<!-- Please provide links to one or more images here. -->

View File

@@ -7,10 +7,20 @@ labels: question
<!-- If this issue relates to installation, please use https://github.com/lovell/sharp/issues/new?labels=installation&template=installation.md instead. --> <!-- If this issue relates to installation, please use https://github.com/lovell/sharp/issues/new?labels=installation&template=installation.md instead. -->
What are you trying to achieve? ## Question about an existing feature
Have you searched for similar questions? ### What are you trying to achieve?
Are you able to provide a minimal, standalone code sample that demonstrates this question? <!-- Please provide context here. -->
Are you able to provide a sample image that helps explain the question? ### When you searched for similar issues, what did you find that might be related?
<!-- Please demonstrate your research here. -->
### Please provide a minimal, standalone code sample, without other dependencies, that demonstrates this question
<!-- Please provide either formatted code or a link to a repo/gist that helps someone else understand here. -->
### Please provide sample image(s) that help explain this question
<!-- Please provide links to one or more images here. -->

View File

@@ -2,29 +2,33 @@ name: CI (MacStadium)
on: on:
- push - push
- pull_request - pull_request
permissions: {}
jobs: jobs:
CI: CI:
permissions:
contents: write # for npx prebuild to make release
name: Node.js ${{ matrix.nodejs_version }} ${{ matrix.nodejs_arch }} ${{ matrix.prebuild && '- prebuild' }}
runs-on: macos-m1 runs-on: macos-m1
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
include: include:
- nodejs_version: 12 - nodejs_version: 14
nodejs_architecture: x64 nodejs_arch: x64
- nodejs_version: 16 - nodejs_version: 18
nodejs_architecture: arm64 nodejs_arch: arm64
prebuild: true prebuild: true
defaults: defaults:
run: run:
shell: /usr/bin/arch -arch arm64e /bin/bash -l {0} shell: /usr/bin/arch -arch arm64e /bin/bash -l {0}
steps: steps:
- name: Dependencies - name: Dependencies (Node.js)
uses: actions/setup-node@v2 uses: actions/setup-node@v3
with: with:
node-version: ${{ matrix.nodejs_version }} node-version: ${{ matrix.nodejs_version }}
architecture: ${{ matrix.nodejs_architecture }} architecture: ${{ matrix.nodejs_arch }}
- name: Checkout - name: Checkout
uses: actions/checkout@v2 uses: actions/checkout@v3
- name: Install - name: Install
run: npm install --build-from-source --unsafe-perm run: npm install --build-from-source --unsafe-perm
- name: Test - name: Test
@@ -33,4 +37,4 @@ jobs:
if: matrix.prebuild && startsWith(github.ref, 'refs/tags/') if: matrix.prebuild && startsWith(github.ref, 'refs/tags/')
env: env:
prebuild_upload: ${{ secrets.GITHUB_TOKEN }} prebuild_upload: ${{ secrets.GITHUB_TOKEN }}
run: npx prebuild --runtime napi --target 5 run: npx prebuild --runtime napi --target 7

View File

@@ -2,66 +2,95 @@ name: CI (GitHub)
on: on:
- push - push
- pull_request - pull_request
permissions: {}
jobs: jobs:
CI: CI:
permissions:
contents: write # for npx prebuild to make release
name: ${{ matrix.container || matrix.os }} - Node.js ${{ matrix.nodejs_version }} ${{ matrix.nodejs_arch }} ${{ matrix.prebuild && '- prebuild' }}
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-20.04 - os: ubuntu-22.04
container: centos:7
nodejs_version: 12
coverage: true
prebuild: true
- os: ubuntu-20.04
container: centos:7 container: centos:7
nodejs_version: 14 nodejs_version: 14
- os: ubuntu-20.04 prebuild: true
- os: ubuntu-22.04
container: centos:7 container: centos:7
nodejs_version: 16 nodejs_version: 16
- os: ubuntu-20.04 - os: ubuntu-22.04
container: node:12-alpine3.11 container: rockylinux:8
nodejs_version: 18
- os: ubuntu-22.04
container: node:14-alpine3.12
prebuild: true prebuild: true
- os: ubuntu-20.04 - os: ubuntu-22.04
container: node:14-alpine3.11 container: node:16-alpine3.12
- os: ubuntu-20.04 - os: ubuntu-22.04
container: node:14-alpine3.13 container: node:18-alpine3.14
- os: ubuntu-20.04 - os: macos-11
container: node:16-alpine3.11
- os: macos-10.15
nodejs_version: 12
prebuild: true
- os: macos-10.15
nodejs_version: 14 nodejs_version: 14
- os: macos-10.15
nodejs_version: 16
- os: windows-2019
nodejs_version: 12
prebuild: true prebuild: true
nodejs_arch: x64
- os: macos-11
nodejs_version: 16
nodejs_arch: x64
- os: macos-11
nodejs_version: 18
nodejs_arch: x64
- os: windows-2019 - os: windows-2019
nodejs_version: 14 nodejs_version: 14
nodejs_arch: x86
prebuild: true
- os: windows-2019 - os: windows-2019
nodejs_version: 16 nodejs_version: 16
nodejs_arch: x86
- os: windows-2019
nodejs_version: 18
nodejs_arch: x86
- os: windows-2019
nodejs_version: 14
nodejs_arch: x64
prebuild: true
- os: windows-2019
nodejs_version: 16
nodejs_arch: x64
- os: windows-2019
nodejs_version: 18
nodejs_arch: x64
steps: steps:
- name: Dependencies (Linux glibc) - name: Dependencies (Linux glibc)
if: contains(matrix.container, 'centos') if: contains(matrix.container, 'centos')
run: | run: |
curl -sL https://rpm.nodesource.com/setup_${{ matrix.nodejs_version }}.x | bash - curl -sL https://rpm.nodesource.com/setup_${{ matrix.nodejs_version }}.x | bash -
yum install -y centos-release-scl yum install -y centos-release-scl
yum install -y devtoolset-10-gcc-c++ make git python3 nodejs yum install -y devtoolset-11-gcc-c++ make git python3 nodejs fontconfig google-noto-sans-fonts
echo "/opt/rh/devtoolset-10/root/usr/bin" >> $GITHUB_PATH echo "/opt/rh/devtoolset-11/root/usr/bin" >> $GITHUB_PATH
- name: Dependencies (Rocky Linux glibc)
if: contains(matrix.container, 'rockylinux')
run: |
curl -sL https://rpm.nodesource.com/setup_${{ matrix.nodejs_version }}.x | bash -
dnf install -y gcc-toolset-11-gcc-c++ make git python3 nodejs fontconfig google-noto-sans-fonts
echo "/opt/rh/gcc-toolset-11/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 --update-cache run: apk add build-base git python3 font-noto --update-cache
- name: Dependencies (macOS, Windows) - name: Dependencies (Python 3.10 - macOS, Windows)
if: contains(matrix.os, 'macos') || contains(matrix.os, 'windows') if: contains(matrix.os, 'macos') || contains(matrix.os, 'windows')
uses: actions/setup-node@v1 uses: actions/setup-python@v4
with:
python-version: '3.10'
- name: Dependencies (Node.js - macOS, Windows)
if: contains(matrix.os, 'macos') || contains(matrix.os, 'windows')
uses: actions/setup-node@v3
with: with:
node-version: ${{ matrix.nodejs_version }} node-version: ${{ matrix.nodejs_version }}
architecture: ${{ matrix.nodejs_arch }}
- name: Checkout - name: Checkout
uses: actions/checkout@v2 uses: actions/checkout@v3
- name: Fix working directory ownership - name: Fix working directory ownership
if: matrix.container if: matrix.container
run: chown root.root . run: chown root.root .
@@ -69,13 +98,8 @@ jobs:
run: npm install --build-from-source --unsafe-perm run: npm install --build-from-source --unsafe-perm
- name: Test - name: Test
run: npm test run: npm test
- name: Coverage
if: matrix.coverage
uses: coverallsapp/github-action@v1.1.2
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Prebuild - name: Prebuild
if: matrix.prebuild && startsWith(github.ref, 'refs/tags/') if: matrix.prebuild && startsWith(github.ref, 'refs/tags/')
env: env:
prebuild_upload: ${{ secrets.GITHUB_TOKEN }} prebuild_upload: ${{ secrets.GITHUB_TOKEN }}
run: npx prebuild --runtime napi --target 5 run: npx prebuild --runtime napi --target 7

7
.mocharc.jsonc Normal file
View File

@@ -0,0 +1,7 @@
{
"parallel": true,
"slow": 1000,
"timeout": 30000,
"require": "./test/beforeEach.js",
"spec": "./test/unit/*.js"
}

View File

@@ -1,6 +1,6 @@
# sharp # sharp
<img src="https://cdn.jsdelivr.net/gh/lovell/sharp@master/docs/image/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right"> <img src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right">
The typical use case for this high speed Node.js module The typical use case for this high speed Node.js module
is to convert large images in common formats to is to convert large images in common formats to
@@ -16,7 +16,7 @@ Lanczos resampling ensures quality is not sacrificed for speed.
As well as image resizing, operations such as As well as image resizing, operations such as
rotation, extraction, compositing and gamma correction are available. rotation, extraction, compositing and gamma correction are available.
Most modern macOS, Windows and Linux systems running Node.js >= 12.13.0 Most modern macOS, Windows and Linux systems running Node.js >= 14.15.0
do not require any additional install or runtime dependencies. do not require any additional install or runtime dependencies.
## Documentation ## Documentation
@@ -95,10 +95,9 @@ readableStream
## Contributing ## Contributing
A [guide for contributors](https://github.com/lovell/sharp/blob/master/.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.
[![Test Coverage](https://coveralls.io/repos/lovell/sharp/badge.svg?branch=master)](https://coveralls.io/r/lovell/sharp?branch=master)
[![Node-API v5](https://img.shields.io/badge/Node--API-v5-green.svg)](https://nodejs.org/dist/latest/docs/api/n-api.html#n_api_n_api_version_matrix) [![Node-API v5](https://img.shields.io/badge/Node--API-v5-green.svg)](https://nodejs.org/dist/latest/docs/api/n-api.html#n_api_n_api_version_matrix)
## Licensing ## Licensing

View File

@@ -1,17 +0,0 @@
os: Visual Studio 2019
version: "{build}"
build: off
platform: x86
environment:
matrix:
- nodejs_version: "12"
prebuild: true
- nodejs_version: "14"
- nodejs_version: "16"
install:
- ps: Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version)
- npm install --build-from-source
test_script:
- npm test
on_success:
- if [%prebuild%] == [true] if [%APPVEYOR_REPO_TAG%] == [true] npx prebuild --runtime napi --target 5

View File

@@ -15,10 +15,11 @@
'_ALLOW_KEYWORD_MACROS' '_ALLOW_KEYWORD_MACROS'
], ],
'sources': [ 'sources': [
'src/libvips/cplusplus/VError.cpp',
'src/libvips/cplusplus/VConnection.cpp', 'src/libvips/cplusplus/VConnection.cpp',
'src/libvips/cplusplus/VError.cpp',
'src/libvips/cplusplus/VImage.cpp',
'src/libvips/cplusplus/VInterpolate.cpp', 'src/libvips/cplusplus/VInterpolate.cpp',
'src/libvips/cplusplus/VImage.cpp' 'src/libvips/cplusplus/VRegion.cpp'
], ],
'include_dirs': [ 'include_dirs': [
'<(sharp_vendor_dir)/include', '<(sharp_vendor_dir)/include',
@@ -39,7 +40,6 @@
'VCCLCompilerTool': { 'VCCLCompilerTool': {
'ExceptionHandling': 1, 'ExceptionHandling': 1,
'Optimization': 1, 'Optimization': 1,
'RuntimeLibrary': '2', # /MD
'WholeProgramOptimization': 'true' 'WholeProgramOptimization': 'true'
}, },
'VCLibrarianTool': { 'VCLibrarianTool': {
@@ -70,7 +70,7 @@
}, { }, {
'target_name': 'sharp-<(platform_and_arch)', 'target_name': 'sharp-<(platform_and_arch)',
'defines': [ 'defines': [
'NAPI_VERSION=5' 'NAPI_VERSION=7'
], ],
'dependencies': [ 'dependencies': [
'<!(node -p "require(\'node-addon-api\').gyp")', '<!(node -p "require(\'node-addon-api\').gyp")',
@@ -206,7 +206,6 @@
'VCCLCompilerTool': { 'VCCLCompilerTool': {
'ExceptionHandling': 1, 'ExceptionHandling': 1,
'Optimization': 1, 'Optimization': 1,
'RuntimeLibrary': '2', # /MD
'WholeProgramOptimization': 'true' 'WholeProgramOptimization': 'true'
}, },
'VCLibrarianTool': { 'VCLibrarianTool': {

View File

@@ -1,6 +1,6 @@
# sharp # sharp
<img src="https://cdn.jsdelivr.net/gh/lovell/sharp@master/docs/image/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right"> <img src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right">
The typical use case for this high speed Node.js module The typical use case for this high speed Node.js module
is to convert large images in common formats to is to convert large images in common formats to
@@ -16,7 +16,7 @@ Lanczos resampling ensures quality is not sacrificed for speed.
As well as image resizing, operations such as As well as image resizing, operations such as
rotation, extraction, compositing and gamma correction are available. rotation, extraction, compositing and gamma correction are available.
Most modern macOS, Windows and Linux systems running Node.js >= 12.13.0 Most modern macOS, Windows and Linux systems running Node.js >= 14.15.0
do not require any additional install or runtime dependencies. do not require any additional install or runtime dependencies.
### Formats ### Formats
@@ -63,9 +63,13 @@ PNG filtering is disabled by default,
which for diagrams and line art often produces the same result which for diagrams and line art often produces the same result
as [pngcrush](https://pmt.sourceforge.io/pngcrush/). as [pngcrush](https://pmt.sourceforge.io/pngcrush/).
The file size of animated GIF output is optimised
without having to use separate command line tools such as
[gifsicle](https://www.lcdf.org/gifsicle/).
### Contributing ### Contributing
A [guide for contributors](https://github.com/lovell/sharp/blob/master/.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

View File

@@ -16,7 +16,7 @@ sharp('rgba.png')
}); });
``` ```
Returns **Sharp** Returns **Sharp**&#x20;
## ensureAlpha ## ensureAlpha
@@ -47,7 +47,7 @@ const rgba = await sharp(rgb)
* Throws **[Error][3]** Invalid alpha transparency level * Throws **[Error][3]** Invalid alpha transparency level
Returns **Sharp** Returns **Sharp**&#x20;
**Meta** **Meta**
@@ -80,7 +80,7 @@ const [red1, red2, ...] = await sharp(input)
* Throws **[Error][3]** Invalid channel * Throws **[Error][3]** Invalid channel
Returns **Sharp** Returns **Sharp**&#x20;
## joinChannel ## joinChannel
@@ -104,7 +104,7 @@ For raw pixel input, the `options` object should contain a `raw` attribute, whic
* Throws **[Error][3]** Invalid parameters * Throws **[Error][3]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
## bandbool ## bandbool
@@ -128,7 +128,7 @@ sharp('3-channel-rgb-input.png')
* Throws **[Error][3]** Invalid parameters * Throws **[Error][3]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
[1]: /api-operation#flatten [1]: /api-operation#flatten

View File

@@ -9,11 +9,17 @@ An alpha channel may be present and will be unchanged by the operation.
* `rgb` **([string][1] | [Object][2])** parsed by the [color][3] module to extract chroma values. * `rgb` **([string][1] | [Object][2])** parsed by the [color][3] module to extract chroma values.
<!----> ### Examples
```javascript
const output = await sharp(input)
.tint({ r: 255, g: 240, b: 16 })
.toBuffer();
```
* Throws **[Error][4]** Invalid parameter * Throws **[Error][4]** Invalid parameter
Returns **Sharp** Returns **Sharp**&#x20;
## greyscale ## greyscale
@@ -28,7 +34,13 @@ An alpha channel may be present, and will be unchanged by the operation.
* `greyscale` **[Boolean][5]** (optional, default `true`) * `greyscale` **[Boolean][5]** (optional, default `true`)
Returns **Sharp** ### Examples
```javascript
const output = await sharp(input).greyscale().toBuffer();
```
Returns **Sharp**&#x20;
## grayscale ## grayscale
@@ -38,7 +50,7 @@ Alternative spelling of `greyscale`.
* `grayscale` **[Boolean][5]** (optional, default `true`) * `grayscale` **[Boolean][5]** (optional, default `true`)
Returns **Sharp** Returns **Sharp**&#x20;
## pipelineColourspace ## pipelineColourspace
@@ -65,7 +77,7 @@ await sharp(input)
* Throws **[Error][4]** Invalid parameters * Throws **[Error][4]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
**Meta** **Meta**
@@ -83,7 +95,7 @@ Alternative spelling of `pipelineColourspace`.
* Throws **[Error][4]** Invalid parameters * Throws **[Error][4]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
## toColourspace ## toColourspace
@@ -105,7 +117,7 @@ await sharp(input)
* Throws **[Error][4]** Invalid parameters * Throws **[Error][4]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
## toColorspace ## toColorspace
@@ -119,7 +131,7 @@ Alternative spelling of `toColourspace`.
* Throws **[Error][4]** Invalid parameters * Throws **[Error][4]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String [1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String

View File

@@ -7,6 +7,9 @@ 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 or rotate operations in the same processing pipeline
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`,
`xor`, `add`, `saturate`, `multiply`, `screen`, `overlay`, `darken`, `lighten`, `xor`, `add`, `saturate`, `multiply`, `screen`, `overlay`, `darken`, `lighten`,
@@ -14,7 +17,7 @@ The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`,
`hard-light`, `soft-light`, `difference`, `exclusion`. `hard-light`, `soft-light`, `difference`, `exclusion`.
More information about blend modes can be found at More information about blend modes can be found at
[https://libvips.github.io/libvips/API/current/libvips-conversion.html#VipsBlendMode][1] [https://www.libvips.org/API/current/libvips-conversion.html#VipsBlendMode][1]
and [https://www.cairographics.org/operators/][2] and [https://www.cairographics.org/operators/][2]
### Parameters ### Parameters
@@ -25,10 +28,22 @@ and [https://www.cairographics.org/operators/][2]
* `images[].input.create` **[Object][4]?** describes a blank overlay to be created. * `images[].input.create` **[Object][4]?** describes a blank overlay to be created.
* `images[].input.create.width` **[Number][7]?** * `images[].input.create.width` **[Number][7]?**&#x20;
* `images[].input.create.height` **[Number][7]?** * `images[].input.create.height` **[Number][7]?**&#x20;
* `images[].input.create.channels` **[Number][7]?** 3-4 * `images[].input.create.channels` **[Number][7]?** 3-4
* `images[].input.create.background` **([String][6] | [Object][4])?** parsed by the [color][8] module to extract values for red, green, blue and alpha. * `images[].input.create.background` **([String][6] | [Object][4])?** parsed by the [color][8] module to extract values for red, green, blue and alpha.
* `images[].input.text` **[Object][4]?** describes a new text image to be created.
* `images[].input.text.text` **[string][6]?** text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.
* `images[].input.text.font` **[string][6]?** font name to render with.
* `images[].input.text.fontfile` **[string][6]?** absolute filesystem path to a font file that can be used by `font`.
* `images[].input.text.width` **[number][7]** integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. (optional, default `0`)
* `images[].input.text.height` **[number][7]** integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. (optional, default `0`)
* `images[].input.text.align` **[string][6]** text alignment (`'left'`, `'centre'`, `'center'`, `'right'`). (optional, default `'left'`)
* `images[].input.text.justify` **[boolean][9]** set this to true to apply justification to the text. (optional, default `false`)
* `images[].input.text.dpi` **[number][7]** the resolution (size) at which to render the text. Does not take effect if `height` is specified. (optional, default `72`)
* `images[].input.text.rgba` **[boolean][9]** set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`. (optional, default `false`)
* `images[].input.text.spacing` **[number][7]** text line height in points. Will use the font line height if none is specified. (optional, default `0`)
* `images[].blend` **[String][6]** how to blend this image with the image below. (optional, default `'over'`) * `images[].blend` **[String][6]** how to blend this image with the image below. (optional, default `'over'`)
* `images[].gravity` **[String][6]** gravity at which to place the overlay. (optional, default `'centre'`) * `images[].gravity` **[String][6]** gravity at which to place the overlay. (optional, default `'centre'`)
* `images[].top` **[Number][7]?** the pixel offset from the top edge. * `images[].top` **[Number][7]?** the pixel offset from the top edge.
@@ -38,14 +53,32 @@ and [https://www.cairographics.org/operators/][2]
* `images[].density` **[Number][7]** number representing the DPI for vector overlay image. (optional, default `72`) * `images[].density` **[Number][7]** number representing the DPI for vector overlay image. (optional, default `72`)
* `images[].raw` **[Object][4]?** describes overlay when using raw pixel data. * `images[].raw` **[Object][4]?** describes overlay when using raw pixel data.
* `images[].raw.width` **[Number][7]?** * `images[].raw.width` **[Number][7]?**&#x20;
* `images[].raw.height` **[Number][7]?** * `images[].raw.height` **[Number][7]?**&#x20;
* `images[].raw.channels` **[Number][7]?** * `images[].raw.channels` **[Number][7]?**&#x20;
* `images[].failOnError` **[boolean][9]** @see [constructor parameters][10] (optional, default `true`) * `images[].animated` **[boolean][9]** Set to `true` to read all frames/pages of an animated image. (optional, default `false`)
* `images[].failOn` **[string][6]** @see [constructor parameters][10] (optional, default `'warning'`)
* `images[].limitInputPixels` **([number][7] | [boolean][9])** @see [constructor parameters][10] (optional, default `268402689`) * `images[].limitInputPixels` **([number][7] | [boolean][9])** @see [constructor parameters][10] (optional, default `268402689`)
### Examples ### Examples
```javascript
await sharp(background)
.composite([
{ input: layer1, gravity: 'northwest' },
{ input: layer2, gravity: 'southeast' },
])
.toFile('combined.png');
```
```javascript
const output = await sharp('input.gif', { animated: true })
.composite([
{ input: 'overlay.png', tile: true, blend: 'saturate' }
])
.toBuffer();
```
```javascript ```javascript
sharp('input.png') sharp('input.png')
.rotate(180) .rotate(180)
@@ -65,13 +98,13 @@ sharp('input.png')
* Throws **[Error][11]** Invalid parameters * Throws **[Error][11]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
**Meta** **Meta**
* **since**: 0.22.0 * **since**: 0.22.0
[1]: https://libvips.github.io/libvips/API/current/libvips-conversion.html#VipsBlendMode [1]: https://www.libvips.org/API/current/libvips-conversion.html#VipsBlendMode
[2]: https://www.cairographics.org/operators/ [2]: https://www.cairographics.org/operators/

View File

@@ -20,38 +20,49 @@ Implements the [stream.Duplex][1] class.
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.
* `options` **[Object][13]?** if present, is an Object with optional attributes. * `options` **[Object][13]?** if present, is an Object with optional attributes.
* `options.failOnError` **[boolean][14]** by default halt processing and raise an error when loading invalid images. * `options.failOn` **[string][12]** when to abort processing of invalid pixel data, one of (in order of sensitivity): 'none' (least), 'truncated', 'error' or 'warning' (most), highers level imply lower levels, invalid metadata will always abort. (optional, default `'warning'`)
Set this flag to `false` if you'd rather apply a "best effort" to decode images, even if the data is corrupt or invalid. (optional, default `true`) * `options.limitInputPixels` **([number][14] | [boolean][15])** Do not process input images where the number of pixels
* `options.limitInputPixels` **([number][15] | [boolean][14])** 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. (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted.
An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). (optional, default `268402689`) An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). (optional, default `268402689`)
* `options.unlimited` **[boolean][14]** Set this to `true` to remove safety features that help prevent memory exhaustion (SVG, PNG). (optional, default `false`) * `options.unlimited` **[boolean][15]** Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). (optional, default `false`)
* `options.sequentialRead` **[boolean][14]** Set this to `true` to use sequential rather than random access where possible. * `options.sequentialRead` **[boolean][15]** Set this to `true` to use sequential rather than random access where possible.
This can reduce memory usage and might improve performance on some systems. (optional, default `false`) This can reduce memory usage and might improve performance on some systems. (optional, default `false`)
* `options.density` **[number][15]** number representing the DPI for vector images in the range 1 to 100000. (optional, default `72`) * `options.density` **[number][14]** number representing the DPI for vector images in the range 1 to 100000. (optional, default `72`)
* `options.pages` **[number][15]** number of pages to extract for multi-page input (GIF, WebP, AVIF, TIFF, PDF), use -1 for all pages. (optional, default `1`) * `options.pages` **[number][14]** number of pages to extract for multi-page input (GIF, WebP, AVIF, TIFF, PDF), use -1 for all pages. (optional, default `1`)
* `options.page` **[number][15]** page number to start extracting from for multi-page input (GIF, WebP, AVIF, TIFF, PDF), zero based. (optional, default `0`) * `options.page` **[number][14]** page number to start extracting from for multi-page input (GIF, WebP, AVIF, TIFF, PDF), zero based. (optional, default `0`)
* `options.subifd` **[number][15]** subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. (optional, default `-1`) * `options.subifd` **[number][14]** subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. (optional, default `-1`)
* `options.level` **[number][15]** level to extract from a multi-level input (OpenSlide), zero based. (optional, default `0`) * `options.level` **[number][14]** level to extract from a multi-level input (OpenSlide), zero based. (optional, default `0`)
* `options.animated` **[boolean][14]** Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). (optional, default `false`) * `options.animated` **[boolean][15]** Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). (optional, default `false`)
* `options.raw` **[Object][13]?** describes raw pixel input image data. See `raw()` for pixel ordering. * `options.raw` **[Object][13]?** describes raw pixel input image data. See `raw()` for pixel ordering.
* `options.raw.width` **[number][15]?** integral number of pixels wide. * `options.raw.width` **[number][14]?** integral number of pixels wide.
* `options.raw.height` **[number][15]?** integral number of pixels high. * `options.raw.height` **[number][14]?** integral number of pixels high.
* `options.raw.channels` **[number][15]?** integral number of channels, between 1 and 4. * `options.raw.channels` **[number][14]?** integral number of channels, between 1 and 4.
* `options.raw.premultiplied` **[boolean][14]?** specifies that the raw input has already been premultiplied, set to `true` * `options.raw.premultiplied` **[boolean][15]?** specifies that the raw input has already been premultiplied, set to `true`
to avoid sharp premultiplying the image. (optional, default `false`) to avoid sharp premultiplying the image. (optional, default `false`)
* `options.create` **[Object][13]?** describes a new image to be created. * `options.create` **[Object][13]?** describes a new image to be created.
* `options.create.width` **[number][15]?** integral number of pixels wide. * `options.create.width` **[number][14]?** integral number of pixels wide.
* `options.create.height` **[number][15]?** integral number of pixels high. * `options.create.height` **[number][14]?** integral number of pixels high.
* `options.create.channels` **[number][15]?** integral number of channels, either 3 (RGB) or 4 (RGBA). * `options.create.channels` **[number][14]?** integral number of channels, either 3 (RGB) or 4 (RGBA).
* `options.create.background` **([string][12] | [Object][13])?** parsed by the [color][16] module to extract values for red, green, blue and alpha. * `options.create.background` **([string][12] | [Object][13])?** parsed by the [color][16] module to extract values for red, green, blue and alpha.
* `options.create.noise` **[Object][13]?** describes a noise to be created. * `options.create.noise` **[Object][13]?** describes a noise to be created.
* `options.create.noise.type` **[string][12]?** type of generated noise, currently only `gaussian` is supported. * `options.create.noise.type` **[string][12]?** type of generated noise, currently only `gaussian` is supported.
* `options.create.noise.mean` **[number][15]?** mean of pixels in generated noise. * `options.create.noise.mean` **[number][14]?** mean of pixels in generated noise.
* `options.create.noise.sigma` **[number][15]?** standard deviation of pixels in generated noise. * `options.create.noise.sigma` **[number][14]?** standard deviation of pixels in generated noise.
* `options.text` **[Object][13]?** describes a new text image to be created.
* `options.text.text` **[string][12]?** text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.
* `options.text.font` **[string][12]?** font name to render with.
* `options.text.fontfile` **[string][12]?** absolute filesystem path to a font file that can be used by `font`.
* `options.text.width` **[number][14]** integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. (optional, default `0`)
* `options.text.height` **[number][14]** integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. (optional, default `0`)
* `options.text.align` **[string][12]** text alignment (`'left'`, `'centre'`, `'center'`, `'right'`). (optional, default `'left'`)
* `options.text.justify` **[boolean][15]** set this to true to apply justification to the text. (optional, default `false`)
* `options.text.dpi` **[number][14]** the resolution (size) at which to render the text. Does not take effect if `height` is specified. (optional, default `72`)
* `options.text.rgba` **[boolean][15]** set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`. (optional, default `false`)
* `options.text.spacing` **[number][14]** text line height in points. Will use the font line height if none is specified. (optional, default `0`)
### Examples ### Examples
@@ -128,9 +139,32 @@ await sharp({
}).toFile('noise.png'); }).toFile('noise.png');
``` ```
```javascript
// Generate an image from text
await sharp({
text: {
text: 'Hello, world!',
width: 400, // max width
height: 300 // max height
}
}).toFile('text_bw.png');
```
```javascript
// Generate an rgba image from text using pango markup and font
await sharp({
text: {
text: '<span foreground="red">Red!</span><span background="cyan">blue</span>',
font: 'sans',
rgba: true,
dpi: 300
}
}).toFile('text_rgba.png');
```
* Throws **[Error][17]** Invalid parameters * Throws **[Error][17]** Invalid parameters
Returns **[Sharp][18]** Returns **[Sharp][18]**&#x20;
## clone ## clone
@@ -154,9 +188,7 @@ readableStream.pipe(pipeline);
// Using Promises to know when the pipeline is complete // Using Promises to know when the pipeline is complete
const fs = require("fs"); const fs = require("fs");
const got = require("got"); const got = require("got");
const sharpStream = sharp({ const sharpStream = sharp({ failOn: 'none' });
failOnError: false
});
const promises = []; const promises = [];
@@ -183,7 +215,7 @@ promises.push(
.toFile("optimized-500.webp") .toFile("optimized-500.webp")
); );
// https://github.com/sindresorhus/got#gotstreamurl-options // https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md
got.stream("https://www.example.com/some-file.jpg").pipe(sharpStream); got.stream("https://www.example.com/some-file.jpg").pipe(sharpStream);
Promise.all(promises) Promise.all(promises)
@@ -198,7 +230,7 @@ Promise.all(promises)
}); });
``` ```
Returns **[Sharp][18]** Returns **[Sharp][18]**&#x20;
[1]: http://nodejs.org/api/stream.html#stream_class_stream_duplex [1]: http://nodejs.org/api/stream.html#stream_class_stream_duplex
@@ -226,9 +258,9 @@ Returns **[Sharp][18]**
[13]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object [13]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[14]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean [14]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
[15]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number [15]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[16]: https://www.npmjs.org/package/color [16]: https://www.npmjs.org/package/color

View File

@@ -7,15 +7,18 @@ Fast access to (uncached) image metadata without decoding any compressed pixel d
This is taken from the header of the input image. This is taken from the header of the input image.
It does not include operations, such as resize, to be applied to the output image. It does not include operations, such as resize, to be applied to the output image.
Dimensions in the response will respect the `page` and `pages` properties of the
[constructor parameters][1].
A `Promise` is returned when `callback` is not provided. A `Promise` is returned when `callback` is not provided.
* `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg` * `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg`
* `size`: Total size of image in bytes, for Stream and Buffer input only * `size`: Total size of image in bytes, for Stream and Buffer input only
* `width`: Number of pixels wide (EXIF orientation is not taken into consideration) * `width`: Number of pixels wide (EXIF orientation is not taken into consideration, see example below)
* `height`: Number of pixels high (EXIF orientation is not taken into consideration) * `height`: Number of pixels high (EXIF orientation is not taken into consideration, see example below)
* `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...][1] * `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...][2]
* `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK * `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK
* `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...][2] * `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...][3]
* `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
@@ -33,14 +36,14 @@ A `Promise` is returned when `callback` is not provided.
* `hasAlpha`: Boolean indicating the presence of an alpha transparency channel * `hasAlpha`: Boolean indicating the presence of an alpha transparency channel
* `orientation`: Number value of the EXIF Orientation header, if present * `orientation`: Number value of the EXIF Orientation header, if present
* `exif`: Buffer containing raw EXIF data, if present * `exif`: Buffer containing raw EXIF data, if present
* `icc`: Buffer containing raw [ICC][3] profile data, if present * `icc`: Buffer containing raw [ICC][4] 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
* `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present * `tifftagPhotoshop`: Buffer containing raw TIFFTAG\_PHOTOSHOP data, if present
### Parameters ### Parameters
* `callback` **[Function][4]?** called with the arguments `(err, metadata)` * `callback` **[Function][5]?** called with the arguments `(err, metadata)`
### Examples ### Examples
@@ -63,7 +66,19 @@ image
}); });
``` ```
Returns **([Promise][5]<[Object][6]> | Sharp)** ```javascript
// Based on EXIF rotation metadata, get the right-side-up width and height:
const size = getNormalSize(await sharp(input).metadata());
function getNormalSize({ width, height, orientation }) {
return (orientation || 0) >= 5
? { width: height, height: width }
: { width, height };
}
```
Returns **([Promise][6]<[Object][7]> | Sharp)**&#x20;
## stats ## stats
@@ -82,16 +97,16 @@ A `Promise` is returned when `callback` is not provided.
* `maxX` (x-coordinate of one of the pixel where the maximum lies) * `maxX` (x-coordinate of one of the pixel where the maximum lies)
* `maxY` (y-coordinate of one of the pixel where the maximum lies) * `maxY` (y-coordinate of one of the pixel where the maximum lies)
* `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque. * `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque.
* `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any (experimental) * `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any.
* `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any (experimental) * `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any.
* `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram (experimental) * `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram.
**Note**: Statistics are derived from the original input image. Any operations performed on the image must first be **Note**: Statistics are derived from the original input image. Any operations performed on the image must first be
written to a buffer in order to run `stats` on the result (see third example). written to a buffer in order to run `stats` on the result (see third example).
### Parameters ### Parameters
* `callback` **[Function][4]?** called with the arguments `(err, stats)` * `callback` **[Function][5]?** called with the arguments `(err, stats)`
### Examples ### Examples
@@ -117,16 +132,18 @@ const part = await image.extract(region).toBuffer();
const stats = await sharp(part).stats(); const stats = await sharp(part).stats();
``` ```
Returns **[Promise][5]<[Object][6]>** Returns **[Promise][6]<[Object][7]>**&#x20;
[1]: https://libvips.github.io/libvips/API/current/VipsImage.html#VipsInterpretation [1]: /api-constructor#parameters
[2]: https://libvips.github.io/libvips/API/current/VipsImage.html#VipsBandFormat [2]: https://www.libvips.org/API/current/VipsImage.html#VipsInterpretation
[3]: https://www.npmjs.com/package/icc [3]: https://www.libvips.org/API/current/VipsImage.html#VipsBandFormat
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function [4]: https://www.npmjs.com/package/icc
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise [5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object [6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise
[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object

View File

@@ -16,8 +16,11 @@ 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` implies the removal of the EXIF `Orientation` tag, if any.
Method order is important when both rotating and extracting regions, Only one rotation can occur per pipeline.
for example `rotate(x).extract(y)` will produce a different result to `extract(y).rotate(x)`. Previous calls to `rotate` in the same pipeline will be ignored.
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)`.
### Parameters ### Parameters
@@ -40,31 +43,54 @@ const pipeline = sharp()
readableStream.pipe(pipeline); readableStream.pipe(pipeline);
``` ```
```javascript
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();
```
* Throws **[Error][5]** Invalid parameters * Throws **[Error][5]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
## flip ## flip
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 before 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.
### Parameters ### Parameters
* `flip` **[Boolean][6]** (optional, default `true`) * `flip` **[Boolean][6]** (optional, default `true`)
Returns **Sharp** ### Examples
```javascript
const output = await sharp(input).flip().toBuffer();
```
Returns **Sharp**&#x20;
## flop ## flop
Flop the image about the horizontal X axis. This always occurs after rotation, if any. Flop the image about the horizontal X axis. This always occurs before rotation, if any.
The use of `flop` implies the removal of the EXIF `Orientation` tag, if any. The use of `flop` implies the removal of the EXIF `Orientation` tag, if any.
### Parameters ### Parameters
* `flop` **[Boolean][6]** (optional, default `true`) * `flop` **[Boolean][6]** (optional, default `true`)
Returns **Sharp** ### Examples
```javascript
const output = await sharp(input).flop().toBuffer();
```
Returns **Sharp**&#x20;
## affine ## affine
@@ -116,7 +142,7 @@ inputStream
* Throws **[Error][5]** Invalid parameters * Throws **[Error][5]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
**Meta** **Meta**
@@ -125,21 +151,53 @@ Returns **Sharp**
## sharpen ## sharpen
Sharpen the image. Sharpen the image.
When used without parameters, performs a fast, mild sharpen of the output image. When used without parameters, performs a fast, mild sharpen of the output image.
When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space. When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space.
Separate control over the level of sharpening in "flat" and "jagged" areas is available. Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available.
See [libvips sharpen][8] operation.
### Parameters ### Parameters
* `sigma` **[number][1]?** the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. * `options` **([Object][2] | [number][1])?** if present, is an Object with attributes
* `flat` **[number][1]** the level of sharpening to apply to "flat" areas. (optional, default `1.0`)
* `jagged` **[number][1]** the level of sharpening to apply to "jagged" areas. (optional, default `2.0`)
<!----> * `options.sigma` **[number][1]?** the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`, between 0.000001 and 10000
* `options.m1` **[number][1]** the level of sharpening to apply to "flat" areas, between 0 and 1000000 (optional, default `1.0`)
* `options.m2` **[number][1]** the level of sharpening to apply to "jagged" areas, between 0 and 1000000 (optional, default `2.0`)
* `options.x1` **[number][1]** threshold between "flat" and "jagged", between 0 and 1000000 (optional, default `2.0`)
* `options.y2` **[number][1]** maximum amount of brightening, between 0 and 1000000 (optional, default `10.0`)
* `options.y3` **[number][1]** maximum amount of darkening, between 0 and 1000000 (optional, default `20.0`)
* `flat` **[number][1]?** (deprecated) see `options.m1`.
* `jagged` **[number][1]?** (deprecated) see `options.m2`.
### Examples
```javascript
const data = await sharp(input).sharpen().toBuffer();
```
```javascript
const data = await sharp(input).sharpen({ sigma: 2 }).toBuffer();
```
```javascript
const data = await sharp(input)
.sharpen({
sigma: 2,
m1: 0,
m2: 3,
x1: 3,
y2: 15,
y3: 15,
})
.toBuffer();
```
* Throws **[Error][5]** Invalid parameters * Throws **[Error][5]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
## median ## median
@@ -150,11 +208,19 @@ When used without parameters the default window is 3x3.
* `size` **[number][1]** square mask size: size x size (optional, default `3`) * `size` **[number][1]** square mask size: size x size (optional, default `3`)
<!----> ### Examples
```javascript
const output = await sharp(input).median().toBuffer();
```
```javascript
const output = await sharp(input).median(5).toBuffer();
```
* Throws **[Error][5]** Invalid parameters * Throws **[Error][5]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
## blur ## blur
@@ -184,17 +250,17 @@ const gaussianBlurred = await sharp(input)
* Throws **[Error][5]** Invalid parameters * Throws **[Error][5]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
## flatten ## flatten
Merge alpha transparency channel, if any, with a background, then remove the alpha channel. Merge alpha transparency channel, if any, with a background, then remove the alpha channel.
See also [removeAlpha][8]. See also [removeAlpha][9].
### Parameters ### Parameters
* `options` **[Object][2]?** * `options` **[Object][2]?**&#x20;
* `options.background` **([string][3] | [Object][2])** background colour, parsed by the [color][4] module, defaults to black. (optional, default `{r:0,g:0,b:0}`) * `options.background` **([string][3] | [Object][2])** background colour, parsed by the [color][4] module, defaults to black. (optional, default `{r:0,g:0,b:0}`)
@@ -206,7 +272,7 @@ await sharp(rgbaInput)
.toBuffer(); .toBuffer();
``` ```
Returns **Sharp** Returns **Sharp**&#x20;
## gamma ## gamma
@@ -227,7 +293,7 @@ Supply a second argument to use a different output gamma value, otherwise the fi
* Throws **[Error][5]** Invalid parameters * Throws **[Error][5]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
## negate ## negate
@@ -235,11 +301,25 @@ Produce the "negative" of the image.
### Parameters ### Parameters
* `options` **[Object][2]?** * `options` **[Object][2]?**&#x20;
* `options.alpha` **[Boolean][6]** Whether or not to negate any alpha channel (optional, default `true`) * `options.alpha` **[Boolean][6]** Whether or not to negate any alpha channel (optional, default `true`)
Returns **Sharp** ### Examples
```javascript
const output = await sharp(input)
.negate()
.toBuffer();
```
```javascript
const output = await sharp(input)
.negate({ alpha: false })
.toBuffer();
```
Returns **Sharp**&#x20;
## normalise ## normalise
@@ -249,7 +329,13 @@ Enhance output image contrast by stretching its luminance to cover the full dyna
* `normalise` **[Boolean][6]** (optional, default `true`) * `normalise` **[Boolean][6]** (optional, default `true`)
Returns **Sharp** ### Examples
```javascript
const output = await sharp(input).normalise().toBuffer();
```
Returns **Sharp**&#x20;
## normalize ## normalize
@@ -259,18 +345,24 @@ Alternative spelling of normalise.
* `normalize` **[Boolean][6]** (optional, default `true`) * `normalize` **[Boolean][6]** (optional, default `true`)
Returns **Sharp** ### Examples
```javascript
const output = await sharp(input).normalize().toBuffer();
```
Returns **Sharp**&#x20;
## clahe ## clahe
Perform contrast limiting adaptive histogram equalization Perform contrast limiting adaptive histogram equalization
[CLAHE][9]. [CLAHE][10].
This will, in general, enhance the clarity of the image by bringing out darker details. This will, in general, enhance the clarity of the image by bringing out darker details.
### Parameters ### Parameters
* `options` **[Object][2]** * `options` **[Object][2]**&#x20;
* `options.width` **[number][1]** integer width of the region in pixels. * `options.width` **[number][1]** integer width of the region in pixels.
* `options.height` **[number][1]** integer height of the region in pixels. * `options.height` **[number][1]** integer height of the region in pixels.
@@ -278,11 +370,20 @@ This will, in general, enhance the clarity of the image by bringing out darker d
cumulative histogram. A value of 0 disables contrast limiting. Valid values cumulative histogram. A value of 0 disables contrast limiting. Valid values
are integers in the range 0-100 (inclusive) (optional, default `3`) are integers in the range 0-100 (inclusive) (optional, default `3`)
<!----> ### Examples
```javascript
const output = await sharp(input)
.clahe({
width: 3,
height: 3,
})
.toBuffer();
```
* Throws **[Error][5]** Invalid parameters * Throws **[Error][5]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
**Meta** **Meta**
@@ -294,7 +395,7 @@ Convolve the image with the specified kernel.
### Parameters ### Parameters
* `kernel` **[Object][2]** * `kernel` **[Object][2]**&#x20;
* `kernel.width` **[number][1]** width of the kernel in pixels. * `kernel.width` **[number][1]** width of the kernel in pixels.
* `kernel.height` **[number][1]** height of the kernel in pixels. * `kernel.height` **[number][1]** height of the kernel in pixels.
@@ -320,7 +421,7 @@ sharp(input)
* Throws **[Error][5]** Invalid parameters * Throws **[Error][5]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
## threshold ## threshold
@@ -329,7 +430,7 @@ Any pixel value greater than or equal to the threshold value will be set to 255,
### Parameters ### Parameters
* `threshold` **[number][1]** a value in the range 0-255 representing the level at which the threshold will be applied. (optional, default `128`) * `threshold` **[number][1]** a value in the range 0-255 representing the level at which the threshold will be applied. (optional, default `128`)
* `options` **[Object][2]?** * `options` **[Object][2]?**&#x20;
* `options.greyscale` **[Boolean][6]** convert to single channel greyscale. (optional, default `true`) * `options.greyscale` **[Boolean][6]** convert to single channel greyscale. (optional, default `true`)
* `options.grayscale` **[Boolean][6]** alternative spelling for greyscale. (optional, default `true`) * `options.grayscale` **[Boolean][6]** alternative spelling for greyscale. (optional, default `true`)
@@ -338,7 +439,7 @@ Any pixel value greater than or equal to the threshold value will be set to 255,
* Throws **[Error][5]** Invalid parameters * Throws **[Error][5]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
## boolean ## boolean
@@ -349,36 +450,54 @@ the selected bitwise boolean `operation` between the corresponding pixels of the
### Parameters ### Parameters
* `operand` **([Buffer][10] | [string][3])** Buffer containing image data or string containing the path to an image file. * `operand` **([Buffer][11] | [string][3])** Buffer containing image data or string containing the path to an image file.
* `operator` **[string][3]** one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. * `operator` **[string][3]** one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.
* `options` **[Object][2]?** * `options` **[Object][2]?**&#x20;
* `options.raw` **[Object][2]?** describes operand when using raw pixel data. * `options.raw` **[Object][2]?** describes operand when using raw pixel data.
* `options.raw.width` **[number][1]?** * `options.raw.width` **[number][1]?**&#x20;
* `options.raw.height` **[number][1]?** * `options.raw.height` **[number][1]?**&#x20;
* `options.raw.channels` **[number][1]?** * `options.raw.channels` **[number][1]?**&#x20;
<!----> <!---->
* Throws **[Error][5]** Invalid parameters * Throws **[Error][5]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
## linear ## linear
Apply the linear formula a \* input + b to the image (levels adjustment) Apply the linear formula `a` \* input + `b` to the image to adjust image levels.
When a single number is provided, it will be used for all image channels.
When an array of numbers is provided, the array length must match the number of channels.
### Parameters ### Parameters
* `a` **[number][1]** multiplier (optional, default `1.0`) * `a` **([number][1] | [Array][7]<[number][1]>)** multiplier (optional, default `[]`)
* `b` **[number][1]** offset (optional, default `0.0`) * `b` **([number][1] | [Array][7]<[number][1]>)** offset (optional, default `[]`)
<!----> ### Examples
```javascript
await sharp(input)
.linear(0.5, 2)
.toBuffer();
```
```javascript
await sharp(rgbInput)
.linear(
[0.25, 0.5, 0.75],
[150, 100, 50]
)
.toBuffer();
```
* Throws **[Error][5]** Invalid parameters * Throws **[Error][5]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
## recomb ## recomb
@@ -406,7 +525,7 @@ sharp(input)
* Throws **[Error][5]** Invalid parameters * Throws **[Error][5]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
**Meta** **Meta**
@@ -420,7 +539,7 @@ brightness is multiplicative whereas lightness is additive.
### Parameters ### Parameters
* `options` **[Object][2]?** * `options` **[Object][2]?**&#x20;
* `options.brightness` **[number][1]?** Brightness multiplier * `options.brightness` **[number][1]?** Brightness multiplier
* `options.saturation` **[number][1]?** Saturation multiplier * `options.saturation` **[number][1]?** Saturation multiplier
@@ -430,31 +549,44 @@ brightness is multiplicative whereas lightness is additive.
### Examples ### Examples
```javascript ```javascript
sharp(input) // increase brightness by a factor of 2
const output = await sharp(input)
.modulate({ .modulate({
brightness: 2 // increase brightness by a factor of 2 brightness: 2
}); })
.toBuffer();
```
sharp(input) ```javascript
// hue-rotate by 180 degrees
const output = await sharp(input)
.modulate({ .modulate({
hue: 180 // hue-rotate by 180 degrees hue: 180
}); })
.toBuffer();
```
sharp(input) ```javascript
// increase lightness by +50
const output = await sharp(input)
.modulate({ .modulate({
lightness: 50 // increase lightness by +50 lightness: 50
}); })
.toBuffer();
```
```javascript
// decreate brightness and saturation while also hue-rotating by 90 degrees // decreate brightness and saturation while also hue-rotating by 90 degrees
sharp(input) const output = await sharp(input)
.modulate({ .modulate({
brightness: 0.5, brightness: 0.5,
saturation: 0.5, saturation: 0.5,
hue: 90 hue: 90,
}); })
.toBuffer();
``` ```
Returns **Sharp** Returns **Sharp**&#x20;
**Meta** **Meta**
@@ -474,8 +606,10 @@ Returns **Sharp**
[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array [7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
[8]: /api-channel#removealpha [8]: https://www.libvips.org/API/current/libvips-convolution.html#vips-sharpen
[9]: https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE [9]: /api-channel#removealpha
[10]: https://nodejs.org/api/buffer.html [10]: https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE
[11]: https://nodejs.org/api/buffer.html

View File

@@ -22,6 +22,7 @@ A `Promise` is returned when `callback` is not provided.
`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`.
May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.
### Examples ### Examples
@@ -46,6 +47,8 @@ Returns **[Promise][5]<[Object][6]>** when no callback is provided
Write output to a Buffer. Write output to a Buffer.
JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported. JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.
Use [toFormat][7] or one of the format-specific functions such as [jpeg][8], [png][9] etc. to set the output format.
If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output. If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output.
By default all metadata will be removed, which includes EXIF-based orientation. By default all metadata will be removed, which includes EXIF-based orientation.
@@ -56,18 +59,18 @@ See [withMetadata][1] for control over this.
* `err` is an error, if any. * `err` is an error, if any.
* `data` is the output image data. * `data` is the output image data.
* `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`. 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.
### Parameters ### Parameters
* `options` **[Object][6]?** * `options` **[Object][6]?**&#x20;
* `options.resolveWithObject` **[boolean][7]?** Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`. * `options.resolveWithObject` **[boolean][10]?** Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`.
* `callback` **[Function][3]?** * `callback` **[Function][3]?**&#x20;
### Examples ### Examples
@@ -85,6 +88,7 @@ sharp(input)
```javascript ```javascript
sharp(input) sharp(input)
.png()
.toBuffer({ resolveWithObject: true }) .toBuffer({ resolveWithObject: true })
.then(({ data, info }) => { ... }) .then(({ data, info }) => { ... })
.catch(err => { ... }); .catch(err => { ... });
@@ -107,7 +111,7 @@ await sharp(pixelArray, { raw: { width, height, channels } })
.toFile('my-changed-image.jpg'); .toFile('my-changed-image.jpg');
``` ```
Returns **[Promise][5]<[Buffer][8]>** when no callback is provided Returns **[Promise][5]<[Buffer][11]>** when no callback is provided
## withMetadata ## withMetadata
@@ -118,14 +122,16 @@ output profile is provided.
The default behaviour, when `withMetadata` is not used, is to convert to the device-independent The default behaviour, when `withMetadata` is not used, is to convert to the device-independent
sRGB colour space and strip all metadata, including the removal of any ICC profile. sRGB colour space and strip all metadata, including the removal of any ICC profile.
EXIF metadata is unsupported for TIFF output.
### Parameters ### Parameters
* `options` **[Object][6]?** * `options` **[Object][6]?**&#x20;
* `options.orientation` **[number][9]?** value between 1 and 8, used to update the EXIF `Orientation` tag. * `options.orientation` **[number][12]?** value between 1 and 8, used to update the EXIF `Orientation` tag.
* `options.icc` **[string][2]?** filesystem path to output ICC profile, defaults to sRGB. * `options.icc` **[string][2]?** filesystem path to output ICC profile, defaults to sRGB.
* `options.exif` **[Object][6]<[Object][6]>** Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. (optional, default `{}`) * `options.exif` **[Object][6]<[Object][6]>** Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. (optional, default `{}`)
* `options.density` **[number][9]?** Number of pixels per inch (DPI). * `options.density` **[number][12]?** Number of pixels per inch (DPI).
### Examples ### Examples
@@ -158,7 +164,7 @@ const data = await sharp(input)
* Throws **[Error][4]** Invalid parameters * Throws **[Error][4]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
## toFormat ## toFormat
@@ -180,7 +186,7 @@ const data = await sharp(input)
* Throws **[Error][4]** unsupported format or options * Throws **[Error][4]** unsupported format or options
Returns **Sharp** Returns **Sharp**&#x20;
## jpeg ## jpeg
@@ -190,19 +196,19 @@ Use these JPEG options for output image.
* `options` **[Object][6]?** output options * `options` **[Object][6]?** output options
* `options.quality` **[number][9]** quality, integer 1-100 (optional, default `80`) * `options.quality` **[number][12]** quality, integer 1-100 (optional, default `80`)
* `options.progressive` **[boolean][7]** use progressive (interlace) scan (optional, default `false`) * `options.progressive` **[boolean][10]** use progressive (interlace) scan (optional, default `false`)
* `options.chromaSubsampling` **[string][2]** set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling (optional, default `'4:2:0'`) * `options.chromaSubsampling` **[string][2]** set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling (optional, default `'4:2:0'`)
* `options.optimiseCoding` **[boolean][7]** optimise Huffman coding tables (optional, default `true`) * `options.optimiseCoding` **[boolean][10]** optimise Huffman coding tables (optional, default `true`)
* `options.optimizeCoding` **[boolean][7]** alternative spelling of optimiseCoding (optional, default `true`) * `options.optimizeCoding` **[boolean][10]** alternative spelling of optimiseCoding (optional, default `true`)
* `options.mozjpeg` **[boolean][7]** use mozjpeg defaults, equivalent to `{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }` (optional, default `false`) * `options.mozjpeg` **[boolean][10]** use mozjpeg defaults, equivalent to `{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }` (optional, default `false`)
* `options.trellisQuantisation` **[boolean][7]** apply trellis quantisation (optional, default `false`) * `options.trellisQuantisation` **[boolean][10]** apply trellis quantisation (optional, default `false`)
* `options.overshootDeringing` **[boolean][7]** apply overshoot deringing (optional, default `false`) * `options.overshootDeringing` **[boolean][10]** apply overshoot deringing (optional, default `false`)
* `options.optimiseScans` **[boolean][7]** optimise progressive scans, forces progressive (optional, default `false`) * `options.optimiseScans` **[boolean][10]** optimise progressive scans, forces progressive (optional, default `false`)
* `options.optimizeScans` **[boolean][7]** alternative spelling of optimiseScans (optional, default `false`) * `options.optimizeScans` **[boolean][10]** alternative spelling of optimiseScans (optional, default `false`)
* `options.quantisationTable` **[number][9]** quantization table to use, integer 0-8 (optional, default `0`) * `options.quantisationTable` **[number][12]** quantization table to use, integer 0-8 (optional, default `0`)
* `options.quantizationTable` **[number][9]** alternative spelling of quantisationTable (optional, default `0`) * `options.quantizationTable` **[number][12]** alternative spelling of quantisationTable (optional, default `0`)
* `options.force` **[boolean][7]** force JPEG output, otherwise attempt to use input format (optional, default `true`) * `options.force` **[boolean][10]** force JPEG output, otherwise attempt to use input format (optional, default `true`)
### Examples ### Examples
@@ -225,7 +231,7 @@ const data = await sharp(input)
* Throws **[Error][4]** Invalid options * Throws **[Error][4]** Invalid options
Returns **Sharp** Returns **Sharp**&#x20;
## png ## png
@@ -237,18 +243,18 @@ Set `palette` to `true` for slower, indexed PNG output.
### Parameters ### Parameters
* `options` **[Object][6]?** * `options` **[Object][6]?**&#x20;
* `options.progressive` **[boolean][7]** use progressive (interlace) scan (optional, default `false`) * `options.progressive` **[boolean][10]** use progressive (interlace) scan (optional, default `false`)
* `options.compressionLevel` **[number][9]** zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest) (optional, default `6`) * `options.compressionLevel` **[number][12]** zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest) (optional, default `6`)
* `options.adaptiveFiltering` **[boolean][7]** use adaptive row filtering (optional, default `false`) * `options.adaptiveFiltering` **[boolean][10]** use adaptive row filtering (optional, default `false`)
* `options.palette` **[boolean][7]** quantise to a palette-based image with alpha transparency support (optional, default `false`) * `options.palette` **[boolean][10]** quantise to a palette-based image with alpha transparency support (optional, default `false`)
* `options.quality` **[number][9]** use the lowest number of colours needed to achieve given quality, sets `palette` to `true` (optional, default `100`) * `options.quality` **[number][12]** use the lowest number of colours needed to achieve given quality, sets `palette` to `true` (optional, default `100`)
* `options.effort` **[number][9]** CPU effort, between 1 (fastest) and 10 (slowest), sets `palette` to `true` (optional, default `7`) * `options.effort` **[number][12]** CPU effort, between 1 (fastest) and 10 (slowest), sets `palette` to `true` (optional, default `7`)
* `options.colours` **[number][9]** maximum number of palette entries, sets `palette` to `true` (optional, default `256`) * `options.colours` **[number][12]** maximum number of palette entries, sets `palette` to `true` (optional, default `256`)
* `options.colors` **[number][9]** alternative spelling of `options.colours`, sets `palette` to `true` (optional, default `256`) * `options.colors` **[number][12]** alternative spelling of `options.colours`, sets `palette` to `true` (optional, default `256`)
* `options.dither` **[number][9]** level of Floyd-Steinberg error diffusion, sets `palette` to `true` (optional, default `1.0`) * `options.dither` **[number][12]** level of Floyd-Steinberg error diffusion, sets `palette` to `true` (optional, default `1.0`)
* `options.force` **[boolean][7]** force PNG output, otherwise attempt to use input format (optional, default `true`) * `options.force` **[boolean][10]** force PNG output, otherwise attempt to use input format (optional, default `true`)
### Examples ### Examples
@@ -268,7 +274,7 @@ const data = await sharp(input)
* Throws **[Error][4]** Invalid options * Throws **[Error][4]** Invalid options
Returns **Sharp** Returns **Sharp**&#x20;
## webp ## webp
@@ -278,15 +284,17 @@ Use these WebP options for output image.
* `options` **[Object][6]?** output options * `options` **[Object][6]?** output options
* `options.quality` **[number][9]** quality, integer 1-100 (optional, default `80`) * `options.quality` **[number][12]** quality, integer 1-100 (optional, default `80`)
* `options.alphaQuality` **[number][9]** quality of alpha layer, integer 0-100 (optional, default `100`) * `options.alphaQuality` **[number][12]** quality of alpha layer, integer 0-100 (optional, default `100`)
* `options.lossless` **[boolean][7]** use lossless compression mode (optional, default `false`) * `options.lossless` **[boolean][10]** use lossless compression mode (optional, default `false`)
* `options.nearLossless` **[boolean][7]** use near_lossless compression mode (optional, default `false`) * `options.nearLossless` **[boolean][10]** use near\_lossless compression mode (optional, default `false`)
* `options.smartSubsample` **[boolean][7]** use high quality chroma subsampling (optional, default `false`) * `options.smartSubsample` **[boolean][10]** use high quality chroma subsampling (optional, default `false`)
* `options.effort` **[number][9]** CPU effort, between 0 (fastest) and 6 (slowest) (optional, default `4`) * `options.effort` **[number][12]** CPU effort, between 0 (fastest) and 6 (slowest) (optional, default `4`)
* `options.loop` **[number][9]** number of animation iterations, use 0 for infinite animation (optional, default `0`) * `options.loop` **[number][12]** number of animation iterations, use 0 for infinite animation (optional, default `0`)
* `options.delay` **([number][9] | [Array][10]<[number][9]>)?** delay(s) between animation frames (in milliseconds) * `options.delay` **([number][12] | [Array][13]<[number][12]>)?** delay(s) between animation frames (in milliseconds)
* `options.force` **[boolean][7]** force WebP output, otherwise attempt to use input format (optional, default `true`) * `options.minSize` **[boolean][10]** prevent use of animation key frames to minimise file size (slow) (optional, default `false`)
* `options.mixed` **[boolean][10]** allow mixture of lossy and lossless animation frames (slow) (optional, default `false`)
* `options.force` **[boolean][10]** force WebP output, otherwise attempt to use input format (optional, default `true`)
### Examples ### Examples
@@ -306,7 +314,7 @@ const outputWebp = await sharp(inputWebp, { animated: true })
* Throws **[Error][4]** Invalid options * Throws **[Error][4]** Invalid options
Returns **Sharp** Returns **Sharp**&#x20;
## gif ## gif
@@ -314,17 +322,23 @@ Use these GIF options for the output image.
The first entry in the palette is reserved for transparency. The first entry in the palette is reserved for transparency.
The palette of the input image will be re-used if possible.
### Parameters ### Parameters
* `options` **[Object][6]?** output options * `options` **[Object][6]?** output options
* `options.colours` **[number][9]** maximum number of palette entries, including transparency, between 2 and 256 (optional, default `256`) * `options.reoptimise` **[boolean][10]** always generate new palettes (slow), re-use existing by default (optional, default `false`)
* `options.colors` **[number][9]** alternative spelling of `options.colours` (optional, default `256`) * `options.reoptimize` **[boolean][10]** alternative spelling of `options.reoptimise` (optional, default `false`)
* `options.effort` **[number][9]** CPU effort, between 1 (fastest) and 10 (slowest) (optional, default `7`) * `options.colours` **[number][12]** maximum number of palette entries, including transparency, between 2 and 256 (optional, default `256`)
* `options.dither` **[number][9]** level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) (optional, default `1.0`) * `options.colors` **[number][12]** alternative spelling of `options.colours` (optional, default `256`)
* `options.loop` **[number][9]** number of animation iterations, use 0 for infinite animation (optional, default `0`) * `options.effort` **[number][12]** CPU effort, between 1 (fastest) and 10 (slowest) (optional, default `7`)
* `options.delay` **([number][9] | [Array][10]<[number][9]>)?** delay(s) between animation frames (in milliseconds) * `options.dither` **[number][12]** level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) (optional, default `1.0`)
* `options.force` **[boolean][7]** force GIF output, otherwise attempt to use input format (optional, default `true`) * `options.interFrameMaxError` **[number][12]** maximum inter-frame error for transparency, between 0 (lossless) and 32 (optional, default `0`)
* `options.interPaletteMaxError` **[number][12]** maximum inter-palette error for palette reuse, between 0 and 256 (optional, default `3`)
* `options.loop` **[number][12]** number of animation iterations, use 0 for infinite animation (optional, default `0`)
* `options.delay` **([number][12] | [Array][13]<[number][12]>)?** delay(s) between animation frames (in milliseconds)
* `options.force` **[boolean][10]** force GIF output, otherwise attempt to use input format (optional, default `true`)
### Examples ### Examples
@@ -332,7 +346,7 @@ The first entry in the palette is reserved for transparency.
// Convert PNG to GIF // Convert PNG to GIF
await sharp(pngBuffer) await sharp(pngBuffer)
.gif() .gif()
.toBuffer()); .toBuffer();
``` ```
```javascript ```javascript
@@ -349,9 +363,16 @@ const out = await sharp('in.gif', { animated: true })
.toBuffer(); .toBuffer();
``` ```
```javascript
// Lossy file size reduction of animated GIF
await sharp('in.gif', { animated: true })
.gif({ interFrameMaxError: 8 })
.toFile('optim.gif');
```
* Throws **[Error][4]** Invalid options * Throws **[Error][4]** Invalid options
Returns **Sharp** Returns **Sharp**&#x20;
**Meta** **Meta**
@@ -363,16 +384,16 @@ Use these JP2 options for output image.
Requires libvips compiled with support for OpenJPEG. Requires libvips compiled with support for OpenJPEG.
The prebuilt binaries do not include this - see The prebuilt binaries do not include this - see
[installing a custom libvips][11]. [installing a custom libvips][14].
### Parameters ### Parameters
* `options` **[Object][6]?** output options * `options` **[Object][6]?** output options
* `options.quality` **[number][9]** quality, integer 1-100 (optional, default `80`) * `options.quality` **[number][12]** quality, integer 1-100 (optional, default `80`)
* `options.lossless` **[boolean][7]** use lossless compression mode (optional, default `false`) * `options.lossless` **[boolean][10]** use lossless compression mode (optional, default `false`)
* `options.tileWidth` **[number][9]** horizontal tile size (optional, default `512`) * `options.tileWidth` **[number][12]** horizontal tile size (optional, default `512`)
* `options.tileHeight` **[number][9]** vertical tile size (optional, default `512`) * `options.tileHeight` **[number][12]** vertical tile size (optional, default `512`)
* `options.chromaSubsampling` **[string][2]** set to '4:2:0' to use chroma subsampling (optional, default `'4:4:4'`) * `options.chromaSubsampling` **[string][2]** set to '4:2:0' to use chroma subsampling (optional, default `'4:4:4'`)
### Examples ### Examples
@@ -396,7 +417,7 @@ const data = await sharp(input)
* Throws **[Error][4]** Invalid options * Throws **[Error][4]** Invalid options
Returns **Sharp** Returns **Sharp**&#x20;
**Meta** **Meta**
@@ -412,18 +433,18 @@ The `density` can be set in pixels/inch via [withMetadata][1] instead of providi
* `options` **[Object][6]?** output options * `options` **[Object][6]?** output options
* `options.quality` **[number][9]** quality, integer 1-100 (optional, default `80`) * `options.quality` **[number][12]** quality, integer 1-100 (optional, default `80`)
* `options.force` **[boolean][7]** force TIFF output, otherwise attempt to use input format (optional, default `true`) * `options.force` **[boolean][10]** force TIFF output, otherwise attempt to use input format (optional, default `true`)
* `options.compression` **[string][2]** compression options: lzw, deflate, jpeg, ccittfax4 (optional, default `'jpeg'`) * `options.compression` **[string][2]** compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k (optional, default `'jpeg'`)
* `options.predictor` **[string][2]** compression predictor options: none, horizontal, float (optional, default `'horizontal'`) * `options.predictor` **[string][2]** compression predictor options: none, horizontal, float (optional, default `'horizontal'`)
* `options.pyramid` **[boolean][7]** write an image pyramid (optional, default `false`) * `options.pyramid` **[boolean][10]** write an image pyramid (optional, default `false`)
* `options.tile` **[boolean][7]** write a tiled tiff (optional, default `false`) * `options.tile` **[boolean][10]** write a tiled tiff (optional, default `false`)
* `options.tileWidth` **[number][9]** horizontal tile size (optional, default `256`) * `options.tileWidth` **[number][12]** horizontal tile size (optional, default `256`)
* `options.tileHeight` **[number][9]** vertical tile size (optional, default `256`) * `options.tileHeight` **[number][12]** vertical tile size (optional, default `256`)
* `options.xres` **[number][9]** horizontal resolution in pixels/mm (optional, default `1.0`) * `options.xres` **[number][12]** horizontal resolution in pixels/mm (optional, default `1.0`)
* `options.yres` **[number][9]** vertical resolution in pixels/mm (optional, default `1.0`) * `options.yres` **[number][12]** vertical resolution in pixels/mm (optional, default `1.0`)
* `options.resolutionUnit` **[string][2]** resolution unit options: inch, cm (optional, default `'inch'`) * `options.resolutionUnit` **[string][2]** resolution unit options: inch, cm (optional, default `'inch'`)
* `options.bitdepth` **[number][9]** reduce bitdepth to 1, 2 or 4 bit (optional, default `8`) * `options.bitdepth` **[number][12]** reduce bitdepth to 1, 2 or 4 bit (optional, default `8`)
### Examples ### Examples
@@ -440,7 +461,7 @@ sharp('input.svg')
* Throws **[Error][4]** Invalid options * Throws **[Error][4]** Invalid options
Returns **Sharp** Returns **Sharp**&#x20;
## avif ## avif
@@ -455,16 +476,28 @@ AVIF image sequences are not supported.
* `options` **[Object][6]?** output options * `options` **[Object][6]?** output options
* `options.quality` **[number][9]** quality, integer 1-100 (optional, default `50`) * `options.quality` **[number][12]** quality, integer 1-100 (optional, default `50`)
* `options.lossless` **[boolean][7]** use lossless compression (optional, default `false`) * `options.lossless` **[boolean][10]** use lossless compression (optional, default `false`)
* `options.effort` **[number][9]** CPU effort, between 0 (fastest) and 9 (slowest) (optional, default `4`) * `options.effort` **[number][12]** CPU effort, between 0 (fastest) and 9 (slowest) (optional, default `4`)
* `options.chromaSubsampling` **[string][2]** set to '4:2:0' to use chroma subsampling (optional, default `'4:4:4'`) * `options.chromaSubsampling` **[string][2]** set to '4:2:0' to use chroma subsampling (optional, default `'4:4:4'`)
<!----> ### Examples
```javascript
const data = await sharp(input)
.avif({ effort: 2 })
.toBuffer();
```
```javascript
const data = await sharp(input)
.avif({ lossless: true })
.toBuffer();
```
* Throws **[Error][4]** Invalid options * Throws **[Error][4]** Invalid options
Returns **Sharp** Returns **Sharp**&#x20;
**Meta** **Meta**
@@ -474,28 +507,66 @@ Returns **Sharp**
Use these HEIF options for output image. Use these HEIF options for output image.
Support for patent-encumbered HEIC images requires the use of a Support for patent-encumbered HEIC images using `hevc` compression requires the use of a
globally-installed libvips compiled with support for libheif, libde265 and x265. globally-installed libvips compiled with support for libheif, libde265 and x265.
### Parameters ### Parameters
* `options` **[Object][6]?** output options * `options` **[Object][6]?** output options
* `options.quality` **[number][9]** quality, integer 1-100 (optional, default `50`) * `options.quality` **[number][12]** quality, integer 1-100 (optional, default `50`)
* `options.compression` **[string][2]** compression format: av1, hevc (optional, default `'av1'`) * `options.compression` **[string][2]** compression format: av1, hevc (optional, default `'av1'`)
* `options.lossless` **[boolean][7]** use lossless compression (optional, default `false`) * `options.lossless` **[boolean][10]** use lossless compression (optional, default `false`)
* `options.effort` **[number][9]** CPU effort, between 0 (fastest) and 9 (slowest) (optional, default `4`) * `options.effort` **[number][12]** CPU effort, between 0 (fastest) and 9 (slowest) (optional, default `4`)
* `options.chromaSubsampling` **[string][2]** set to '4:2:0' to use chroma subsampling (optional, default `'4:4:4'`) * `options.chromaSubsampling` **[string][2]** set to '4:2:0' to use chroma subsampling (optional, default `'4:4:4'`)
### Examples
```javascript
const data = await sharp(input)
.heif({ compression: 'hevc' })
.toBuffer();
```
* Throws **[Error][4]** Invalid options
Returns **Sharp**&#x20;
**Meta**
* **since**: 0.23.0
## jxl
Use these JPEG-XL (JXL) options for output image.
This feature is experimental, please do not use in production systems.
Requires libvips compiled with support for libjxl.
The prebuilt binaries do not include this - see
[installing a custom libvips][14].
Image metadata (EXIF, XMP) is unsupported.
### Parameters
* `options` **[Object][6]?** output options
* `options.distance` **[number][12]** maximum encoding error, between 0 (highest quality) and 15 (lowest quality) (optional, default `1.0`)
* `options.quality` **[number][12]?** calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified
* `options.decodingTier` **[number][12]** target decode speed tier, between 0 (highest quality) and 4 (lowest quality) (optional, default `0`)
* `options.lossless` **[boolean][10]** use lossless compression (optional, default `false`)
* `options.effort` **[number][12]** CPU effort, between 3 (fastest) and 9 (slowest) (optional, default `7`)
<!----> <!---->
* Throws **[Error][4]** Invalid options * Throws **[Error][4]** Invalid options
Returns **Sharp** Returns **Sharp**&#x20;
**Meta** **Meta**
* **since**: 0.23.0 * **since**: 0.31.3
## raw ## raw
@@ -533,24 +604,28 @@ const data = await sharp('input.png')
## tile ## tile
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.
The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`.
### Parameters ### Parameters
* `options` **[Object][6]?** * `options` **[Object][6]?**&#x20;
* `options.size` **[number][9]** tile size in pixels, a value between 1 and 8192. (optional, default `256`) * `options.size` **[number][12]** tile size in pixels, a value between 1 and 8192. (optional, default `256`)
* `options.overlap` **[number][9]** tile overlap in pixels, a value between 0 and 8192. (optional, default `0`) * `options.overlap` **[number][12]** tile overlap in pixels, a value between 0 and 8192. (optional, default `0`)
* `options.angle` **[number][9]** tile angle of rotation, must be a multiple of 90. (optional, default `0`) * `options.angle` **[number][12]** tile angle of rotation, must be a multiple of 90. (optional, default `0`)
* `options.background` **([string][2] | [Object][6])** background colour, parsed by the [color][12] module, defaults to white without transparency. (optional, default `{r:255,g:255,b:255,alpha:1}`) * `options.background` **([string][2] | [Object][6])** background colour, parsed by the [color][15] module, defaults to white without transparency. (optional, default `{r:255,g:255,b:255,alpha:1}`)
* `options.depth` **[string][2]?** how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout. * `options.depth` **[string][2]?** how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout.
* `options.skipBlanks` **[number][9]** threshold to skip tile generation, a value 0 - 255 for 8-bit images or 0 - 65535 for 16-bit images (optional, default `-1`) * `options.skipBlanks` **[number][12]** threshold to skip tile generation, a value 0 - 255 for 8-bit images or 0 - 65535 for 16-bit images (optional, default `-1`)
* `options.container` **[string][2]** tile container, with value `fs` (filesystem) or `zip` (compressed file). (optional, default `'fs'`) * `options.container` **[string][2]** tile container, with value `fs` (filesystem) or `zip` (compressed file). (optional, default `'fs'`)
* `options.layout` **[string][2]** filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`. (optional, default `'dz'`) * `options.layout` **[string][2]** filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`. (optional, default `'dz'`)
* `options.centre` **[boolean][7]** centre image in tile. (optional, default `false`) * `options.centre` **[boolean][10]** centre image in tile. (optional, default `false`)
* `options.center` **[boolean][7]** alternative spelling of centre. (optional, default `false`) * `options.center` **[boolean][10]** alternative spelling of centre. (optional, default `false`)
* `options.id` **[string][2]** when `layout` is `iiif`/`iiif3`, sets the `@id`/`id` attribute of `info.json` (optional, default `'https://example.com/iiif'`) * `options.id` **[string][2]** when `layout` is `iiif`/`iiif3`, sets the `@id`/`id` attribute of `info.json` (optional, default `'https://example.com/iiif'`)
* `options.basename` **[string][2]?** the name of the directory within the zip file when container is `zip`.
### Examples ### Examples
@@ -566,9 +641,22 @@ sharp('input.tiff')
}); });
``` ```
```javascript
const zipFileWithTiles = await sharp(input)
.tile({ basename: "tiles" })
.toBuffer();
```
```javascript
const iiififier = sharp().tile({ layout: "iiif" });
readableStream
.pipe(iiififier)
.pipe(writeableStream);
```
* Throws **[Error][4]** Invalid parameters * Throws **[Error][4]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
## timeout ## timeout
@@ -580,11 +668,25 @@ Time spent waiting for a libuv thread to become available is not included.
### Parameters ### Parameters
* `options` **[Object][6]** * `options` **[Object][6]**&#x20;
* `options.seconds` **[number][9]** Number of seconds after which processing will be stopped * `options.seconds` **[number][12]** Number of seconds after which processing will be stopped
Returns **Sharp** ### Examples
```javascript
// Ensure processing takes no longer than 3 seconds
try {
const data = await sharp(input)
.blur(1000)
.timeout({ seconds: 3 })
.toBuffer();
} catch (err) {
if (err.message.includes('timeout')) { ... }
}
```
Returns **Sharp**&#x20;
**Meta** **Meta**
@@ -602,14 +704,20 @@ Returns **Sharp**
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object [6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean [7]: #toformat
[8]: https://nodejs.org/api/buffer.html [8]: #jpeg
[9]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number [9]: #png
[10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array [10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[11]: https://sharp.pixelplumbing.com/install#custom-libvips [11]: https://nodejs.org/api/buffer.html
[12]: https://www.npmjs.org/package/color [12]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
[13]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
[14]: https://sharp.pixelplumbing.com/install#custom-libvips
[15]: https://www.npmjs.org/package/color

View File

@@ -14,7 +14,9 @@ When both a `width` and `height` are provided, the possible methods by which the
Some of these values are based on the [object-fit][1] CSS property. Some of these values are based on the [object-fit][1] CSS property.
When using a `fit` of `cover` or `contain`, the default **position** is `centre`. Other options are: <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.png">
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`.
* `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`. * `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`.
@@ -36,17 +38,20 @@ Possible interpolation kernels are:
* `lanczos2`: Use a [Lanczos kernel][7] with `a=2`. * `lanczos2`: Use a [Lanczos kernel][7] with `a=2`.
* `lanczos3`: Use a Lanczos kernel with `a=3` (the default). * `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
Only one resize can occur per pipeline.
Previous calls to `resize` in the same pipeline will be ignored.
### Parameters ### Parameters
* `width` **[number][8]?** pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height. * `width` **[number][8]?** pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height.
* `height` **[number][8]?** pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width. * `height` **[number][8]?** pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width.
* `options` **[Object][9]?** * `options` **[Object][9]?**&#x20;
* `options.width` **[String][10]?** alternative means of specifying `width`. If both are present this take priority. * `options.width` **[String][10]?** alternative means of specifying `width`. If both are present this takes priority.
* `options.height` **[String][10]?** alternative means of specifying `height`. If both are present this take priority. * `options.height` **[String][10]?** alternative means of specifying `height`. If both are present this takes priority.
* `options.fit` **[String][10]** how the image should be resized to fit both provided dimensions, one of `cover`, `contain`, `fill`, `inside` or `outside`. (optional, default `'cover'`) * `options.fit` **[String][10]** how the image should be resized to fit both provided dimensions, one of `cover`, `contain`, `fill`, `inside` or `outside`. (optional, default `'cover'`)
* `options.position` **[String][10]** position, gravity or strategy to use when `fit` is `cover` or `contain`. (optional, default `'centre'`) * `options.position` **[String][10]** position, gravity or strategy to use when `fit` is `cover` or `contain`. (optional, default `'centre'`)
* `options.background` **([String][10] | [Object][9])** background colour when using a `fit` of `contain`, parsed by the [color][11] module, defaults to black without transparency. (optional, default `{r:0,g:0,b:0,alpha:1}`) * `options.background` **([String][10] | [Object][9])** background colour when `fit` is `contain`, parsed by the [color][11] module, defaults to black without transparency. (optional, default `{r:0,g:0,b:0,alpha:1}`)
* `options.kernel` **[String][10]** the kernel to use for image reduction. (optional, default `'lanczos3'`) * `options.kernel` **[String][10]** the kernel to use for image reduction. (optional, default `'lanczos3'`)
* `options.withoutEnlargement` **[Boolean][12]** do not enlarge if the width *or* height are already less than the specified dimensions, equivalent to GraphicsMagick's `>` geometry option. (optional, default `false`) * `options.withoutEnlargement` **[Boolean][12]** do not enlarge if the width *or* height are already less than the specified dimensions, equivalent to GraphicsMagick's `>` geometry option. (optional, default `false`)
* `options.withoutReduction` **[Boolean][12]** do not reduce if the width *or* height are already greater than the specified dimensions, equivalent to GraphicsMagick's `<` geometry option. (optional, default `false`) * `options.withoutReduction` **[Boolean][12]** do not reduce if the width *or* height are already greater than the specified dimensions, equivalent to GraphicsMagick's `<` geometry option. (optional, default `false`)
@@ -144,7 +149,7 @@ const scaleByHalf = await sharp(input)
* Throws **[Error][13]** Invalid parameters * Throws **[Error][13]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
## extend ## extend
@@ -190,7 +195,7 @@ sharp(input)
* Throws **[Error][13]** Invalid parameters * Throws **[Error][13]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
## extract ## extract
@@ -231,25 +236,70 @@ sharp(input)
* Throws **[Error][13]** Invalid parameters * Throws **[Error][13]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
## trim ## trim
Trim "boring" pixels from all edges that contain values similar to the top-left pixel. Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.
Images consisting entirely of a single colour will calculate "boring" using the alpha channel, if any.
Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels.
If the result of this operation would trim an image to nothing then no change is made.
The `info` response Object, obtained from callback of `.toFile()` or `.toBuffer()`, The `info` response Object, obtained from callback of `.toFile()` or `.toBuffer()`,
will contain `trimOffsetLeft` and `trimOffsetTop` properties. will contain `trimOffsetLeft` and `trimOffsetTop` properties.
### Parameters ### Parameters
* `threshold` **[number][8]** the allowed difference from the top-left pixel, a number greater than zero. (optional, default `10`) * `trim` **([string][10] | [number][8] | [Object][9])** the specific background colour to trim, the threshold for doing so or an Object with both.
<!----> * `trim.background` **([string][10] | [Object][9])** background colour, parsed by the [color][11] module, defaults to that of the top-left pixel. (optional, default `'top-left pixel'`)
* `trim.threshold` **[number][8]** the allowed difference from the above colour, a positive number. (optional, default `10`)
### Examples
```javascript
// Trim pixels with a colour similar to that of the top-left pixel.
sharp(input)
.trim()
.toFile(output, function(err, info) {
...
});
```
```javascript
// Trim pixels with the exact same colour as that of the top-left pixel.
sharp(input)
.trim(0)
.toFile(output, function(err, info) {
...
});
```
```javascript
// Trim only pixels with a similar colour to red.
sharp(input)
.trim("#FF0000")
.toFile(output, function(err, info) {
...
});
```
```javascript
// Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
sharp(input)
.trim({
background: "yellow",
threshold: 42,
})
.toFile(output, function(err, info) {
...
});
```
* Throws **[Error][13]** Invalid parameters * Throws **[Error][13]** Invalid parameters
Returns **Sharp** Returns **Sharp**&#x20;
[1]: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit [1]: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

View File

@@ -10,7 +10,7 @@ An Object containing nested boolean values representing the available input and
console.log(sharp.format); console.log(sharp.format);
``` ```
Returns **[Object][1]** Returns **[Object][1]**&#x20;
## interpolators ## interpolators
@@ -90,12 +90,16 @@ sharp.cache( { files: 0 } );
sharp.cache(false); sharp.cache(false);
``` ```
Returns **[Object][1]** Returns **[Object][1]**&#x20;
## concurrency ## concurrency
Gets or, when a concurrency is provided, sets Gets or, when a concurrency is provided, sets
the number of threads *libvips'* should create to process each image. the maximum number of threads *libvips* should use to process *each image*.
These are from a thread pool managed by glib,
which helps avoid the overhead of creating new threads.
This method always returns the current concurrency.
The default value is the number of CPU cores, The default value is the number of CPU cores,
except when using glibc-based Linux without jemalloc, except when using glibc-based Linux without jemalloc,
@@ -103,14 +107,23 @@ where the default is `1` to help reduce memory fragmentation.
A value of `0` will reset this to the number of CPU cores. A value of `0` will reset this to the number of CPU cores.
The maximum number of images that can be processed in parallel Some image format libraries spawn additional threads,
is limited by libuv's `UV_THREADPOOL_SIZE` environment variable. e.g. libaom manages its own 4 threads when encoding AVIF images,
and these are independent of the value set here.
This method always returns the current concurrency. The maximum number of images that sharp can process in parallel
is controlled by libuv's `UV_THREADPOOL_SIZE` environment variable,
which defaults to 4.
[https://nodejs.org/api/cli.html#uv\_threadpool\_sizesize][12]
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.
### Parameters ### Parameters
* `concurrency` **[number][11]?** * `concurrency` **[number][11]?**&#x20;
### Examples ### Examples
@@ -150,7 +163,7 @@ Provides access to internal task counters.
const counters = sharp.counters(); // { queue: 2, process: 4 } const counters = sharp.counters(); // { queue: 2, process: 4 }
``` ```
Returns **[Object][1]** Returns **[Object][1]**&#x20;
## simd ## simd
@@ -176,7 +189,7 @@ const simd = sharp.simd(false);
// prevent libvips from using liborc at runtime // prevent libvips from using liborc at runtime
``` ```
Returns **[boolean][10]** Returns **[boolean][10]**&#x20;
[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object [1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
@@ -188,14 +201,16 @@ Returns **[boolean][10]**
[5]: http://en.wikipedia.org/wiki/Bicubic_interpolation [5]: http://en.wikipedia.org/wiki/Bicubic_interpolation
[6]: https://github.com/jcupitt/libvips/blob/master/libvips/resample/lbb.cpp#L100 [6]: https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100
[7]: http://en.wikipedia.org/wiki/Acutance [7]: http://en.wikipedia.org/wiki/Acutance
[8]: http://eprints.soton.ac.uk/268086/ [8]: http://eprints.soton.ac.uk/268086/
[9]: https://github.com/jcupitt/libvips/blob/master/libvips/resample/vsqbs.cpp#L48 [9]: https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48
[10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean [10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[11]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number [11]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
[12]: https://nodejs.org/api/cli.html#uv_threadpool_sizesize

View File

@@ -2,7 +2,6 @@
const fs = require('fs').promises; const fs = require('fs').promises;
const path = require('path'); const path = require('path');
const documentation = require('documentation');
[ [
'constructor', 'constructor',
@@ -15,6 +14,8 @@ const documentation = require('documentation');
'output', 'output',
'utility' 'utility'
].forEach(async (m) => { ].forEach(async (m) => {
const documentation = await import('documentation');
const input = path.join('lib', `${m}.js`); const input = path.join('lib', `${m}.js`);
const output = path.join('docs', `api-${m}.md`); const output = path.join('docs', `api-${m}.md`);

View File

@@ -1,9 +1,235 @@
# Changelog # Changelog
## v0.31 - *eagle*
Requires libvips v8.13.3
### v0.31.3 - 21st December 2022
* Add experimental support for JPEG-XL images. Requires libvips compiled with libjxl.
[#2731](https://github.com/lovell/sharp/issues/2731)
* Add runtime detection of V8 memory cage, ensures compatibility with Electron 21 onwards.
[#3384](https://github.com/lovell/sharp/issues/3384)
* Expose `interFrameMaxError` and `interPaletteMaxError` GIF optimisation properties.
[#3401](https://github.com/lovell/sharp/issues/3401)
* Allow installation on Linux with glibc patch versions e.g. Fedora 38.
[#3423](https://github.com/lovell/sharp/issues/3423)
* Expand range of existing `sharpen` parameters to match libvips.
[#3427](https://github.com/lovell/sharp/issues/3427)
* Prevent possible race condition awaiting metadata of Stream-based input.
[#3451](https://github.com/lovell/sharp/issues/3451)
* Improve `extractChannel` support for 16-bit output colourspaces.
[#3453](https://github.com/lovell/sharp/issues/3453)
* Ignore `sequentialRead` option when calculating image statistics.
[#3462](https://github.com/lovell/sharp/issues/3462)
* Small performance improvement for operations that introduce a non-opaque background.
[#3465](https://github.com/lovell/sharp/issues/3465)
* Ensure integral output of `linear` operation.
[#3468](https://github.com/lovell/sharp/issues/3468)
### v0.31.2 - 4th November 2022
* Upgrade to libvips v8.13.3 for upstream bug fixes.
* Ensure manual flip, rotate, resize operation ordering (regression in 0.31.1)
[#3391](https://github.com/lovell/sharp/issues/3391)
* Ensure auto-rotation works without resize (regression in 0.31.1)
[#3422](https://github.com/lovell/sharp/issues/3422)
### v0.31.1 - 29th September 2022
* Upgrade to libvips v8.13.2 for upstream bug fixes.
* Ensure `close` event occurs after `end` event for Stream-based output.
[#3313](https://github.com/lovell/sharp/issues/3313)
* Ensure `limitInputPixels` constructor option uses uint64.
[#3349](https://github.com/lovell/sharp/pull/3349)
[@marcosc90](https://github.com/marcosc90)
* Ensure auto-rotation works with shrink-on-load and extract (regression in 0.31.0).
[#3352](https://github.com/lovell/sharp/issues/3352)
* Ensure AVIF output is always 8-bit.
[#3358](https://github.com/lovell/sharp/issues/3358)
* Ensure greyscale images can be trimmed (regression in 0.31.0).
[#3386](https://github.com/lovell/sharp/issues/3386)
### v0.31.0 - 5th September 2022
* Drop support for Node.js 12, now requires Node.js >= 14.15.0.
* GIF output now re-uses input palette if possible. Use `reoptimise` option to generate a new palette.
* Add WebP `minSize` and `mixed` options for greater control over animation frames.
* Remove previously-deprecated WebP `reductionEffort` and HEIF `speed` options. Use `effort` to control these.
* The `flip` and `flop` operations will now occur before the `rotate` operation.
* Improve `normalise` operation with use of histogram.
[#200](https://github.com/lovell/sharp/issues/200)
* Use combined bounding box of alpha and non-alpha channels for `trim` operation.
[#2166](https://github.com/lovell/sharp/issues/2166)
* Add Buffer and Stream support to tile-based output.
[#2238](https://github.com/lovell/sharp/issues/2238)
* Add input `fileSuffix` and output `alias` to `format` information.
[#2642](https://github.com/lovell/sharp/issues/2642)
* Re-introduce support for greyscale ICC profiles (temporarily removed in 0.30.2).
[#3114](https://github.com/lovell/sharp/issues/3114)
* Add support for WebP and PackBits `compression` options with TIFF output.
[#3198](https://github.com/lovell/sharp/issues/3198)
* Ensure OpenSlide and FITS input works with custom libvips.
[#3226](https://github.com/lovell/sharp/issues/3226)
* Ensure `trim` operation is a no-op when it would reduce an image to nothing.
[#3223](https://github.com/lovell/sharp/issues/3223)
* Expose `vips_text` to create an image containing rendered text.
[#3252](https://github.com/lovell/sharp/pull/3252)
[@brahima](https://github.com/brahima)
* Ensure only properties owned by the `withMetadata` EXIF Object are parsed.
[#3292](https://github.com/lovell/sharp/issues/3292)
* Expand `linear` operation to allow use of per-channel arrays.
[#3303](https://github.com/lovell/sharp/pull/3303)
[@antonmarsden](https://github.com/antonmarsden)
* Ensure the order of `rotate`, `resize` and `extend` operations is respected where possible.
Emit warnings when previous calls in the same pipeline will be ignored.
[#3319](https://github.com/lovell/sharp/issues/3319)
* Ensure PNG bitdepth can be set for non-palette output.
[#3322](https://github.com/lovell/sharp/issues/3322)
* Add trim option to provide a specific background colour.
[#3332](https://github.com/lovell/sharp/pull/3332)
[@mart-jansink](https://github.com/mart-jansink)
* Ensure resized image is unpremultiplied before composite.
[#3334](https://github.com/lovell/sharp/issues/3334)
## v0.30 - *dresser* ## v0.30 - *dresser*
Requires libvips v8.12.2 Requires libvips v8.12.2
### v0.30.7 - 22nd June 2022
* Ensure tiled composition always works with outside resizing.
[#3227](https://github.com/lovell/sharp/issues/3227)
* Allow WebP encoding effort of 0.
[#3261](https://github.com/lovell/sharp/pull/3261)
[@AlexanderTheGrey](https://github.com/AlexanderTheGrey)
* Prevent upsampling via libwebp.
[#3267](https://github.com/lovell/sharp/pull/3267)
[@blacha](https://github.com/blacha)
### v0.30.6 - 30th May 2022
* Allow values for `limitInputPixels` larger than 32-bit.
[#3238](https://github.com/lovell/sharp/issues/3238)
* Ensure brew-installed `vips` can be detected (regression in 0.30.5).
[#3239](https://github.com/lovell/sharp/issues/3239)
### v0.30.5 - 23rd May 2022
* Install: pass `PKG_CONFIG_PATH` via env rather than substitution.
[@dwisiswant0](https://github.com/dwisiswant0)
* Add support for `--libc` flag to improve cross-platform installation.
[#3160](https://github.com/lovell/sharp/pull/3160)
[@joonamo](https://github.com/joonamo)
* Allow installation of prebuilt libvips binaries from filesystem.
[#3196](https://github.com/lovell/sharp/pull/3196)
[@ankurparihar](https://github.com/ankurparihar)
* Fix rotate-then-extract for EXIF orientation 2.
[#3218](https://github.com/lovell/sharp/pull/3218)
[@jakob0fischl](https://github.com/jakob0fischl)
### v0.30.4 - 18th April 2022
* Increase control over sensitivity to invalid images via `failOn`, deprecate `failOnError` (equivalent to `failOn: 'warning'`).
* Ensure `create` input image has correct bit depth and colour space.
[#3139](https://github.com/lovell/sharp/issues/3139)
* Add support for `TypedArray` input with `byteOffset` and `length`.
[#3146](https://github.com/lovell/sharp/pull/3146)
[@codepage949](https://github.com/codepage949)
* Improve error message when attempting to render SVG input greater than 32767x32767.
[#3167](https://github.com/lovell/sharp/issues/3167)
* Add missing file name to 'Input file is missing' error message.
[#3178](https://github.com/lovell/sharp/pull/3178)
[@Brodan](https://github.com/Brodan)
### v0.30.3 - 14th March 2022
* Allow `sharpen` options to be provided more consistently as an Object.
[#2561](https://github.com/lovell/sharp/issues/2561)
* Expose `x1`, `y2` and `y3` parameters of `sharpen` operation.
[#2935](https://github.com/lovell/sharp/issues/2935)
* Prevent double unpremultiply with some composite blend modes (regression in 0.30.2).
[#3118](https://github.com/lovell/sharp/issues/3118)
### v0.30.2 - 2nd March 2022
* Improve performance and accuracy when compositing multiple images.
[#2286](https://github.com/lovell/sharp/issues/2286)
* Expand pkgconfig search path for wider BSD support.
[#3106](https://github.com/lovell/sharp/issues/3106)
* Ensure Windows C++ runtime is linked statically (regression in 0.30.0).
[#3110](https://github.com/lovell/sharp/pull/3110)
[@kleisauke](https://github.com/kleisauke)
* Temporarily ignore greyscale ICC profiles to workaround lcms bug.
[#3112](https://github.com/lovell/sharp/issues/3112)
### v0.30.1 - 9th February 2022
* Allow use of `toBuffer` and `toFile` on the same instance.
[#3044](https://github.com/lovell/sharp/issues/3044)
* Skip shrink-on-load for known libjpeg rounding errors.
[#3066](https://github.com/lovell/sharp/issues/3066)
[@kleisauke](https://github.com/kleisauke)
* Ensure withoutReduction does not interfere with contain/crop/embed.
[#3081](https://github.com/lovell/sharp/pull/3081)
[@kleisauke](https://github.com/kleisauke)
* Ensure affine interpolator is correctly finalised.
[#3083](https://github.com/lovell/sharp/pull/3083)
[@kleisauke](https://github.com/kleisauke)
### v0.30.0 - 1st February 2022 ### v0.30.0 - 1st February 2022
* Add support for GIF output to prebuilt binaries. * Add support for GIF output to prebuilt binaries.

View File

@@ -236,3 +236,30 @@ GitHub: https://github.com/gforge
Name: Chris Banks Name: Chris Banks
GitHub: https://github.com/christopherbradleybanks GitHub: https://github.com/christopherbradleybanks
Name: codepage949
GitHub: https://github.com/codepage949
Name: Chris Hranj
GitHub: https://github.com/Brodan
Name: Ankur Parihar
GitHub: https://github.com/ankurparihar
Name: Joona Heinikoski
GitHub: https://github.com/joonamo
Name: AlexanderTheGrey
GitHub: https://github.com/AlexanderTheGrey
Name: Blayne Chard
GitHub: https://github.com/blacha
Name: Brahim
GitHub: https://github.com/brahima
Name: Anton Marsden
GitHub: https://github.com/antonmarsden
Name: Marcos Casagrande
GitHub: https://github.com/marcosc90

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

BIN
docs/image/sharp-logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 661 B

View File

@@ -6,19 +6,13 @@
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Resize large images in common formats to smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions"> <meta name="description" content="Resize large images in common formats to smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; object-src 'none'; style-src 'unsafe-inline'; <meta http-equiv="Content-Security-Policy" content="default-src 'self'; object-src 'none'; style-src 'unsafe-inline';
img-src 'unsafe-inline' data: https://pixel.plumbing/px/ https://cdn.jsdelivr.net/gh/lovell/ https://www.google-analytics.com; img-src 'unsafe-inline' data: https://cdn.jsdelivr.net/gh/lovell/ https://www.google-analytics.com;
connect-src 'self' https://www.google-analytics.com; connect-src 'self' https://www.google-analytics.com;
script-src 'self' 'unsafe-inline' 'unsafe-eval' script-src 'self' 'unsafe-inline' 'unsafe-eval'
https://www.google-analytics.com/analytics.js;"> https://www.google-analytics.com/analytics.js;">
<link rel="icon" type="image/png" href="https://pixel.plumbing/px/32x32/sharp-logo.svg"> <link rel="icon" type="image/svg+xml" href="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo.svg">
<link rel="apple-touch-icon-precomposed" sizes="152x152" href="https://pixel.plumbing/px/152x152/sharp-logo.svg"> <link rel="icon" type="image/png" sizes="32x32" href="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo.png">
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://pixel.plumbing/px/144x144/sharp-logo.svg">
<link rel="apple-touch-icon-precomposed" sizes="120x120" href="https://pixel.plumbing/px/120x120/sharp-logo.svg">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="https://pixel.plumbing/px/114x114/sharp-logo.svg">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="https://pixel.plumbing/px/72x72/sharp-logo.svg">
<link rel="apple-touch-icon-precomposed" href="https://pixel.plumbing/px/57x57/sharp-logo.svg">
<link rel="author" href="/humans.txt" type="text/plain"> <link rel="author" href="/humans.txt" type="text/plain">
<link rel="dns-prefetch" href="https://pixel.plumbing">
<link rel="dns-prefetch" href="https://www.google-analytics.com"> <link rel="dns-prefetch" href="https://www.google-analytics.com">
<script type="application/ld+json"> <script type="application/ld+json">
{ {
@@ -124,7 +118,7 @@
router: { mode: 'history' }, router: { mode: 'history' },
logo: '<div style="display:flex;align-items:center">' logo: '<div style="display:flex;align-items:center">'
+ '<strong>sharp</strong> ' + '<strong>sharp</strong> '
+ '<img src="https://pixel.plumbing/px/16x16/sharp-logo.svg" style="padding:8px" alt="#"> ' + '<img src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo.svg" style="padding:8px" width="32" height="32" alt="#"> '
+ '<span style="opacity:0.8;white-space:pre" class="shorten-strapline">High performance </span> ' + '<span style="opacity:0.8;white-space:pre" class="shorten-strapline">High performance </span> '
+ '<span style="opacity:0.8">Node.js image processing</span> ' + '<span style="opacity:0.8">Node.js image processing</span> '
+ '</div>', + '</div>',

View File

@@ -10,7 +10,7 @@ yarn add sharp
## Prerequisites ## Prerequisites
* Node.js >= 12.13.0 * Node.js >= 14.15.0
## Prebuilt binaries ## Prebuilt binaries
@@ -57,7 +57,7 @@ When using npm v7 or later, the user running `npm install` must own the director
The `npm install --ignore-scripts=false` flag must be used when `npm` has been configured to ignore installation scripts. The `npm install --ignore-scripts=false` flag must be used when `npm` has been configured to ignore installation scripts.
Check the output of running `npm install --verbose sharp` for useful error messages. Check the output of running `npm install --verbose --foreground-scripts sharp` for useful error messages.
## Apple M1 ## Apple M1
@@ -74,20 +74,36 @@ The target platform and/or architecture can be manually selected using the follo
npm install --platform=... --arch=... --arm-version=... sharp npm install --platform=... --arch=... --arm-version=... sharp
``` ```
* `--platform`: one of `linux`, `linuxmusl`, `darwin` or `win32`. * `--platform`: one of `linux`, `darwin` or `win32`.
* `--arch`: one of `x64`, `ia32`, `arm` or `arm64`. * `--arch`: one of `x64`, `ia32`, `arm` or `arm64`.
* `--arm-version`: one of `6`, `7` or `8` (`arm` defaults to `6`, `arm64` defaults to `8`). * `--arm-version`: one of `6`, `7` or `8` (`arm` defaults to `6`, `arm64` defaults to `8`).
* `--libc`: one of `glibc` or `musl`. This option only works with platform `linux`, defaults to `glibc`
* `--sharp-install-force`: skip version compatibility and Subresource Integrity checks. * `--sharp-install-force`: skip version compatibility and Subresource Integrity checks.
These values can also be set via environment variables, These values can also be set via environment variables,
`npm_config_platform`, `npm_config_arch`, `npm_config_arm_version` `npm_config_platform`, `npm_config_arch`, `npm_config_arm_version`, `npm_config_libc`
and `SHARP_INSTALL_FORCE` respectively. and `SHARP_INSTALL_FORCE` respectively.
For example, if the target machine has a 64-bit ARM CPU and is running Alpine Linux, For example, if the target machine has a 64-bit ARM CPU and is running Alpine Linux,
use the following flags: use the following flags:
```sh ```sh
npm install --arch=arm64 --platform=linuxmusl sharp npm install --arch=arm64 --platform=linux --libc=musl sharp
```
If the current machine is Alpine Linux and the target machine is Debian Linux on x64 cpu,
use the following flags:
```sh
npm install --arch=x64 --platform=linux --libc=glibc sharp
```
Multiple platforms and architectures can be supported within the same installation tree.
The following example for macOS installs x64 binaries then adds (via a rebuild) arm64 binaries:
```sh
npm install --platform=darwin --arch=x64 sharp
npm rebuild --platform=darwin --arch=arm64 sharp
``` ```
## Custom libvips ## Custom libvips
@@ -96,8 +112,8 @@ To use a custom, globally-installed version of libvips instead of the provided b
make sure it is at least the version listed under `config.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 from source, please see For help compiling libvips and its dependencies, please see
[https://libvips.github.io/libvips/install.html#building-libvips-from-a-source-tarball](https://libvips.github.io/libvips/install.html#building-libvips-from-a-source-tarball). [building libvips from source](https://www.libvips.org/install.html#building-libvips-from-source).
The use of a globally-installed libvips is unsupported on Windows. The use of a globally-installed libvips is unsupported on Windows.
@@ -118,6 +134,8 @@ Building from source requires:
This is an advanced approach that most people will not require. This is an advanced approach that most people will not require.
### Prebuilt sharp binaries
To install the prebuilt sharp binaries from a custom URL, To install the prebuilt sharp binaries from a custom URL,
set the `sharp_binary_host` npm config option set the `sharp_binary_host` npm config option
or the `npm_config_sharp_binary_host` environment variable. or the `npm_config_sharp_binary_host` environment variable.
@@ -126,14 +144,37 @@ To install the prebuilt sharp binaries from a directory on the local filesystem,
set the `sharp_local_prebuilds` npm config option set the `sharp_local_prebuilds` npm config option
or the `npm_config_sharp_local_prebuilds` environment variable. or the `npm_config_sharp_local_prebuilds` environment variable.
URL example:
if `sharp_binary_host` is set to `https://hostname/path`
and the sharp version is `1.2.3` then the resultant URL will be
`https://hostname/path/sharp-v1.2.3-napi-v5-platform-arch.tar.gz`.
Filename example:
if `sharp_local_prebuilds` is set to `/path`
and the sharp version is `1.2.3` then the resultant filename will be
`/path/sharp-v1.2.3-napi-v5-platform-arch.tar.gz`.
### Prebuilt libvips binaries
To install the prebuilt libvips binaries from a custom URL, To install the prebuilt libvips binaries from a custom URL,
set the `sharp_libvips_binary_host` npm config option set the `sharp_libvips_binary_host` npm config option
or the `npm_config_sharp_libvips_binary_host` environment variable. or the `npm_config_sharp_libvips_binary_host` environment variable.
The version subpath and file name are appended to these. To install the prebuilt libvips binaries from a directory on the local filesystem,
For example, if `sharp_libvips_binary_host` is set to `https://hostname/path` set the `sharp_libvips_local_prebuilds` npm config option
and the libvips version is `1.2.3` then the resultant URL will be or the `npm_config_sharp_libvips_local_prebuilds` environment variable.
`https://hostname/path/v1.2.3/libvips-1.2.3-platform-arch.tar.br`.
The version subpath and filename are appended to these.
URL example:
if `sharp_libvips_binary_host` is set to `https://hostname/path`
and the libvips version is `4.5.6` then the resultant URL will be
`https://hostname/path/v4.5.6/libvips-4.5.6-platform-arch.tar.br`.
Filename example:
if `sharp_libvips_local_prebuilds` is set to `/path`
and the libvips version is `4.5.6` then the resultant filename will be
`/path/v4.5.6/libvips-4.5.6-platform-arch.tar.br`.
See the Chinese mirror below for a further example. See the Chinese mirror below for a further example.
@@ -207,15 +248,18 @@ run the following additional command after `npm install`:
```sh ```sh
npm install npm install
SHARP_IGNORE_GLOBAL_LIBVIPS=1 npm install --arch=x64 --platform=linux sharp rm -rf node_modules/sharp
SHARP_IGNORE_GLOBAL_LIBVIPS=1 npm install --arch=x64 --platform=linux --libc=glibc sharp
``` ```
To get the best performance select the largest memory available. To get the best performance select the largest memory available.
A 1536 MB function provides ~12x more CPU time than a 128 MB function. A 1536 MB function provides ~12x more CPU time than a 128 MB function.
## Webpack ## Bundlers
Ensure sharp is added to the ### webpack
Ensure sharp is excluded from bundling via the
[externals](https://webpack.js.org/configuration/externals/) [externals](https://webpack.js.org/configuration/externals/)
configuration. configuration.
@@ -225,20 +269,86 @@ externals: {
} }
``` ```
### esbuild
Ensure sharp is excluded from bundling via the
[external](https://esbuild.github.io/api/#external)
configuration.
```js
buildSync({
entryPoints: ['app.js'],
bundle: true,
platform: 'node',
external: ['sharp'],
})
```
```sh
esbuild app.js --bundle --platform=node --external:sharp
```
For `serverless-esbuild`, ensure platform-specific binaries are installed
via the `serverless.yml` configuration.
```yaml
custom:
esbuild:
external:
- sharp
packagerOptions:
scripts:
- npm install --arch=x64 --platform=linux sharp
```
## Fonts
When creating text images or rendering SVG images that contain text elements,
`fontconfig` is used to find the relevant fonts.
On Windows and macOS systems, all system fonts are available for use.
On macOS systems using Homebrew, you may need to set the
`PANGOCAIRO_BACKEND` environment variable to a value of `fontconfig`
to ensure it is used for font discovery instead of Core Text.
On Linux systems, fonts that include the relevant
[`fontconfig` configuration](https://www.freedesktop.org/software/fontconfig/fontconfig-user.html)
when installed via package manager are available for use.
If `fontconfig` configuration is not found, the following error will occur:
```
Fontconfig error: Cannot load default config file
```
In serverless environments where there is no control over font packages,
use the `FONTCONFIG_PATH` environment variable to point to a custom location.
Embedded SVG fonts are unsupported.
## Worker threads ## Worker threads
The main thread must call `require('sharp')` On some platforms, including glibc-based Linux,
before worker threads are created the main thread must call `require('sharp')`
to ensure shared libraries remain loaded in memory _before_ worker threads are created.
This is to ensure shared libraries remain loaded in memory
until after all threads are complete. until after all threads are complete.
Without this, the following error may occur:
```
Module did not self-register
```
## Known conflicts ## Known conflicts
### Canvas and Windows ### Canvas and Windows
The prebuilt binaries provided by `canvas` for Windows depend on the unmaintained GTK 2, last updated in 2011. The prebuilt binaries provided by `canvas` for Windows
from v2.7.0 onwards depend on the Visual C++ Runtime (MSVCRT).
These conflict with the binaries provided by sharp,
which depend on the more modern Universal C Runtime (UCRT).
These conflict with the modern, up-to-date binaries provided by sharp. See [Automattic/node-canvas#2155](https://github.com/Automattic/node-canvas/issues/2155).
If both modules are used in the same Windows process, the following error will occur: If both modules are used in the same Windows process, the following error will occur:
``` ```

View File

@@ -2,15 +2,19 @@
A test to benchmark the performance of this module relative to alternatives. 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.
## The contenders ## The contenders
* [jimp](https://www.npmjs.com/package/jimp) v0.16.1 - Image processing in pure JavaScript. Provides bicubic interpolation. * [jimp](https://www.npmjs.com/package/jimp) v0.16.2 - Image processing in pure JavaScript. Provides bicubic interpolation.
* [mapnik](https://www.npmjs.org/package/mapnik) v4.5.9 - Whilst primarily a map renderer, Mapnik contains bitmap image utilities.
* [imagemagick](https://www.npmjs.com/package/imagemagick) v0.1.3 - Supports filesystem only and "*has been unmaintained for a long time*". * [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.23.1 - Fully featured wrapper around GraphicsMagick's `gm` command line utility. * [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.4.0 - Image libraries transpiled to WebAssembly, includes GPLv3 code. * [@squoosh/lib](https://www.npmjs.com/package/@squoosh/lib) v0.4.0 - Image libraries transpiled to WebAssembly, includes GPLv3 code.
* [@squoosh/cli](https://www.npmjs.com/package/@squoosh/cli) v0.7.2 - Command line wrapper around `@squoosh/lib`, avoids GPLv3 by spawning process. * [@squoosh/cli](https://www.npmjs.com/package/@squoosh/cli) v0.7.2 - Command line wrapper around `@squoosh/lib`, avoids GPLv3 by spawning process.
* sharp v0.30.0 / libvips v8.12.2 - Caching within libvips disabled to ensure a fair comparison. * sharp v0.31.3 / libvips v8.13.3 - Caching within libvips disabled to ensure a fair comparison.
## The task ## The task
@@ -18,55 +22,50 @@ Decompress a 2725x2225 JPEG image,
resize to 720x588 using Lanczos 3 resampling (where available), resize to 720x588 using Lanczos 3 resampling (where available),
then compress to JPEG at a "quality" setting of 80. then compress to JPEG at a "quality" setting of 80.
## Test environment
* AWS EC2 eu-west-1 [c5ad.xlarge](https://aws.amazon.com/ec2/instance-types/c5/) (4x AMD EPYC 7R32)
* Ubuntu 21.10 (ami-0258eeb71ddf238b3)
* Node.js 16.13.2
## Results ## Results
### AMD64
* AWS EC2 eu-west-1 [c6a.xlarge](https://aws.amazon.com/ec2/instance-types/c6a/) (4x AMD EPYC 7R13)
* Ubuntu 22.04 (ami-026e72e4e468afa7b)
* Node.js 16.19.0
| Module | Input | Output | Ops/sec | Speed-up |
| :----------------- | :----- | :----- | ------: | -------: |
| jimp | buffer | buffer | 0.82 | 1.0 |
| squoosh-cli | file | file | 1.05 | 1.3 |
| squoosh-lib | buffer | buffer | 1.19 | 1.5 |
| gm | buffer | buffer | 8.47 | 10.3 |
| gm | file | file | 8.58 | 10.5 |
| imagemagick | file | file | 9.23 | 11.3 |
| sharp | stream | stream | 33.23 | 40.5 |
| sharp | file | file | 35.22 | 43.0 |
| sharp | buffer | buffer | 35.70 | 43.5 |
### ARM64
* AWS EC2 eu-west-1 [c7g.xlarge](https://aws.amazon.com/ec2/instance-types/c7g/) (4x ARM Graviton3)
* Ubuntu 22.04 (ami-02142ceceb3933ff5)
* Node.js 16.19.0
| Module | Input | Output | Ops/sec | Speed-up | | Module | Input | Output | Ops/sec | Speed-up |
| :----------------- | :----- | :----- | ------: | -------: | | :----------------- | :----- | :----- | ------: | -------: |
| jimp | buffer | buffer | 0.84 | 1.0 | | jimp | buffer | buffer | 0.84 | 1.0 |
| squoosh-cli | file | file | 1.08 | 1.3 | | squoosh-cli | file | file | 1.12 | 1.3 |
| squoosh-lib | buffer | buffer | 1.85 | 2.2 | | squoosh-lib | buffer | buffer | 2.11 | 2.5 |
| mapnik | buffer | buffer | 3.45 | 4.1 | | gm | buffer | buffer | 10.39 | 12.4 |
| gm | buffer | buffer | 8.60 | 10.2 | | gm | file | file | 10.40 | 12.4 |
| gm | file | file | 8.66 | 10.3 | | imagemagick | file | file | 10.73 | 12.8 |
| imagemagick | file | file | 8.79 | 10.5 | | sharp | stream | stream | 33.63 | 40.0 |
| sharp | stream | stream | 28.90 | 34.4 | | sharp | file | file | 34.91 | 41.6 |
| sharp | file | file | 30.08 | 35.8 | | sharp | buffer | buffer | 35.72 | 42.5 |
| sharp | buffer | buffer | 30.42 | 36.2 |
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.
## Running the benchmark test ## Running the benchmark test
Requires _ImageMagick_, _GraphicsMagick_ and _Mapnik_: Requires Docker.
```sh
brew install imagemagick
brew install graphicsmagick
brew install mapnik
```
```sh
sudo apt-get install build-essential imagemagick libmagick++-dev graphicsmagick libmapnik-dev
```
```sh
sudo yum install ImageMagick-devel ImageMagick-c++-devel GraphicsMagick mapnik-devel
```
```sh ```sh
git clone https://github.com/lovell/sharp.git git clone https://github.com/lovell/sharp.git
cd sharp cd sharp/test/bench
npm install --build-from-source ./run-with-docker.sh
cd test/bench
npm install
npm test
``` ```

File diff suppressed because one or more lines are too long

View File

@@ -9,7 +9,7 @@ const extractDescription = (str) =>
.replace(/\s+/g, ' ') .replace(/\s+/g, ' ')
.replace(/[^A-Za-z0-9_/\-,. ]/g, '') .replace(/[^A-Za-z0-9_/\-,. ]/g, '')
.replace(/\s+/g, ' ') .replace(/\s+/g, ' ')
.substr(0, 180) .substring(0, 200)
.trim(); .trim();
const extractParameters = (str) => const extractParameters = (str) =>

View File

@@ -12,6 +12,7 @@ module.exports = [
'and', 'and',
'any', 'any',
'are', 'are',
'available',
'based', 'based',
'been', 'been',
'before', 'before',
@@ -21,6 +22,7 @@ module.exports = [
'can', 'can',
'containing', 'containing',
'contains', 'contains',
'created',
'current', 'current',
'date', 'date',
'default', 'default',
@@ -43,6 +45,8 @@ module.exports = [
'how', 'how',
'image', 'image',
'implies', 'implies',
'include',
'including',
'involve', 'involve',
'its', 'its',
'last', 'last',
@@ -69,14 +73,18 @@ module.exports = [
'provided', 'provided',
'ready', 'ready',
'requires', 'requires',
'requiresharp',
'returned', 'returned',
'run',
'same', 'same',
'see', 'see',
'set', 'set',
'sets', 'sets',
'sharp',
'should', 'should',
'since', 'since',
'site', 'site',
'some',
'specified', 'specified',
'spelling', 'spelling',
'such', 'such',
@@ -111,5 +119,6 @@ module.exports = [
'will', 'will',
'with', 'with',
'without', 'without',
'you' 'you',
'your'
]; ];

View File

@@ -35,6 +35,7 @@ const hasSharpPrebuild = [
]; ];
const { minimumLibvipsVersion, minimumLibvipsVersionLabelled } = libvips; const { minimumLibvipsVersion, minimumLibvipsVersionLabelled } = libvips;
const localLibvipsDir = process.env.npm_config_sharp_libvips_local_prebuilds || '';
const distHost = process.env.npm_config_sharp_libvips_binary_host || 'https://github.com/lovell/sharp-libvips/releases/download'; const distHost = process.env.npm_config_sharp_libvips_binary_host || 'https://github.com/lovell/sharp-libvips/releases/download';
const distBaseUrl = process.env.npm_config_sharp_dist_base_url || process.env.SHARP_DIST_BASE_URL || `${distHost}/v${minimumLibvipsVersionLabelled}/`; const distBaseUrl = process.env.npm_config_sharp_dist_base_url || process.env.SHARP_DIST_BASE_URL || `${distHost}/v${minimumLibvipsVersionLabelled}/`;
const installationForced = !!(process.env.npm_config_sharp_install_force || process.env.SHARP_INSTALL_FORCE); const installationForced = !!(process.env.npm_config_sharp_install_force || process.env.SHARP_INSTALL_FORCE);
@@ -42,7 +43,9 @@ const installationForced = !!(process.env.npm_config_sharp_install_force || proc
const fail = function (err) { const fail = function (err) {
libvips.log(err); libvips.log(err);
if (err.code === 'EACCES') { if (err.code === 'EACCES') {
libvips.log('Are you trying to install as a root or sudo user? Try again with the --unsafe-perm flag'); libvips.log('Are you trying to install as a root or sudo user?');
libvips.log('- For npm <= v6, try again with the "--unsafe-perm" flag');
libvips.log('- For npm >= v8, the user must own the directory "npm install" is run in');
} }
libvips.log('Please see https://sharp.pixelplumbing.com/install for required dependencies'); libvips.log('Please see https://sharp.pixelplumbing.com/install for required dependencies');
process.exit(1); process.exit(1);
@@ -135,7 +138,8 @@ try {
const libcFamily = detectLibc.familySync(); const libcFamily = detectLibc.familySync();
const libcVersion = detectLibc.versionSync(); const libcVersion = detectLibc.versionSync();
if (libcFamily === detectLibc.GLIBC && libcVersion && minimumGlibcVersionByArch[arch]) { if (libcFamily === detectLibc.GLIBC && libcVersion && minimumGlibcVersionByArch[arch]) {
if (semverLessThan(`${libcVersion}.0`, `${minimumGlibcVersionByArch[arch]}.0`)) { const libcVersionWithoutPatch = libcVersion.split('.').slice(0, 2).join('.');
if (semverLessThan(`${libcVersionWithoutPatch}.0`, `${minimumGlibcVersionByArch[arch]}.0`)) {
handleError(new Error(`Use with glibc ${libcVersion} requires manual installation of libvips >= ${minimumLibvipsVersion}`)); handleError(new Error(`Use with glibc ${libcVersion} requires manual installation of libvips >= ${minimumLibvipsVersion}`));
} }
} }
@@ -156,10 +160,15 @@ try {
if (fs.existsSync(tarPathCache)) { if (fs.existsSync(tarPathCache)) {
libvips.log(`Using cached ${tarPathCache}`); libvips.log(`Using cached ${tarPathCache}`);
extractTarball(tarPathCache, platformAndArch); extractTarball(tarPathCache, platformAndArch);
} else if (localLibvipsDir) {
// If localLibvipsDir is given try to use binaries from local directory
const tarPathLocal = path.join(path.resolve(localLibvipsDir), `v${minimumLibvipsVersionLabelled}`, tarFilename);
libvips.log(`Using local libvips from ${tarPathLocal}`);
extractTarball(tarPathLocal, platformAndArch);
} else { } else {
const url = distBaseUrl + tarFilename; const url = distBaseUrl + tarFilename;
libvips.log(`Downloading ${url}`); libvips.log(`Downloading ${url}`);
simpleGet({ url: url, agent: agent() }, function (err, response) { simpleGet({ url: url, agent: agent(libvips.log) }, function (err, response) {
if (err) { if (err) {
fail(err); fail(err);
} else if (response.statusCode === 404) { } else if (response.statusCode === 404) {

View File

@@ -18,7 +18,7 @@ function env (key) {
return process.env[key]; return process.env[key];
} }
module.exports = function () { module.exports = function (log) {
try { try {
const proxy = new url.URL(proxies.map(env).find(is.string)); const proxy = new url.URL(proxies.map(env).find(is.string));
const tunnel = proxy.protocol === 'https:' const tunnel = proxy.protocol === 'https:'
@@ -27,6 +27,7 @@ module.exports = function () {
const proxyAuth = proxy.username && proxy.password const proxyAuth = proxy.username && proxy.password
? `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}` ? `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`
: null; : null;
log(`Via proxy ${proxy.protocol}://${proxy.hostname}:${proxy.port} ${proxyAuth ? 'with' : 'no'} credentials`);
return tunnel({ return tunnel({
proxy: { proxy: {
port: Number(proxy.port), port: Number(proxy.port),

View File

@@ -98,7 +98,7 @@ function extractChannel (channel) {
} else { } else {
throw is.invalidParameterError('channel', 'integer or one of: red, green, blue, alpha', channel); throw is.invalidParameterError('channel', 'integer or one of: red, green, blue, alpha', channel);
} }
return this.toColourspace('b-w'); return this;
} }
/** /**

View File

@@ -19,6 +19,11 @@ const colourspace = {
* Tint the image using the provided chroma while preserving the image luminance. * Tint the image using the provided chroma while preserving the image luminance.
* 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
* const output = await sharp(input)
* .tint({ r: 255, g: 240, b: 16 })
* .toBuffer();
*
* @param {string|Object} rgb - parsed by the [color](https://www.npmjs.org/package/color) module to extract chroma values. * @param {string|Object} rgb - parsed by the [color](https://www.npmjs.org/package/color) module to extract chroma values.
* @returns {Sharp} * @returns {Sharp}
* @throws {Error} Invalid parameter * @throws {Error} Invalid parameter
@@ -37,6 +42,10 @@ function tint (rgb) {
* 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 color 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
* const output = await sharp(input).greyscale().toBuffer();
*
* @param {Boolean} [greyscale=true] * @param {Boolean} [greyscale=true]
* @returns {Sharp} * @returns {Sharp}
*/ */

View File

@@ -43,6 +43,9 @@ 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 or rotate operations in the same processing pipeline
* 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`,
* `xor`, `add`, `saturate`, `multiply`, `screen`, `overlay`, `darken`, `lighten`, * `xor`, `add`, `saturate`, `multiply`, `screen`, `overlay`, `darken`, `lighten`,
@@ -50,12 +53,27 @@ const blend = {
* `hard-light`, `soft-light`, `difference`, `exclusion`. * `hard-light`, `soft-light`, `difference`, `exclusion`.
* *
* More information about blend modes can be found at * More information about blend modes can be found at
* https://libvips.github.io/libvips/API/current/libvips-conversion.html#VipsBlendMode * https://www.libvips.org/API/current/libvips-conversion.html#VipsBlendMode
* and https://www.cairographics.org/operators/ * and https://www.cairographics.org/operators/
* *
* @since 0.22.0 * @since 0.22.0
* *
* @example * @example
* await sharp(background)
* .composite([
* { input: layer1, gravity: 'northwest' },
* { input: layer2, gravity: 'southeast' },
* ])
* .toFile('combined.png');
*
* @example
* const output = await sharp('input.gif', { animated: true })
* .composite([
* { input: 'overlay.png', tile: true, blend: 'saturate' }
* ])
* .toBuffer();
*
* @example
* sharp('input.png') * sharp('input.png')
* .rotate(180) * .rotate(180)
* .resize(300) * .resize(300)
@@ -78,6 +96,17 @@ const blend = {
* @param {Number} [images[].input.create.height] * @param {Number} [images[].input.create.height]
* @param {Number} [images[].input.create.channels] - 3-4 * @param {Number} [images[].input.create.channels] - 3-4
* @param {String|Object} [images[].input.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} [images[].input.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
* @param {Object} [images[].input.text] - describes a new text image to be created.
* @param {string} [images[].input.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.
* @param {string} [images[].input.text.font] - font name to render with.
* @param {string} [images[].input.text.fontfile] - absolute filesystem path to a font file that can be used by `font`.
* @param {number} [images[].input.text.width=0] - integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries.
* @param {number} [images[].input.text.height=0] - integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0.
* @param {string} [images[].input.text.align='left'] - text alignment (`'left'`, `'centre'`, `'center'`, `'right'`).
* @param {boolean} [images[].input.text.justify=false] - set this to true to apply justification to the text.
* @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 {number} [images[].input.text.spacing=0] - text line height in points. Will use the font line height if none is specified.
* @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.
@@ -89,7 +118,8 @@ const blend = {
* @param {Number} [images[].raw.width] * @param {Number} [images[].raw.width]
* @param {Number} [images[].raw.height] * @param {Number} [images[].raw.height]
* @param {Number} [images[].raw.channels] * @param {Number} [images[].raw.channels]
* @param {boolean} [images[].failOnError=true] - @see {@link /api-constructor#parameters|constructor parameters} * @param {boolean} [images[].animated=false] - Set to `true` to read all frames/pages of an animated image.
* @param {string} [images[].failOn='warning'] - @see {@link /api-constructor#parameters|constructor parameters}
* @param {number|boolean} [images[].limitInputPixels=268402689] - @see {@link /api-constructor#parameters|constructor parameters} * @param {number|boolean} [images[].limitInputPixels=268402689] - @see {@link /api-constructor#parameters|constructor parameters}
* @returns {Sharp} * @returns {Sharp}
* @throws {Error} Invalid parameters * @throws {Error} Invalid parameters
@@ -162,7 +192,6 @@ function composite (images) {
throw is.invalidParameterError('premultiplied', 'boolean', image.premultiplied); throw is.invalidParameterError('premultiplied', 'boolean', image.premultiplied);
} }
} }
return composite; return composite;
}); });
return this; return this;

View File

@@ -92,18 +92,38 @@ const debuglog = util.debuglog('sharp');
* } * }
* }).toFile('noise.png'); * }).toFile('noise.png');
* *
* @example
* // Generate an image from text
* await sharp({
* text: {
* text: 'Hello, world!',
* width: 400, // max width
* height: 300 // max height
* }
* }).toFile('text_bw.png');
*
* @example
* // Generate an rgba image from text using pango markup and font
* await sharp({
* text: {
* text: '<span foreground="red">Red!</span><span background="cyan">blue</span>',
* font: 'sans',
* rgba: true,
* dpi: 300
* }
* }).toFile('text_rgba.png');
*
* @param {(Buffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string)} [input] - if present, can be * @param {(Buffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string)} [input] - if present, can be
* a Buffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or * a Buffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or
* a TypedArray containing raw pixel image data, or * a 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.
* 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 {boolean} [options.failOnError=true] - by default halt processing and raise an error when loading invalid images. * @param {string} [options.failOn='warning'] - 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.
* Set this flag to `false` if you'd rather apply a "best effort" to decode images, even if the data is corrupt or invalid.
* @param {number|boolean} [options.limitInputPixels=268402689] - Do not process input images where the number of pixels * @param {number|boolean} [options.limitInputPixels=268402689] - 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. * (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 (SVG, PNG). * @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.sequentialRead=false] - Set this to `true` to use sequential rather than random access where possible. * @param {boolean} [options.sequentialRead=false] - Set this to `true` to use sequential rather than random access where possible.
* This can reduce memory usage and might improve performance on some systems. * This can reduce memory usage and might improve performance on some systems.
* @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.
@@ -127,6 +147,17 @@ const debuglog = util.debuglog('sharp');
* @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] - mean of pixels in generated noise.
* @param {number} [options.create.noise.sigma] - standard deviation of pixels in generated noise. * @param {number} [options.create.noise.sigma] - standard deviation of pixels in generated noise.
* @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.font] - font name to render with.
* @param {string} [options.text.fontfile] - absolute filesystem path to a font file that can be used by `font`.
* @param {number} [options.text.width=0] - integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries.
* @param {number} [options.text.height=0] - integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0.
* @param {string} [options.text.align='left'] - text alignment (`'left'`, `'centre'`, `'center'`, `'right'`).
* @param {boolean} [options.text.justify=false] - set this to true to apply justification to the text.
* @param {number} [options.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified.
* @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.
* @returns {Sharp} * @returns {Sharp}
* @throws {Error} Invalid parameters * @throws {Error} Invalid parameters
*/ */
@@ -186,10 +217,14 @@ const Sharp = function (input, options) {
medianSize: 0, medianSize: 0,
blurSigma: 0, blurSigma: 0,
sharpenSigma: 0, sharpenSigma: 0,
sharpenFlat: 1, sharpenM1: 1,
sharpenJagged: 2, sharpenM2: 2,
sharpenX1: 2,
sharpenY2: 10,
sharpenY3: 20,
threshold: 0, threshold: 0,
thresholdGrayscale: true, thresholdGrayscale: true,
trimBackground: [],
trimThreshold: 0, trimThreshold: 0,
gamma: 0, gamma: 0,
gammaOut: 0, gammaOut: 0,
@@ -249,9 +284,14 @@ const Sharp = function (input, options) {
webpNearLossless: false, webpNearLossless: false,
webpSmartSubsample: false, webpSmartSubsample: false,
webpEffort: 4, webpEffort: 4,
webpMinSize: false,
webpMixed: false,
gifBitdepth: 8, gifBitdepth: 8,
gifEffort: 7, gifEffort: 7,
gifDither: 1, gifDither: 1,
gifInterFrameMaxError: 0,
gifInterPaletteMaxError: 3,
gifReoptimise: false,
tiffQuality: 80, tiffQuality: 80,
tiffCompression: 'jpeg', tiffCompression: 'jpeg',
tiffPredictor: 'horizontal', tiffPredictor: 'horizontal',
@@ -268,6 +308,10 @@ const Sharp = function (input, options) {
heifCompression: 'av1', heifCompression: 'av1',
heifEffort: 4, heifEffort: 4,
heifChromaSubsampling: '4:4:4', heifChromaSubsampling: '4:4:4',
jxlDistance: 1,
jxlDecodingTier: 0,
jxlEffort: 7,
jxlLossless: false,
rawDepth: 'uchar', rawDepth: 'uchar',
tileSize: 256, tileSize: 256,
tileOverlap: 0, tileOverlap: 0,
@@ -280,9 +324,10 @@ const Sharp = function (input, options) {
tileBackground: [255, 255, 255, 255], tileBackground: [255, 255, 255, 255],
tileCentre: false, tileCentre: false,
tileId: 'https://example.com/iiif', tileId: 'https://example.com/iiif',
tileBasename: '',
timeoutSeconds: 0, timeoutSeconds: 0,
linearA: 1, linearA: [],
linearB: 0, linearB: [],
// Function to notify of libvips warnings // Function to notify of libvips warnings
debuglog: warning => { debuglog: warning => {
this.emit('warning', warning); this.emit('warning', warning);
@@ -317,9 +362,7 @@ Object.setPrototypeOf(Sharp, stream.Duplex);
* // Using Promises to know when the pipeline is complete * // Using Promises to know when the pipeline is complete
* const fs = require("fs"); * const fs = require("fs");
* const got = require("got"); * const got = require("got");
* const sharpStream = sharp({ * const sharpStream = sharp({ failOn: 'none' });
* failOnError: false
* });
* *
* const promises = []; * const promises = [];
* *
@@ -346,7 +389,7 @@ Object.setPrototypeOf(Sharp, stream.Duplex);
* .toFile("optimized-500.webp") * .toFile("optimized-500.webp")
* ); * );
* *
* // https://github.com/sindresorhus/got#gotstreamurl-options * // https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md
* got.stream("https://www.example.com/some-file.jpg").pipe(sharpStream); * got.stream("https://www.example.com/some-file.jpg").pipe(sharpStream);
* *
* Promise.all(promises) * Promise.all(promises)

View File

@@ -4,14 +4,26 @@ const color = require('color');
const is = require('./is'); const is = require('./is');
const sharp = require('./sharp'); const sharp = require('./sharp');
/**
* Justication alignment
* @member
* @private
*/
const align = {
left: 'low',
center: 'centre',
centre: 'centre',
right: 'high'
};
/** /**
* 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, unlimited, sequentialRead, failOnError, animated, page, pages, subifd } = obj; const { raw, density, limitInputPixels, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd } = obj;
return [raw, density, limitInputPixels, unlimited, sequentialRead, failOnError, animated, page, pages, subifd].some(is.defined) return [raw, density, limitInputPixels, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd].some(is.defined)
? { raw, density, limitInputPixels, unlimited, sequentialRead, failOnError, animated, page, pages, subifd } ? { raw, density, limitInputPixels, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd }
: undefined; : undefined;
} }
@@ -21,7 +33,7 @@ function _inputOptionsFromObject (obj) {
*/ */
function _createInputDescriptor (input, inputOptions, containerOptions) { function _createInputDescriptor (input, inputOptions, containerOptions) {
const inputDescriptor = { const inputDescriptor = {
failOnError: true, failOn: 'warning',
limitInputPixels: Math.pow(0x3FFF, 2), limitInputPixels: Math.pow(0x3FFF, 2),
unlimited: false, unlimited: false,
sequentialRead: false sequentialRead: false
@@ -39,7 +51,7 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
if (input.length === 0) { if (input.length === 0) {
throw Error('Input Bit Array is empty'); throw Error('Input Bit Array is empty');
} }
inputDescriptor.buffer = Buffer.from(input.buffer); inputDescriptor.buffer = Buffer.from(input.buffer, input.byteOffset, input.byteLength);
} else if (is.plainObject(input) && !is.defined(inputOptions)) { } else if (is.plainObject(input) && !is.defined(inputOptions)) {
// Plain Object descriptor, e.g. create // Plain Object descriptor, e.g. create
inputOptions = input; inputOptions = input;
@@ -56,14 +68,22 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
}`); }`);
} }
if (is.object(inputOptions)) { if (is.object(inputOptions)) {
// Fail on error // Deprecated: failOnError
if (is.defined(inputOptions.failOnError)) { if (is.defined(inputOptions.failOnError)) {
if (is.bool(inputOptions.failOnError)) { if (is.bool(inputOptions.failOnError)) {
inputDescriptor.failOnError = inputOptions.failOnError; inputDescriptor.failOn = inputOptions.failOnError ? 'warning' : 'none';
} else { } else {
throw is.invalidParameterError('failOnError', 'boolean', inputOptions.failOnError); throw is.invalidParameterError('failOnError', 'boolean', inputOptions.failOnError);
} }
} }
// failOn
if (is.defined(inputOptions.failOn)) {
if (is.string(inputOptions.failOn) && is.inArray(inputOptions.failOn, ['none', 'truncated', 'error', 'warning'])) {
inputDescriptor.failOn = inputOptions.failOn;
} else {
throw is.invalidParameterError('failOn', 'one of: none, truncated, error, warning', inputOptions.failOn);
}
}
// 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)) {
@@ -78,10 +98,10 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
inputDescriptor.limitInputPixels = inputOptions.limitInputPixels inputDescriptor.limitInputPixels = inputOptions.limitInputPixels
? Math.pow(0x3FFF, 2) ? Math.pow(0x3FFF, 2)
: 0; : 0;
} else if (is.integer(inputOptions.limitInputPixels) && inputOptions.limitInputPixels >= 0) { } else if (is.integer(inputOptions.limitInputPixels) && is.inRange(inputOptions.limitInputPixels, 0, Number.MAX_SAFE_INTEGER)) {
inputDescriptor.limitInputPixels = inputOptions.limitInputPixels; inputDescriptor.limitInputPixels = inputOptions.limitInputPixels;
} else { } else {
throw is.invalidParameterError('limitInputPixels', 'integer >= 0', inputOptions.limitInputPixels); throw is.invalidParameterError('limitInputPixels', 'positive integer', inputOptions.limitInputPixels);
} }
} }
// unlimited // unlimited
@@ -237,6 +257,81 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
throw new Error('Expected valid width, height and channels to create a new input image'); throw new Error('Expected valid width, height and channels to create a new input image');
} }
} }
// Create a new image with text
if (is.defined(inputOptions.text)) {
if (is.object(inputOptions.text) && is.string(inputOptions.text.text)) {
inputDescriptor.textValue = inputOptions.text.text;
if (is.defined(inputOptions.text.height) && is.defined(inputOptions.text.dpi)) {
throw new Error('Expected only one of dpi or height');
}
if (is.defined(inputOptions.text.font)) {
if (is.string(inputOptions.text.font)) {
inputDescriptor.textFont = inputOptions.text.font;
} else {
throw is.invalidParameterError('text.font', 'string', inputOptions.text.font);
}
}
if (is.defined(inputOptions.text.fontfile)) {
if (is.string(inputOptions.text.fontfile)) {
inputDescriptor.textFontfile = inputOptions.text.fontfile;
} else {
throw is.invalidParameterError('text.fontfile', 'string', inputOptions.text.fontfile);
}
}
if (is.defined(inputOptions.text.width)) {
if (is.number(inputOptions.text.width)) {
inputDescriptor.textWidth = inputOptions.text.width;
} else {
throw is.invalidParameterError('text.textWidth', 'number', inputOptions.text.width);
}
}
if (is.defined(inputOptions.text.height)) {
if (is.number(inputOptions.text.height)) {
inputDescriptor.textHeight = inputOptions.text.height;
} else {
throw is.invalidParameterError('text.height', 'number', inputOptions.text.height);
}
}
if (is.defined(inputOptions.text.align)) {
if (is.string(inputOptions.text.align) && is.string(this.constructor.align[inputOptions.text.align])) {
inputDescriptor.textAlign = this.constructor.align[inputOptions.text.align];
} else {
throw is.invalidParameterError('text.align', 'valid alignment', inputOptions.text.align);
}
}
if (is.defined(inputOptions.text.justify)) {
if (is.bool(inputOptions.text.justify)) {
inputDescriptor.textJustify = inputOptions.text.justify;
} else {
throw is.invalidParameterError('text.justify', 'boolean', inputOptions.text.justify);
}
}
if (is.defined(inputOptions.text.dpi)) {
if (is.number(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 100000)) {
inputDescriptor.textDpi = inputOptions.text.dpi;
} else {
throw is.invalidParameterError('text.dpi', 'number between 1 and 100000', inputOptions.text.dpi);
}
}
if (is.defined(inputOptions.text.rgba)) {
if (is.bool(inputOptions.text.rgba)) {
inputDescriptor.textRgba = inputOptions.text.rgba;
} else {
throw is.invalidParameterError('text.rgba', 'bool', inputOptions.text.rgba);
}
}
if (is.defined(inputOptions.text.spacing)) {
if (is.number(inputOptions.text.spacing)) {
inputDescriptor.textSpacing = inputOptions.text.spacing;
} else {
throw is.invalidParameterError('text.spacing', 'number', inputOptions.text.spacing);
}
}
delete inputDescriptor.buffer;
} else {
throw new Error('Expected a valid string to create an image with text.');
}
}
} else if (is.defined(inputOptions)) { } else if (is.defined(inputOptions)) {
throw new Error('Invalid input options ' + inputOptions); throw new Error('Invalid input options ' + inputOptions);
} }
@@ -295,15 +390,18 @@ function _isStreamInput () {
* This is taken from the header of the input image. * This is taken from the header of the input image.
* It does not include operations, such as resize, to be applied to the output image. * It does not include operations, such as resize, to be applied to the output image.
* *
* Dimensions in the response will respect the `page` and `pages` properties of the
* {@link /api-constructor#parameters|constructor parameters}.
*
* A `Promise` is returned when `callback` is not provided. * A `Promise` is returned when `callback` is not provided.
* *
* - `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg` * - `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg`
* - `size`: Total size of image in bytes, for Stream and Buffer input only * - `size`: Total size of image in bytes, for Stream and Buffer input only
* - `width`: Number of pixels wide (EXIF orientation is not taken into consideration) * - `width`: Number of pixels wide (EXIF orientation is not taken into consideration, see example below)
* - `height`: Number of pixels high (EXIF orientation is not taken into consideration) * - `height`: Number of pixels high (EXIF orientation is not taken into consideration, see example below)
* - `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://libvips.github.io/libvips/API/current/VipsImage.html#VipsInterpretation) * - `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://www.libvips.org/API/current/VipsImage.html#VipsInterpretation)
* - `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK * - `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK
* - `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...](https://libvips.github.io/libvips/API/current/VipsImage.html#VipsBandFormat) * - `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...](https://www.libvips.org/API/current/VipsImage.html#VipsBandFormat)
* - `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
@@ -343,6 +441,17 @@ function _isStreamInput () {
* // data contains a WebP image half the width and height of the original JPEG * // data contains a WebP image half the width and height of the original JPEG
* }); * });
* *
* @example
* // Based on EXIF rotation metadata, get the right-side-up width and height:
*
* const size = getNormalSize(await sharp(input).metadata());
*
* 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}
*/ */
@@ -360,7 +469,7 @@ function metadata (callback) {
} else { } else {
if (this._isStreamInput()) { if (this._isStreamInput()) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.on('finish', () => { const finished = () => {
this._flattenBufferIn(); this._flattenBufferIn();
sharp.metadata(this.options, (err, metadata) => { sharp.metadata(this.options, (err, metadata) => {
if (err) { if (err) {
@@ -369,7 +478,12 @@ function metadata (callback) {
resolve(metadata); resolve(metadata);
} }
}); });
}); };
if (this.writableFinished) {
finished();
} else {
this.once('finish', finished);
}
}); });
} else { } else {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@@ -401,9 +515,9 @@ function metadata (callback) {
* - `maxX` (x-coordinate of one of the pixel where the maximum lies) * - `maxX` (x-coordinate of one of the pixel where the maximum lies)
* - `maxY` (y-coordinate of one of the pixel where the maximum lies) * - `maxY` (y-coordinate of one of the pixel where the maximum lies)
* - `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque. * - `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque.
* - `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any (experimental) * - `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any.
* - `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any (experimental) * - `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any.
* - `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram (experimental) * - `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram.
* *
* **Note**: Statistics are derived from the original input image. Any operations performed on the image must first be * **Note**: Statistics are derived from the original input image. Any operations performed on the image must first be
* written to a buffer in order to run `stats` on the result (see third example). * written to a buffer in order to run `stats` on the result (see third example).
@@ -485,4 +599,6 @@ module.exports = function (Sharp) {
metadata, metadata,
stats stats
}); });
// Class attributes
Sharp.align = align;
}; };

View File

@@ -65,7 +65,13 @@ const isRosetta = function () {
const globalLibvipsVersion = function () { const globalLibvipsVersion = function () {
if (process.platform !== 'win32') { if (process.platform !== 'win32') {
const globalLibvipsVersion = spawnSync(`PKG_CONFIG_PATH="${pkgConfigPath()}" pkg-config --modversion vips-cpp`, spawnSyncOptions).stdout; const globalLibvipsVersion = spawnSync('pkg-config --modversion vips-cpp', {
...spawnSyncOptions,
env: {
...env,
PKG_CONFIG_PATH: pkgConfigPath()
}
}).stdout;
/* istanbul ignore next */ /* istanbul ignore next */
return (globalLibvipsVersion || '').trim(); return (globalLibvipsVersion || '').trim();
} else { } else {
@@ -83,12 +89,21 @@ const removeVendoredLibvips = function () {
rm(vendorPath, { recursive: true, maxRetries: 3, force: true }); rm(vendorPath, { recursive: true, maxRetries: 3, force: true });
}; };
/* istanbul ignore next */
const pkgConfigPath = function () { const pkgConfigPath = function () {
if (process.platform !== 'win32') { if (process.platform !== 'win32') {
const brewPkgConfigPath = spawnSync('which brew >/dev/null 2>&1 && eval $(brew --env) && echo $PKG_CONFIG_LIBDIR', spawnSyncOptions).stdout || ''; const brewPkgConfigPath = spawnSync(
return [brewPkgConfigPath.trim(), env.PKG_CONFIG_PATH, '/usr/local/lib/pkgconfig', '/usr/lib/pkgconfig'] 'which brew >/dev/null 2>&1 && brew environment --plain | grep PKG_CONFIG_LIBDIR | cut -d" " -f2',
.filter(function (p) { return !!p; }) spawnSyncOptions
.join(':'); ).stdout || '';
return [
brewPkgConfigPath.trim(),
env.PKG_CONFIG_PATH,
'/usr/local/lib/pkgconfig',
'/usr/lib/pkgconfig',
'/usr/local/libdata/pkgconfig',
'/usr/libdata/pkgconfig'
].filter(Boolean).join(':');
} else { } else {
return ''; return '';
} }

View File

@@ -18,8 +18,11 @@ const is = require('./is');
* *
* The use of `rotate` implies the removal of the EXIF `Orientation` tag, if any. * The use of `rotate` implies the removal of the EXIF `Orientation` tag, if any.
* *
* Method order is important when both rotating and extracting regions, * Only one rotation can occur per pipeline.
* for example `rotate(x).extract(y)` will produce a different result to `extract(y).rotate(x)`. * Previous calls to `rotate` in the same pipeline will be ignored.
*
* 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 * @example
* const pipeline = sharp() * const pipeline = sharp()
@@ -32,6 +35,16 @@ const is = require('./is');
* }); * });
* readableStream.pipe(pipeline); * 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 {number} [angle=auto] angle of rotation.
* @param {Object} [options] - if present, is an Object with optional attributes. * @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. * @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.
@@ -39,6 +52,9 @@ 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; this.options.useExifOrientation = true;
} else if (is.integer(angle) && !(angle % 90)) { } else if (is.integer(angle) && !(angle % 90)) {
@@ -61,8 +77,12 @@ function rotate (angle, options) {
} }
/** /**
* 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 before 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.
*
* @example
* const output = await sharp(input).flip().toBuffer();
*
* @param {Boolean} [flip=true] * @param {Boolean} [flip=true]
* @returns {Sharp} * @returns {Sharp}
*/ */
@@ -72,8 +92,12 @@ function flip (flip) {
} }
/** /**
* Flop the image about the horizontal X axis. This always occurs after rotation, if any. * Flop the image about the horizontal X axis. This always occurs before rotation, if any.
* The use of `flop` implies the removal of the EXIF `Orientation` tag, if any. * The use of `flop` implies the removal of the EXIF `Orientation` tag, if any.
*
* @example
* const output = await sharp(input).flop().toBuffer();
*
* @param {Boolean} [flop=true] * @param {Boolean} [flop=true]
* @returns {Sharp} * @returns {Sharp}
*/ */
@@ -181,44 +205,113 @@ function affine (matrix, options) {
/** /**
* Sharpen the image. * Sharpen the image.
* When used without parameters, performs a fast, mild sharpen of the output image.
* When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space.
* Separate control over the level of sharpening in "flat" and "jagged" areas is available.
* *
* @param {number} [sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. * When used without parameters, performs a fast, mild sharpen of the output image.
* @param {number} [flat=1.0] - the level of sharpening to apply to "flat" areas. *
* @param {number} [jagged=2.0] - the level of sharpening to apply to "jagged" areas. * When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space.
* Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available.
*
* See {@link https://www.libvips.org/API/current/libvips-convolution.html#vips-sharpen|libvips sharpen} operation.
*
* @example
* const data = await sharp(input).sharpen().toBuffer();
*
* @example
* const data = await sharp(input).sharpen({ sigma: 2 }).toBuffer();
*
* @example
* const data = await sharp(input)
* .sharpen({
* sigma: 2,
* m1: 0,
* m2: 3,
* x1: 3,
* y2: 15,
* y3: 15,
* })
* .toBuffer();
*
* @param {Object|number} [options] - if present, is an Object with attributes
* @param {number} [options.sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`, between 0.000001 and 10000
* @param {number} [options.m1=1.0] - the level of sharpening to apply to "flat" areas, between 0 and 1000000
* @param {number} [options.m2=2.0] - the level of sharpening to apply to "jagged" areas, between 0 and 1000000
* @param {number} [options.x1=2.0] - threshold between "flat" and "jagged", between 0 and 1000000
* @param {number} [options.y2=10.0] - maximum amount of brightening, between 0 and 1000000
* @param {number} [options.y3=20.0] - maximum amount of darkening, between 0 and 1000000
* @param {number} [flat] - (deprecated) see `options.m1`.
* @param {number} [jagged] - (deprecated) see `options.m2`.
* @returns {Sharp} * @returns {Sharp}
* @throws {Error} Invalid parameters * @throws {Error} Invalid parameters
*/ */
function sharpen (sigma, flat, jagged) { function sharpen (options, flat, jagged) {
if (!is.defined(sigma)) { if (!is.defined(options)) {
// No arguments: default to mild sharpen // No arguments: default to mild sharpen
this.options.sharpenSigma = -1; this.options.sharpenSigma = -1;
} else if (is.bool(sigma)) { } else if (is.bool(options)) {
// Boolean argument: apply mild sharpen? // Deprecated boolean argument: apply mild sharpen?
this.options.sharpenSigma = sigma ? -1 : 0; this.options.sharpenSigma = options ? -1 : 0;
} else if (is.number(sigma) && is.inRange(sigma, 0.01, 10000)) { } else if (is.number(options) && is.inRange(options, 0.01, 10000)) {
// Numeric argument: specific sigma // Deprecated numeric argument: specific sigma
this.options.sharpenSigma = sigma; this.options.sharpenSigma = options;
// Control over flat areas // Deprecated control over flat areas
if (is.defined(flat)) { if (is.defined(flat)) {
if (is.number(flat) && is.inRange(flat, 0, 10000)) { if (is.number(flat) && is.inRange(flat, 0, 10000)) {
this.options.sharpenFlat = flat; this.options.sharpenM1 = flat;
} else { } else {
throw is.invalidParameterError('flat', 'number between 0 and 10000', flat); throw is.invalidParameterError('flat', 'number between 0 and 10000', flat);
} }
} }
// Control over jagged areas // Deprecated control over jagged areas
if (is.defined(jagged)) { if (is.defined(jagged)) {
if (is.number(jagged) && is.inRange(jagged, 0, 10000)) { if (is.number(jagged) && is.inRange(jagged, 0, 10000)) {
this.options.sharpenJagged = jagged; this.options.sharpenM2 = jagged;
} else { } else {
throw is.invalidParameterError('jagged', 'number between 0 and 10000', jagged); throw is.invalidParameterError('jagged', 'number between 0 and 10000', jagged);
} }
} }
} else if (is.plainObject(options)) {
if (is.number(options.sigma) && is.inRange(options.sigma, 0.000001, 10000)) {
this.options.sharpenSigma = options.sigma;
} else {
throw is.invalidParameterError('options.sigma', 'number between 0.000001 and 10000', options.sigma);
}
if (is.defined(options.m1)) {
if (is.number(options.m1) && is.inRange(options.m1, 0, 1000000)) {
this.options.sharpenM1 = options.m1;
} else {
throw is.invalidParameterError('options.m1', 'number between 0 and 1000000', options.m1);
}
}
if (is.defined(options.m2)) {
if (is.number(options.m2) && is.inRange(options.m2, 0, 1000000)) {
this.options.sharpenM2 = options.m2;
} else {
throw is.invalidParameterError('options.m2', 'number between 0 and 1000000', options.m2);
}
}
if (is.defined(options.x1)) {
if (is.number(options.x1) && is.inRange(options.x1, 0, 1000000)) {
this.options.sharpenX1 = options.x1;
} else {
throw is.invalidParameterError('options.x1', 'number between 0 and 1000000', options.x1);
}
}
if (is.defined(options.y2)) {
if (is.number(options.y2) && is.inRange(options.y2, 0, 1000000)) {
this.options.sharpenY2 = options.y2;
} else {
throw is.invalidParameterError('options.y2', 'number between 0 and 1000000', options.y2);
}
}
if (is.defined(options.y3)) {
if (is.number(options.y3) && is.inRange(options.y3, 0, 1000000)) {
this.options.sharpenY3 = options.y3;
} else {
throw is.invalidParameterError('options.y3', 'number between 0 and 1000000', options.y3);
}
}
} else { } else {
throw is.invalidParameterError('sigma', 'number between 0.01 and 10000', sigma); throw is.invalidParameterError('sigma', 'number between 0.01 and 10000', options);
} }
return this; return this;
} }
@@ -226,6 +319,13 @@ function sharpen (sigma, flat, jagged) {
/** /**
* Apply median filter. * Apply median filter.
* When used without parameters the default window is 3x3. * When used without parameters the default window is 3x3.
*
* @example
* const output = await sharp(input).median().toBuffer();
*
* @example
* const output = await sharp(input).median(5).toBuffer();
*
* @param {number} [size=3] square mask size: size x size * @param {number} [size=3] square mask size: size x size
* @returns {Sharp} * @returns {Sharp}
* @throws {Error} Invalid parameters * @throws {Error} Invalid parameters
@@ -338,6 +438,17 @@ function gamma (gamma, gammaOut) {
/** /**
* Produce the "negative" of the image. * Produce the "negative" of the image.
*
* @example
* const output = await sharp(input)
* .negate()
* .toBuffer();
*
* @example
* const output = await sharp(input)
* .negate({ alpha: false })
* .toBuffer();
*
* @param {Object} [options] * @param {Object} [options]
* @param {Boolean} [options.alpha=true] Whether or not to negate any alpha channel * @param {Boolean} [options.alpha=true] Whether or not to negate any alpha channel
* @returns {Sharp} * @returns {Sharp}
@@ -356,6 +467,10 @@ function negate (options) {
/** /**
* Enhance output image contrast by stretching its luminance to cover the full dynamic range. * Enhance output image contrast by stretching its luminance to cover the full dynamic range.
*
* @example
* const output = await sharp(input).normalise().toBuffer();
*
* @param {Boolean} [normalise=true] * @param {Boolean} [normalise=true]
* @returns {Sharp} * @returns {Sharp}
*/ */
@@ -366,6 +481,10 @@ function normalise (normalise) {
/** /**
* Alternative spelling of normalise. * Alternative spelling of normalise.
*
* @example
* const output = await sharp(input).normalize().toBuffer();
*
* @param {Boolean} [normalize=true] * @param {Boolean} [normalize=true]
* @returns {Sharp} * @returns {Sharp}
*/ */
@@ -381,6 +500,14 @@ function normalize (normalize) {
* *
* @since 0.28.3 * @since 0.28.3
* *
* @example
* const output = await sharp(input)
* .clahe({
* width: 3,
* height: 3,
* })
* .toBuffer();
*
* @param {Object} options * @param {Object} options
* @param {number} options.width - integer width of the region in pixels. * @param {number} options.width - integer width of the region in pixels.
* @param {number} options.height - integer height of the region in pixels. * @param {number} options.height - integer height of the region in pixels.
@@ -519,26 +646,55 @@ function boolean (operand, operator, options) {
} }
/** /**
* Apply the linear formula a * input + b to the image (levels adjustment) * Apply the linear formula `a` * input + `b` to the image to adjust image levels.
* @param {number} [a=1.0] multiplier *
* @param {number} [b=0.0] offset * When a single number is provided, it will be used for all image channels.
* When an array of numbers is provided, the array length must match the number of channels.
*
* @example
* await sharp(input)
* .linear(0.5, 2)
* .toBuffer();
*
* @example
* await sharp(rgbInput)
* .linear(
* [0.25, 0.5, 0.75],
* [150, 100, 50]
* )
* .toBuffer();
*
* @param {(number|number[])} [a=[]] multiplier
* @param {(number|number[])} [b=[]] offset
* @returns {Sharp} * @returns {Sharp}
* @throws {Error} Invalid parameters * @throws {Error} Invalid parameters
*/ */
function linear (a, b) { function linear (a, b) {
if (!is.defined(a) && is.number(b)) {
a = 1.0;
} else if (is.number(a) && !is.defined(b)) {
b = 0.0;
}
if (!is.defined(a)) { if (!is.defined(a)) {
this.options.linearA = 1.0; this.options.linearA = [];
} else if (is.number(a)) { } else if (is.number(a)) {
this.options.linearA = [a];
} else if (Array.isArray(a) && a.length && a.every(is.number)) {
this.options.linearA = a; this.options.linearA = a;
} else { } else {
throw is.invalidParameterError('a', 'numeric', a); throw is.invalidParameterError('a', 'number or array of numbers', a);
} }
if (!is.defined(b)) { if (!is.defined(b)) {
this.options.linearB = 0.0; this.options.linearB = [];
} else if (is.number(b)) { } else if (is.number(b)) {
this.options.linearB = [b];
} else if (Array.isArray(b) && b.length && b.every(is.number)) {
this.options.linearB = b; this.options.linearB = b;
} else { } else {
throw is.invalidParameterError('b', 'numeric', b); throw is.invalidParameterError('b', 'number or array of numbers', b);
}
if (this.options.linearA.length !== this.options.linearB.length) {
throw new Error('Expected a and b to be arrays of the same length');
} }
return this; return this;
} }
@@ -590,28 +746,38 @@ function recomb (inputMatrix) {
* @since 0.22.1 * @since 0.22.1
* *
* @example * @example
* sharp(input) * // increase brightness by a factor of 2
* const output = await sharp(input)
* .modulate({ * .modulate({
* brightness: 2 // increase brightness by a factor of 2 * brightness: 2
* }); * })
* .toBuffer();
* *
* sharp(input) * @example
* // hue-rotate by 180 degrees
* const output = await sharp(input)
* .modulate({ * .modulate({
* hue: 180 // hue-rotate by 180 degrees * hue: 180
* }); * })
* .toBuffer();
* *
* sharp(input) * @example
* // increase lightness by +50
* const output = await sharp(input)
* .modulate({ * .modulate({
* lightness: 50 // increase lightness by +50 * lightness: 50
* }); * })
* .toBuffer();
* *
* @example
* // decreate brightness and saturation while also hue-rotating by 90 degrees * // decreate brightness and saturation while also hue-rotating by 90 degrees
* sharp(input) * const output = await sharp(input)
* .modulate({ * .modulate({
* brightness: 0.5, * brightness: 0.5,
* saturation: 0.5, * saturation: 0.5,
* hue: 90 * hue: 90,
* }); * })
* .toBuffer();
* *
* @param {Object} [options] * @param {Object} [options]
* @param {number} [options.brightness] Brightness multiplier * @param {number} [options.brightness] Brightness multiplier

View File

@@ -10,6 +10,9 @@ const formats = new Map([
['avif', 'avif'], ['avif', 'avif'],
['jpeg', 'jpeg'], ['jpeg', 'jpeg'],
['jpg', 'jpeg'], ['jpg', 'jpeg'],
['jpe', 'jpeg'],
['tile', 'tile'],
['dz', 'tile'],
['png', 'png'], ['png', 'png'],
['raw', 'raw'], ['raw', 'raw'],
['tiff', 'tiff'], ['tiff', 'tiff'],
@@ -19,10 +22,13 @@ const formats = new Map([
['jp2', 'jp2'], ['jp2', 'jp2'],
['jpx', 'jp2'], ['jpx', 'jp2'],
['j2k', 'jp2'], ['j2k', 'jp2'],
['j2c', 'jp2'] ['j2c', 'jp2'],
['jxl', 'jxl']
]); ]);
const errJp2Save = new Error('JP2 output requires libvips with support for OpenJPEG'); const jp2Regex = /\.jp[2x]|j2[kc]$/i;
const errJp2Save = () => new Error('JP2 output requires libvips with support for OpenJPEG');
const bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math.log2(colours))); const bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math.log2(colours)));
@@ -55,6 +61,7 @@ const bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math
* `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`.
* 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
*/ */
@@ -64,6 +71,8 @@ function toFile (fileOut, callback) {
err = new Error('Missing output file path'); err = new Error('Missing output file path');
} else if (is.string(this.options.input.file) && path.resolve(this.options.input.file) === path.resolve(fileOut)) { } else if (is.string(this.options.input.file) && path.resolve(this.options.input.file) === path.resolve(fileOut)) {
err = new Error('Cannot use same file for input and output'); err = new Error('Cannot use same file for input and output');
} else if (jp2Regex.test(fileOut) && !this.constructor.format.jp2k.output.file) {
err = errJp2Save();
} }
if (err) { if (err) {
if (is.fn(callback)) { if (is.fn(callback)) {
@@ -82,6 +91,8 @@ function toFile (fileOut, callback) {
* Write output to a Buffer. * Write output to a Buffer.
* JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported. * JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.
* *
* Use {@link toFormat} or one of the format-specific functions such as {@link jpeg}, {@link png} etc. to set the output format.
*
* If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output. * If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output.
* *
* By default all metadata will be removed, which includes EXIF-based orientation. * By default all metadata will be removed, which includes EXIF-based orientation.
@@ -93,6 +104,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`.
* 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.
* *
@@ -108,6 +120,7 @@ function toFile (fileOut, callback) {
* *
* @example * @example
* sharp(input) * sharp(input)
* .png()
* .toBuffer({ resolveWithObject: true }) * .toBuffer({ resolveWithObject: true })
* .then(({ data, info }) => { ... }) * .then(({ data, info }) => { ... })
* .catch(err => { ... }); * .catch(err => { ... });
@@ -139,6 +152,7 @@ function toBuffer (options, callback) {
} else if (this.options.resolveWithObject) { } else if (this.options.resolveWithObject) {
this.options.resolveWithObject = false; this.options.resolveWithObject = false;
} }
this.options.fileOut = '';
return this._pipeline(is.fn(options) ? options : callback); return this._pipeline(is.fn(options) ? options : callback);
} }
@@ -150,6 +164,8 @@ function toBuffer (options, callback) {
* The default behaviour, when `withMetadata` is not used, is to convert to the device-independent * The default behaviour, when `withMetadata` is not used, is to convert to the device-independent
* sRGB colour space and strip all metadata, including the removal of any ICC profile. * sRGB colour space and strip all metadata, including the removal of any ICC profile.
* *
* EXIF metadata is unsupported for TIFF output.
*
* @example * @example
* sharp('input.jpg') * sharp('input.jpg')
* .withMetadata() * .withMetadata()
@@ -396,6 +412,14 @@ function png (options) {
if (is.defined(options.adaptiveFiltering)) { if (is.defined(options.adaptiveFiltering)) {
this._setBooleanOption('pngAdaptiveFiltering', options.adaptiveFiltering); this._setBooleanOption('pngAdaptiveFiltering', options.adaptiveFiltering);
} }
const colours = options.colours || options.colors;
if (is.defined(colours)) {
if (is.integer(colours) && is.inRange(colours, 2, 256)) {
this.options.pngBitdepth = bitdepthFromColourCount(colours);
} else {
throw is.invalidParameterError('colours', 'integer between 2 and 256', colours);
}
}
if (is.defined(options.palette)) { if (is.defined(options.palette)) {
this._setBooleanOption('pngPalette', options.palette); this._setBooleanOption('pngPalette', options.palette);
} else if ([options.quality, options.effort, options.colours, options.colors, options.dither].some(is.defined)) { } else if ([options.quality, options.effort, options.colours, options.colors, options.dither].some(is.defined)) {
@@ -416,14 +440,6 @@ function png (options) {
throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort); throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort);
} }
} }
const colours = options.colours || options.colors;
if (is.defined(colours)) {
if (is.integer(colours) && is.inRange(colours, 2, 256)) {
this.options.pngBitdepth = bitdepthFromColourCount(colours);
} else {
throw is.invalidParameterError('colours', 'integer between 2 and 256', colours);
}
}
if (is.defined(options.dither)) { if (is.defined(options.dither)) {
if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) { if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) {
this.options.pngDither = options.dither; this.options.pngDither = options.dither;
@@ -460,6 +476,8 @@ function png (options) {
* @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
* @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.minSize=false] - prevent use of animation key frames to minimise file size (slow)
* @param {boolean} [options.mixed=false] - allow mixture of lossy and lossless animation frames (slow)
* @param {boolean} [options.force=true] - force WebP output, otherwise attempt to use input format * @param {boolean} [options.force=true] - force WebP output, otherwise attempt to use input format
* @returns {Sharp} * @returns {Sharp}
* @throws {Error} Invalid options * @throws {Error} Invalid options
@@ -489,14 +507,19 @@ function webp (options) {
if (is.defined(options.smartSubsample)) { if (is.defined(options.smartSubsample)) {
this._setBooleanOption('webpSmartSubsample', options.smartSubsample); this._setBooleanOption('webpSmartSubsample', options.smartSubsample);
} }
const effort = options.effort || options.reductionEffort; if (is.defined(options.effort)) {
if (is.defined(effort)) { if (is.integer(options.effort) && is.inRange(options.effort, 0, 6)) {
if (is.integer(effort) && is.inRange(effort, 0, 6)) { this.options.webpEffort = options.effort;
this.options.webpEffort = effort;
} else { } else {
throw is.invalidParameterError('effort', 'integer between 0 and 6', effort); throw is.invalidParameterError('effort', 'integer between 0 and 6', options.effort);
} }
} }
if (is.defined(options.minSize)) {
this._setBooleanOption('webpMinSize', options.minSize);
}
if (is.defined(options.mixed)) {
this._setBooleanOption('webpMixed', options.mixed);
}
} }
trySetAnimationOptions(options, this.options); trySetAnimationOptions(options, this.options);
return this._updateFormatOut('webp', options); return this._updateFormatOut('webp', options);
@@ -507,13 +530,15 @@ function webp (options) {
* *
* The first entry in the palette is reserved for transparency. * The first entry in the palette is reserved for transparency.
* *
* The palette of the input image will be re-used if possible.
*
* @since 0.30.0 * @since 0.30.0
* *
* @example * @example
* // Convert PNG to GIF * // Convert PNG to GIF
* await sharp(pngBuffer) * await sharp(pngBuffer)
* .gif() * .gif()
* .toBuffer()); * .toBuffer();
* *
* @example * @example
* // Convert animated WebP to animated GIF * // Convert animated WebP to animated GIF
@@ -527,11 +552,21 @@ function webp (options) {
* .gif({ dither: 0 }) * .gif({ dither: 0 })
* .toBuffer(); * .toBuffer();
* *
* @example
* // Lossy file size reduction of animated GIF
* await sharp('in.gif', { animated: true })
* .gif({ interFrameMaxError: 8 })
* .toFile('optim.gif');
*
* @param {Object} [options] - output options * @param {Object} [options] - output options
* @param {boolean} [options.reoptimise=false] - always generate new palettes (slow), re-use existing by default
* @param {boolean} [options.reoptimize=false] - alternative spelling of `options.reoptimise`
* @param {number} [options.colours=256] - maximum number of palette entries, including transparency, between 2 and 256 * @param {number} [options.colours=256] - maximum number of palette entries, including transparency, between 2 and 256
* @param {number} [options.colors=256] - alternative spelling of `options.colours` * @param {number} [options.colors=256] - alternative spelling of `options.colours`
* @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest) * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest)
* @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.interPaletteMaxError=3] - maximum inter-palette error for palette reuse, between 0 and 256
* @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
@@ -540,6 +575,11 @@ function webp (options) {
*/ */
function gif (options) { function gif (options) {
if (is.object(options)) { if (is.object(options)) {
if (is.defined(options.reoptimise)) {
this._setBooleanOption('gifReoptimise', options.reoptimise);
} else if (is.defined(options.reoptimize)) {
this._setBooleanOption('gifReoptimise', options.reoptimize);
}
const colours = options.colours || options.colors; const colours = options.colours || options.colors;
if (is.defined(colours)) { if (is.defined(colours)) {
if (is.integer(colours) && is.inRange(colours, 2, 256)) { if (is.integer(colours) && is.inRange(colours, 2, 256)) {
@@ -562,6 +602,20 @@ function gif (options) {
throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither); throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither);
} }
} }
if (is.defined(options.interFrameMaxError)) {
if (is.number(options.interFrameMaxError) && is.inRange(options.interFrameMaxError, 0, 32)) {
this.options.gifInterFrameMaxError = options.interFrameMaxError;
} else {
throw is.invalidParameterError('interFrameMaxError', 'number between 0.0 and 32.0', options.interFrameMaxError);
}
}
if (is.defined(options.interPaletteMaxError)) {
if (is.number(options.interPaletteMaxError) && is.inRange(options.interPaletteMaxError, 0, 256)) {
this.options.gifInterPaletteMaxError = options.interPaletteMaxError;
} else {
throw is.invalidParameterError('interPaletteMaxError', 'number between 0.0 and 256.0', options.interPaletteMaxError);
}
}
} }
trySetAnimationOptions(options, this.options); trySetAnimationOptions(options, this.options);
return this._updateFormatOut('gif', options); return this._updateFormatOut('gif', options);
@@ -603,7 +657,7 @@ function gif (options) {
/* istanbul ignore next */ /* istanbul ignore next */
function jp2 (options) { function jp2 (options) {
if (!this.constructor.format.jp2k.output.buffer) { if (!this.constructor.format.jp2k.output.buffer) {
throw errJp2Save; throw errJp2Save();
} }
if (is.object(options)) { if (is.object(options)) {
if (is.defined(options.quality)) { if (is.defined(options.quality)) {
@@ -696,7 +750,7 @@ function trySetAnimationOptions (source, target) {
* @param {Object} [options] - output options * @param {Object} [options] - output options
* @param {number} [options.quality=80] - quality, integer 1-100 * @param {number} [options.quality=80] - quality, integer 1-100
* @param {boolean} [options.force=true] - force TIFF output, otherwise attempt to use input format * @param {boolean} [options.force=true] - force TIFF output, otherwise attempt to use input format
* @param {string} [options.compression='jpeg'] - compression options: lzw, deflate, jpeg, ccittfax4 * @param {string} [options.compression='jpeg'] - compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k
* @param {string} [options.predictor='horizontal'] - compression predictor options: none, horizontal, float * @param {string} [options.predictor='horizontal'] - compression predictor options: none, horizontal, float
* @param {boolean} [options.pyramid=false] - write an image pyramid * @param {boolean} [options.pyramid=false] - write an image pyramid
* @param {boolean} [options.tile=false] - write a tiled tiff * @param {boolean} [options.tile=false] - write a tiled tiff
@@ -764,10 +818,10 @@ function tiff (options) {
} }
// compression // compression
if (is.defined(options.compression)) { if (is.defined(options.compression)) {
if (is.string(options.compression) && is.inArray(options.compression, ['lzw', 'deflate', 'jpeg', 'ccittfax4', 'none'])) { if (is.string(options.compression) && is.inArray(options.compression, ['none', 'jpeg', 'deflate', 'packbits', 'ccittfax4', 'lzw', 'webp', 'zstd', 'jp2k'])) {
this.options.tiffCompression = options.compression; this.options.tiffCompression = options.compression;
} else { } else {
throw is.invalidParameterError('compression', 'one of: lzw, deflate, jpeg, ccittfax4, none', options.compression); throw is.invalidParameterError('compression', 'one of: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k', options.compression);
} }
} }
// predictor // predictor
@@ -798,6 +852,16 @@ function tiff (options) {
* *
* AVIF image sequences are not supported. * AVIF image sequences are not supported.
* *
* @example
* const data = await sharp(input)
* .avif({ effort: 2 })
* .toBuffer();
*
* @example
* const data = await sharp(input)
* .avif({ lossless: true })
* .toBuffer();
*
* @since 0.27.0 * @since 0.27.0
* *
* @param {Object} [options] - output options * @param {Object} [options] - output options
@@ -815,9 +879,14 @@ function avif (options) {
/** /**
* Use these HEIF options for output image. * Use these HEIF options for output image.
* *
* Support for patent-encumbered HEIC images requires the use of a * Support for patent-encumbered HEIC images using `hevc` compression requires the use of a
* globally-installed libvips compiled with support for libheif, libde265 and x265. * globally-installed libvips compiled with support for libheif, libde265 and x265.
* *
* @example
* const data = await sharp(input)
* .heif({ compression: 'hevc' })
* .toBuffer();
*
* @since 0.23.0 * @since 0.23.0
* *
* @param {Object} [options] - output options * @param {Object} [options] - output options
@@ -858,12 +927,6 @@ function heif (options) {
} else { } else {
throw is.invalidParameterError('effort', 'integer between 0 and 9', options.effort); throw is.invalidParameterError('effort', 'integer between 0 and 9', options.effort);
} }
} else if (is.defined(options.speed)) {
if (is.integer(options.speed) && is.inRange(options.speed, 0, 9)) {
this.options.heifEffort = 9 - options.speed;
} else {
throw is.invalidParameterError('speed', 'integer between 0 and 9', options.speed);
}
} }
if (is.defined(options.chromaSubsampling)) { if (is.defined(options.chromaSubsampling)) {
if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) { if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) {
@@ -876,6 +939,71 @@ function heif (options) {
return this._updateFormatOut('heif', options); return this._updateFormatOut('heif', options);
} }
/**
* Use these JPEG-XL (JXL) options for output image.
*
* This feature is experimental, please do not use in production systems.
*
* Requires libvips compiled with support for libjxl.
* The prebuilt binaries do not include this - see
* {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}.
*
* Image metadata (EXIF, XMP) is unsupported.
*
* @since 0.31.3
*
* @param {Object} [options] - output options
* @param {number} [options.distance=1.0] - maximum encoding error, between 0 (highest quality) and 15 (lowest quality)
* @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 {boolean} [options.lossless=false] - use lossless compression
* @param {number} [options.effort=7] - CPU effort, between 3 (fastest) and 9 (slowest)
* @returns {Sharp}
* @throws {Error} Invalid options
*/
function jxl (options) {
if (is.object(options)) {
if (is.defined(options.quality)) {
if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {
// https://github.com/libjxl/libjxl/blob/0aeea7f180bafd6893c1db8072dcb67d2aa5b03d/tools/cjxl_main.cc#L640-L644
this.options.jxlDistance = options.quality >= 30
? 0.1 + (100 - options.quality) * 0.09
: 53 / 3000 * options.quality * options.quality - 23 / 20 * options.quality + 25;
} else {
throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);
}
} else if (is.defined(options.distance)) {
if (is.number(options.distance) && is.inRange(options.distance, 0, 15)) {
this.options.jxlDistance = options.distance;
} else {
throw is.invalidParameterError('distance', 'number between 0.0 and 15.0', options.distance);
}
}
if (is.defined(options.decodingTier)) {
if (is.integer(options.decodingTier) && is.inRange(options.decodingTier, 0, 4)) {
this.options.jxlDecodingTier = options.decodingTier;
} else {
throw is.invalidParameterError('decodingTier', 'integer between 0 and 4', options.decodingTier);
}
}
if (is.defined(options.lossless)) {
if (is.bool(options.lossless)) {
this.options.jxlLossless = options.lossless;
} else {
throw is.invalidParameterError('lossless', 'boolean', options.lossless);
}
}
if (is.defined(options.effort)) {
if (is.integer(options.effort) && is.inRange(options.effort, 3, 9)) {
this.options.jxlEffort = options.effort;
} else {
throw is.invalidParameterError('effort', 'integer between 3 and 9', options.effort);
}
}
}
return this._updateFormatOut('jxl', options);
}
/** /**
* Force output to be raw, uncompressed pixel data. * Force output to be raw, uncompressed pixel data.
* Pixel ordering is left-to-right, top-to-bottom, without padding. * Pixel ordering is left-to-right, top-to-bottom, without padding.
@@ -917,9 +1045,12 @@ function raw (options) {
/** /**
* 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.
* *
* The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`.
*
* @example * @example
* sharp('input.tiff') * sharp('input.tiff')
* .png() * .png()
@@ -931,6 +1062,17 @@ function raw (options) {
* // output_files contains 512x512 tiles grouped by zoom level * // output_files contains 512x512 tiles grouped by zoom level
* }); * });
* *
* @example
* const zipFileWithTiles = await sharp(input)
* .tile({ basename: "tiles" })
* .toBuffer();
*
* @example
* const iiififier = sharp().tile({ layout: "iiif" });
* readableStream
* .pipe(iiififier)
* .pipe(writeableStream);
*
* @param {Object} [options] * @param {Object} [options]
* @param {number} [options.size=256] tile size in pixels, a value between 1 and 8192. * @param {number} [options.size=256] tile size in pixels, a value between 1 and 8192.
* @param {number} [options.overlap=0] tile overlap in pixels, a value between 0 and 8192. * @param {number} [options.overlap=0] tile overlap in pixels, a value between 0 and 8192.
@@ -943,6 +1085,7 @@ function raw (options) {
* @param {boolean} [options.centre=false] centre image in tile. * @param {boolean} [options.centre=false] centre image in tile.
* @param {boolean} [options.center=false] alternative spelling of centre. * @param {boolean} [options.center=false] alternative spelling of centre.
* @param {string} [options.id='https://example.com/iiif'] when `layout` is `iiif`/`iiif3`, sets the `@id`/`id` attribute of `info.json` * @param {string} [options.id='https://example.com/iiif'] when `layout` is `iiif`/`iiif3`, sets the `@id`/`id` attribute of `info.json`
* @param {string} [options.basename] the name of the directory within the zip file when container is `zip`.
* @returns {Sharp} * @returns {Sharp}
* @throws {Error} Invalid parameters * @throws {Error} Invalid parameters
*/ */
@@ -1024,6 +1167,14 @@ function tile (options) {
throw is.invalidParameterError('id', 'string', options.id); throw is.invalidParameterError('id', 'string', options.id);
} }
} }
// Basename for zip container
if (is.defined(options.basename)) {
if (is.string(options.basename)) {
this.options.tileBasename = options.basename;
} else {
throw is.invalidParameterError('basename', 'string', options.basename);
}
}
} }
// Format // Format
if (is.inArray(this.options.formatOut, ['jpeg', 'png', 'webp'])) { if (is.inArray(this.options.formatOut, ['jpeg', 'png', 'webp'])) {
@@ -1041,6 +1192,17 @@ function tile (options) {
* The clock starts when libvips opens an input image for processing. * The clock starts when libvips opens an input image for processing.
* Time spent waiting for a libuv thread to become available is not included. * Time spent waiting for a libuv thread to become available is not included.
* *
* @example
* // Ensure processing takes no longer than 3 seconds
* try {
* const data = await sharp(input)
* .blur(1000)
* .timeout({ seconds: 3 })
* .toBuffer();
* } catch (err) {
* if (err.message.includes('timeout')) { ... }
* }
*
* @since 0.29.2 * @since 0.29.2
* *
* @param {Object} options * @param {Object} options
@@ -1135,7 +1297,7 @@ function _pipeline (callback) {
this.push(data); this.push(data);
} }
this.push(null); this.push(null);
this.emit('close'); this.on('end', () => this.emit('close'));
}); });
}); });
if (this.streamInFinished) { if (this.streamInFinished) {
@@ -1151,7 +1313,7 @@ function _pipeline (callback) {
this.push(data); this.push(data);
} }
this.push(null); this.push(null);
this.emit('close'); this.on('end', () => this.emit('close'));
}); });
} }
return this; return this;
@@ -1212,6 +1374,7 @@ module.exports = function (Sharp) {
tiff, tiff,
avif, avif,
heif, heif,
jxl,
gif, gif,
raw, raw,
tile, tile,

View File

@@ -7,10 +7,12 @@ const env = process.env;
module.exports = function () { module.exports = function () {
const arch = env.npm_config_arch || process.arch; const arch = env.npm_config_arch || process.arch;
const platform = env.npm_config_platform || process.platform; const platform = env.npm_config_platform || process.platform;
/* istanbul ignore next */ const libc = process.env.npm_config_libc ||
const libc = (platform === 'linux' && detectLibc.isNonGlibcLinuxSync()) ? detectLibc.familySync() : ''; /* istanbul ignore next */
(detectLibc.isNonGlibcLinuxSync() ? detectLibc.familySync() : '');
const libcId = platform !== 'linux' || libc === detectLibc.GLIBC ? '' : libc;
const platformId = [`${platform}${libc}`]; const platformId = [`${platform}${libcId}`];
if (arch === 'arm') { if (arch === 'arm') {
const fallback = process.versions.electron ? '7' : '6'; const fallback = process.versions.electron ? '7' : '6';

View File

@@ -92,6 +92,13 @@ function isRotationExpected (options) {
return (options.angle % 360) !== 0 || options.useExifOrientation === true || options.rotationAngle !== 0; return (options.angle % 360) !== 0 || options.useExifOrientation === true || options.rotationAngle !== 0;
} }
/**
* @private
*/
function isResizeExpected (options) {
return options.width !== -1 || options.height !== -1;
}
/** /**
* Resize image to `width`, `height` or `width x height`. * Resize image to `width`, `height` or `width x height`.
* *
@@ -104,7 +111,9 @@ function isRotationExpected (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.
* *
* When using a `fit` of `cover` or `contain`, the default **position** is `centre`. Other options are: * <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.png">
*
* 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`.
* - `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`. * - `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`.
* - `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy. * - `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy.
@@ -123,6 +132,9 @@ function isRotationExpected (options) {
* - `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).
* *
* Only one resize can occur per pipeline.
* Previous calls to `resize` in the same pipeline will be ignored.
*
* @example * @example
* sharp(input) * sharp(input)
* .resize({ width: 100 }) * .resize({ width: 100 })
@@ -207,11 +219,11 @@ function isRotationExpected (options) {
* @param {number} [width] - pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height. * @param {number} [width] - pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height.
* @param {number} [height] - pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width. * @param {number} [height] - pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width.
* @param {Object} [options] * @param {Object} [options]
* @param {String} [options.width] - alternative means of specifying `width`. If both are present this take priority. * @param {String} [options.width] - alternative means of specifying `width`. If both are present this takes priority.
* @param {String} [options.height] - alternative means of specifying `height`. If both are present this take priority. * @param {String} [options.height] - alternative means of specifying `height`. If both are present this takes priority.
* @param {String} [options.fit='cover'] - how the image should be resized to fit both provided dimensions, one of `cover`, `contain`, `fill`, `inside` or `outside`. * @param {String} [options.fit='cover'] - how the image should be resized to fit both provided dimensions, one of `cover`, `contain`, `fill`, `inside` or `outside`.
* @param {String} [options.position='centre'] - position, gravity or strategy to use when `fit` is `cover` or `contain`. * @param {String} [options.position='centre'] - position, gravity or strategy to use when `fit` is `cover` or `contain`.
* @param {String|Object} [options.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour when using a `fit` of `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency. * @param {String|Object} [options.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency.
* @param {String} [options.kernel='lanczos3'] - the kernel to use for image reduction. * @param {String} [options.kernel='lanczos3'] - the kernel to use for image reduction.
* @param {Boolean} [options.withoutEnlargement=false] - do not enlarge if the width *or* height are already less than the specified dimensions, equivalent to GraphicsMagick's `>` geometry option. * @param {Boolean} [options.withoutEnlargement=false] - do not enlarge if the width *or* height are already less than the specified dimensions, equivalent to GraphicsMagick's `>` geometry option.
* @param {Boolean} [options.withoutReduction=false] - do not reduce if the width *or* height are already greater than the specified dimensions, equivalent to GraphicsMagick's `<` geometry option. * @param {Boolean} [options.withoutReduction=false] - do not reduce if the width *or* height are already greater than the specified dimensions, equivalent to GraphicsMagick's `<` geometry option.
@@ -220,6 +232,9 @@ function isRotationExpected (options) {
* @throws {Error} Invalid parameters * @throws {Error} Invalid parameters
*/ */
function resize (width, height, options) { function resize (width, height, options) {
if (isResizeExpected(this.options)) {
this.options.debuglog('ignoring previous resize options');
}
if (is.defined(width)) { if (is.defined(width)) {
if (is.object(width) && !is.defined(options)) { if (is.object(width) && !is.defined(options)) {
options = width; options = width;
@@ -300,6 +315,9 @@ function resize (width, height, options) {
this._setBooleanOption('fastShrinkOnLoad', options.fastShrinkOnLoad); this._setBooleanOption('fastShrinkOnLoad', options.fastShrinkOnLoad);
} }
} }
if (isRotationExpected(this.options) && isResizeExpected(this.options)) {
this.options.rotateBeforePreExtract = true;
}
return this; return this;
} }
@@ -412,7 +430,10 @@ function extend (extend) {
* @throws {Error} Invalid parameters * @throws {Error} Invalid parameters
*/ */
function extract (options) { function extract (options) {
const suffix = this.options.width === -1 && this.options.height === -1 ? 'Pre' : 'Post'; const suffix = isResizeExpected(this.options) || this.options.widthPre !== -1 ? 'Post' : 'Pre';
if (this.options[`width${suffix}`] !== -1) {
this.options.debuglog('ignoring previous extract options');
}
['left', 'top', 'width', 'height'].forEach(function (name) { ['left', 'top', 'width', 'height'].forEach(function (name) {
const value = options[name]; const value = options[name];
if (is.integer(value) && value >= 0) { if (is.integer(value) && value >= 0) {
@@ -422,32 +443,87 @@ function extract (options) {
} }
}, this); }, this);
// Ensure existing rotation occurs before pre-resize extraction // Ensure existing rotation occurs before pre-resize extraction
if (suffix === 'Pre' && isRotationExpected(this.options)) { if (isRotationExpected(this.options) && !isResizeExpected(this.options)) {
this.options.rotateBeforePreExtract = true; if (this.options.widthPre === -1 || this.options.widthPost === -1) {
this.options.rotateBeforePreExtract = true;
}
} }
return this; return this;
} }
/** /**
* Trim "boring" pixels from all edges that contain values similar to the top-left pixel. * Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.
* Images consisting entirely of a single colour will calculate "boring" using the alpha channel, if any. *
* Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels.
*
* If the result of this operation would trim an image to nothing then no change is made.
* *
* The `info` response Object, obtained from callback of `.toFile()` or `.toBuffer()`, * The `info` response Object, obtained from callback of `.toFile()` or `.toBuffer()`,
* will contain `trimOffsetLeft` and `trimOffsetTop` properties. * will contain `trimOffsetLeft` and `trimOffsetTop` properties.
* *
* @param {number} [threshold=10] the allowed difference from the top-left pixel, a number greater than zero. * @example
* // Trim pixels with a colour similar to that of the top-left pixel.
* sharp(input)
* .trim()
* .toFile(output, function(err, info) {
* ...
* });
* @example
* // Trim pixels with the exact same colour as that of the top-left pixel.
* sharp(input)
* .trim(0)
* .toFile(output, function(err, info) {
* ...
* });
* @example
* // Trim only pixels with a similar colour to red.
* sharp(input)
* .trim("#FF0000")
* .toFile(output, function(err, info) {
* ...
* });
* @example
* // Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
* sharp(input)
* .trim({
* background: "yellow",
* threshold: 42,
* })
* .toFile(output, function(err, info) {
* ...
* });
*
* @param {string|number|Object} trim - the specific background colour to trim, the threshold for doing so or an Object with both.
* @param {string|Object} [trim.background='top-left pixel'] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel.
* @param {number} [trim.threshold=10] - the allowed difference from the above colour, a positive number.
* @returns {Sharp} * @returns {Sharp}
* @throws {Error} Invalid parameters * @throws {Error} Invalid parameters
*/ */
function trim (threshold) { function trim (trim) {
if (!is.defined(threshold)) { if (!is.defined(trim)) {
this.options.trimThreshold = 10; this.options.trimThreshold = 10;
} else if (is.number(threshold) && threshold > 0) { } else if (is.string(trim)) {
this.options.trimThreshold = threshold; this._setBackgroundColourOption('trimBackground', trim);
this.options.trimThreshold = 10;
} else if (is.number(trim)) {
if (trim >= 0) {
this.options.trimThreshold = trim;
} else {
throw is.invalidParameterError('threshold', 'positive number', trim);
}
} else if (is.object(trim)) {
this._setBackgroundColourOption('trimBackground', trim.background);
if (!is.defined(trim.threshold)) {
this.options.trimThreshold = 10;
} else if (is.number(trim.threshold) && trim.threshold >= 0) {
this.options.trimThreshold = trim.threshold;
} else {
throw is.invalidParameterError('threshold', 'positive number', trim);
}
} else { } else {
throw is.invalidParameterError('threshold', 'number greater than zero', threshold); throw is.invalidParameterError('trim', 'string, number or object', trim);
} }
if (this.options.trimThreshold && isRotationExpected(this.options)) { if (isRotationExpected(this.options)) {
this.options.rotateBeforePreExtract = true; this.options.rotateBeforePreExtract = true;
} }
return this; return this;

View File

@@ -12,8 +12,11 @@ try {
help.push('- Update Homebrew: "brew update && brew upgrade vips"'); help.push('- Update Homebrew: "brew update && brew upgrade vips"');
} else { } else {
const [platform, arch] = platformAndArch.split('-'); const [platform, arch] = platformAndArch.split('-');
if (platform === 'linux' && /Module did not self-register/.test(err.message)) {
help.push('- Using worker threads? See https://sharp.pixelplumbing.com/install#worker-threads');
}
help.push( help.push(
'- Install with the --verbose flag and look for errors: "npm install --ignore-scripts=false --verbose sharp"', '- Install with verbose logging and look for errors: "npm install --ignore-scripts=false --foreground-scripts --verbose sharp"',
`- Install for the current ${platformAndArch} runtime: "npm install --platform=${platform} --arch=${arch} sharp"` `- Install for the current ${platformAndArch} runtime: "npm install --platform=${platform} --arch=${arch} sharp"`
); );
} }
@@ -21,7 +24,7 @@ try {
'- Consult the installation documentation: https://sharp.pixelplumbing.com/install' '- Consult the installation documentation: https://sharp.pixelplumbing.com/install'
); );
// Check loaded // Check loaded
if (process.platform === 'win32') { if (process.platform === 'win32' || /symbol/.test(err.message)) {
const loadedModule = Object.keys(require.cache).find((i) => /[\\/]build[\\/]Release[\\/]sharp(.*)\.node$/.test(i)); const loadedModule = Object.keys(require.cache).find((i) => /[\\/]build[\\/]Release[\\/]sharp(.*)\.node$/.test(i));
if (loadedModule) { if (loadedModule) {
const [, loadedPackage] = loadedModule.match(/node_modules[\\/]([^\\/]+)[\\/]/); const [, loadedPackage] = loadedModule.match(/node_modules[\\/]([^\\/]+)[\\/]/);

View File

@@ -17,6 +17,10 @@ const sharp = require('./sharp');
* @returns {Object} * @returns {Object}
*/ */
const format = sharp.format(); const format = sharp.format();
format.heif.output.alias = ['avif', 'heic'];
format.jpeg.output.alias = ['jpe', 'jpg'];
format.tiff.output.alias = ['tif'];
format.jp2k.output.alias = ['j2c', 'j2k', 'jp2', 'jpx'];
/** /**
* An Object containing the available interpolators and their proper values * An Object containing the available interpolators and their proper values
@@ -30,11 +34,11 @@ const interpolators = {
bilinear: 'bilinear', bilinear: 'bilinear',
/** [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). */ /** [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). */
bicubic: 'bicubic', bicubic: 'bicubic',
/** [LBB interpolation](https://github.com/jcupitt/libvips/blob/master/libvips/resample/lbb.cpp#L100). Prevents some "[acutance](http://en.wikipedia.org/wiki/Acutance)" but typically reduces performance by a factor of 2. */ /** [LBB interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100). Prevents some "[acutance](http://en.wikipedia.org/wiki/Acutance)" but typically reduces performance by a factor of 2. */
locallyBoundedBicubic: 'lbb', locallyBoundedBicubic: 'lbb',
/** [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. */ /** [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. */
nohalo: 'nohalo', nohalo: 'nohalo',
/** [VSQBS interpolation](https://github.com/jcupitt/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents "staircasing" when enlarging. */ /** [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents "staircasing" when enlarging. */
vertexSplitQuadraticBasisSpline: 'vsqbs' vertexSplitQuadraticBasisSpline: 'vsqbs'
}; };
@@ -103,7 +107,11 @@ cache(true);
/** /**
* Gets or, when a concurrency is provided, sets * Gets or, when a concurrency is provided, sets
* the number of threads _libvips'_ should create to process each image. * the maximum number of threads _libvips_ should use to process _each image_.
* These are from a thread pool managed by glib,
* which helps avoid the overhead of creating new threads.
*
* This method always returns the current concurrency.
* *
* The default value is the number of CPU cores, * The default value is the number of CPU cores,
* except when using glibc-based Linux without jemalloc, * except when using glibc-based Linux without jemalloc,
@@ -111,10 +119,19 @@ cache(true);
* *
* A value of `0` will reset this to the number of CPU cores. * A value of `0` will reset this to the number of CPU cores.
* *
* The maximum number of images that can be processed in parallel * Some image format libraries spawn additional threads,
* is limited by libuv's `UV_THREADPOOL_SIZE` environment variable. * e.g. libaom manages its own 4 threads when encoding AVIF images,
* and these are independent of the value set here.
* *
* This method always returns the current concurrency. * The maximum number of images that sharp can process in parallel
* is controlled by libuv's `UV_THREADPOOL_SIZE` environment variable,
* 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

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.30.0", "version": "0.31.3",
"author": "Lovell Fuller <npm@lovell.info>", "author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://github.com/lovell/sharp", "homepage": "https://github.com/lovell/sharp",
"contributors": [ "contributors": [
@@ -81,16 +81,19 @@
"Taneli Vatanen <taneli.vatanen@gmail.com>", "Taneli Vatanen <taneli.vatanen@gmail.com>",
"Joris Dugué <zaruike10@gmail.com>", "Joris Dugué <zaruike10@gmail.com>",
"Chris Banks <christopher.bradley.banks@gmail.com>", "Chris Banks <christopher.bradley.banks@gmail.com>",
"Ompal Singh <ompal.hitm09@gmail.com>" "Ompal Singh <ompal.hitm09@gmail.com>",
"Brodan <christopher.hranj@gmail.com",
"Ankur Parihar <ankur.github@gmail.com>",
"Brahim Ait elhaj <brahima@gmail.com>",
"Mart Jansink <m.jansink@gmail.com>"
], ],
"scripts": { "scripts": {
"install": "(node install/libvips && node install/dll-copy && prebuild-install) || (node install/can-compile && node-gyp rebuild && node install/dll-copy)", "install": "(node install/libvips && node install/dll-copy && prebuild-install) || (node install/can-compile && node-gyp rebuild && node install/dll-copy)",
"clean": "rm -rf node_modules/ build/ vendor/ .nyc_output/ coverage/ test/fixtures/output.*", "clean": "rm -rf node_modules/ build/ vendor/ .nyc_output/ coverage/ test/fixtures/output.*",
"test": "npm run test-lint && npm run test-unit && npm run test-licensing", "test": "npm run test-lint && npm run test-unit && npm run test-licensing",
"test-lint": "semistandard && cpplint", "test-lint": "semistandard && cpplint",
"test-unit": "nyc --reporter=lcov --branches=99 mocha --slow=1000 --timeout=60000 ./test/unit/*.js", "test-unit": "nyc --reporter=lcov --reporter=text --check-coverage --branches=100 mocha",
"test-licensing": "license-checker --production --summary --onlyAllow=\"Apache-2.0;BSD;ISC;MIT\"", "test-licensing": "license-checker --production --summary --onlyAllow=\"Apache-2.0;BSD;ISC;MIT\"",
"test-coverage": "./test/coverage/report.sh",
"test-leak": "./test/leak/leak.sh", "test-leak": "./test/leak/leak.sh",
"docs-build": "documentation lint lib && node docs/build && node docs/search-index/build", "docs-build": "documentation lint lib && node docs/build && node docs/search-index/build",
"docs-serve": "cd docs && npx serve", "docs-serve": "cd docs && npx serve",
@@ -126,58 +129,58 @@
"vips" "vips"
], ],
"dependencies": { "dependencies": {
"color": "^4.2.0", "color": "^4.2.3",
"detect-libc": "^2.0.0", "detect-libc": "^2.0.1",
"node-addon-api": "^4.3.0", "node-addon-api": "^5.0.0",
"prebuild-install": "^7.0.1", "prebuild-install": "^7.1.1",
"semver": "^7.3.5", "semver": "^7.3.8",
"simple-get": "^4.0.1", "simple-get": "^4.0.1",
"tar-fs": "^2.1.1", "tar-fs": "^2.1.1",
"tunnel-agent": "^0.6.0" "tunnel-agent": "^0.6.0"
}, },
"devDependencies": { "devDependencies": {
"async": "^3.2.3", "async": "^3.2.4",
"cc": "^3.0.1", "cc": "^3.0.1",
"decompress-zip": "^0.3.3", "documentation": "^14.0.1",
"documentation": "^13.2.5",
"exif-reader": "^1.0.3", "exif-reader": "^1.0.3",
"extract-zip": "^2.0.1",
"icc": "^2.0.0", "icc": "^2.0.0",
"license-checker": "^25.0.1", "license-checker": "^25.0.1",
"mocha": "^9.2.0", "mocha": "^10.2.0",
"mock-fs": "^5.1.2", "mock-fs": "^5.2.0",
"nyc": "^15.1.0", "nyc": "^15.1.0",
"prebuild": "^11.0.2", "prebuild": "^11.0.4",
"rimraf": "^3.0.2", "rimraf": "^3.0.2",
"semistandard": "^16.0.1" "semistandard": "^16.0.1"
}, },
"license": "Apache-2.0", "license": "Apache-2.0",
"config": { "config": {
"libvips": "8.12.2", "libvips": "8.13.3",
"integrity": { "integrity": {
"darwin-arm64v8": "sha512-p46s/bbJAjkOXzPISZt9HUpG9GWjwQkYnLLRLKzsBJHLtB3X6C6Y/zXI5Hd0DOojcFkks9a0kTN+uDQ/XJY19g==", "darwin-arm64v8": "sha512-xFgYt7CtQSZcWoyUdzPTDNHbioZIrZSEU+gkMxzH4Cgjhi4/N49UsonnIZhKQoTBGloAqEexHeMx4rYTQ2Kgvw==",
"darwin-x64": "sha512-6vOHVZnvXwe6EXRsy29jdkUzBE6ElNpXUwd+m8vV7qy32AnXu7B9YemHsZ44vWviIwPZeXF6Nhd9EFLM0wWohw==", "darwin-x64": "sha512-6SivWKzu15aUMMohe0wg7sNYMPETVnOe40BuWsnKOgzl3o5FpQqNSgs+68Mi8Za3Qti9/DaR+H/fyD0x48Af2w==",
"linux-arm64v8": "sha512-XwZdS63yhqLtbFtx/0eoLF/Agf5qtTrI11FMnMRpuBJWd4jHB60RAH+uzYUgoChCmKIS+AeXYMLm4d8Ns2QX8w==", "linux-arm64v8": "sha512-b+iI9V/ehgDabXYRQcvqa5CEysh+1FQsgFmYc358StCrJCDahwNmsQdsiH1GOVd5WaWh5wHUGByPwMmFOO16Aw==",
"linux-armv6": "sha512-Rh0Q0kqwPG2MjXWOkPCuPEyiUKFgKJYWLgS835D4MrXgdKr8Tft/eVrc2iGIxt2re30VpDiZ1h0Rby1aCZt2zw==", "linux-armv6": "sha512-zRP2F+EiustLE4bXSH8AHCxwfemh9d+QuvmPjira/HL6uJOUuA7SyQgVV1TPwTQle2ioCNnKPm7FEB/MAiT+ug==",
"linux-armv7": "sha512-heTS/MsmRvu4JljINxP+vDiS9ZZfuGhr3IStb5F7Gc0/QLRhllYAg4rcO8L1eTK9sIIzG5ARvI19+YUZe7WbzA==", "linux-armv7": "sha512-6OCChowE5lBXXXAZrnGdA9dVktg7UdODEBpE5qTroiAJYZv4yXRMgyDFYajok7du2NTgoklhxGk8d9+4vGv5hg==",
"linux-x64": "sha512-SSWAwBFi0hx8V/h/v82tTFGKWTFv9FiCK3Timz5OExuI+sX1Ngrd0PVQaWXOThGNdel/fcD3Bz9YjSt4feBR1g==", "linux-x64": "sha512-OTmlmP2r8ozGKdB96X+K5oQE1ojVZanqLqqKlwDpEnfixyIaDGYbVzcjWBNGU3ai/26bvkaCkjynnc2ecYcsuA==",
"linuxmusl-arm64v8": "sha512-Rhks+5C7p7aO6AucLT1uvzo8ohlqcqCUPgZmN+LZjsPWob/Iix3MfiDYtv/+gTvdeEfXxbCU6/YuPBwHQ7/crA==", "linuxmusl-arm64v8": "sha512-Qh5Wi+bkKTohFYHzSPssfjMhIkD6z6EHbVmnwmWSsgY9zsUBStFp6+mKcNTQfP5YM5Mz06vJOkLHX2OzEr5TzA==",
"linuxmusl-x64": "sha512-IOyjSQqpWVntqOUpCHVWuQwACwmmjdi15H8Pc+Ma1JkhPogTfVsFQWyL7DuOTD3Yr23EuYGzovUX00duOtfy/g==", "linuxmusl-x64": "sha512-DwB4Fs3+ISw9etaLCANkueZDdk758iOS+wNp4TKZkHdq0al6B/3Pk7OHLR8a9E3H6wYDD328u++dcJzip5tacA==",
"win32-arm64v8": "sha512-A+Qe8Ipewtvw9ldvF6nWed2J8kphzrUE04nFeKCtNx6pfGQ/MAlCKMjt/U8VgUKNjB01zJDUW9XE0+FhGZ/UpQ==", "win32-arm64v8": "sha512-96r3W+O4BtX602B1MtxU5Ru4lKzRRTZqM4OQEBJ//TNL3fiCZdd9agD+RQBjaeR4KFIyBSt3F7IE425ZWmxz+w==",
"win32-ia32": "sha512-cMrAvwFdDeAVnLJt0IPMPRKaIFhyXYGTprsM0DND9VUHE8F7dJMR44tS5YkXsGh1QNDtjKT6YuxAVUglmiXtpA==", "win32-ia32": "sha512-qfN1MsfQGek1QQd1UNW7JT+5K5Ne1suFQ2GpgpYm3JLSpIve/tz2vOGEGzvTVssOBADJvAkTDFt+yIi3PgU9pA==",
"win32-x64": "sha512-vLFIfw6aW2zABa8jpgzWDhljnE6glktrddErVyazAIoHl6BFFe/Da+LK1DbXvIYHz7fyOoKhSfCJHCiJG1Vg6w==" "win32-x64": "sha512-eb3aAmjbVVBVRbiYgebQwoxkAt69WI8nwmKlilSQ3kWqoc0pXfIe322rF2UR8ebbISCGvYRUfzD2r1k92RXISQ=="
}, },
"runtime": "napi", "runtime": "napi",
"target": 5 "target": 7
}, },
"engines": { "engines": {
"node": ">=12.13.0" "node": ">=14.15.0"
}, },
"funding": { "funding": {
"url": "https://opencollective.com/libvips" "url": "https://opencollective.com/libvips"
}, },
"binary": { "binary": {
"napi_versions": [ "napi_versions": [
5 7
] ]
}, },
"semistandard": { "semistandard": {

View File

@@ -48,6 +48,9 @@ namespace sharp {
int32_t AttrAsInt32(Napi::Object obj, unsigned int const attr) { int32_t AttrAsInt32(Napi::Object obj, unsigned int const attr) {
return obj.Get(attr).As<Napi::Number>().Int32Value(); return obj.Get(attr).As<Napi::Number>().Int32Value();
} }
int64_t AttrAsInt64(Napi::Object obj, std::string attr) {
return obj.Get(attr).As<Napi::Number>().Int64Value();
}
double AttrAsDouble(Napi::Object obj, std::string attr) { double AttrAsDouble(Napi::Object obj, std::string attr) {
return obj.Get(attr).As<Napi::Number>().DoubleValue(); return obj.Get(attr).As<Napi::Number>().DoubleValue();
} }
@@ -73,6 +76,14 @@ namespace sharp {
} }
return vector; return vector;
} }
Napi::Buffer<char> NewOrCopyBuffer(Napi::Env env, char* data, size_t len) {
try {
return Napi::Buffer<char>::New(env, data, len, FreeCallback);
} catch (Napi::Error const &err) {}
Napi::Buffer<char> buf = Napi::Buffer<char>::Copy(env, data, len);
FreeCallback(nullptr, data);
return buf;
}
// Create an InputDescriptor instance from a Napi::Object describing an input image // Create an InputDescriptor instance from a Napi::Object describing an input image
InputDescriptor* CreateInputDescriptor(Napi::Object input) { InputDescriptor* CreateInputDescriptor(Napi::Object input) {
@@ -85,16 +96,14 @@ namespace sharp {
descriptor->buffer = buffer.Data(); descriptor->buffer = buffer.Data();
descriptor->isBuffer = TRUE; descriptor->isBuffer = TRUE;
} }
descriptor->failOnError = AttrAsBool(input, "failOnError"); descriptor->failOn = AttrAsEnum<VipsFailOn>(input, "failOn", VIPS_TYPE_FAIL_ON);
// Density for vector-based input // Density for vector-based input
if (HasAttr(input, "density")) { if (HasAttr(input, "density")) {
descriptor->density = AttrAsDouble(input, "density"); descriptor->density = AttrAsDouble(input, "density");
} }
// Raw pixel input // Raw pixel input
if (HasAttr(input, "rawChannels")) { if (HasAttr(input, "rawChannels")) {
descriptor->rawDepth = static_cast<VipsBandFormat>( descriptor->rawDepth = AttrAsEnum<VipsBandFormat>(input, "rawDepth", VIPS_TYPE_BAND_FORMAT);
vips_enum_from_nick(nullptr, VIPS_TYPE_BAND_FORMAT,
AttrAsStr(input, "rawDepth").data()));
descriptor->rawChannels = AttrAsUint32(input, "rawChannels"); descriptor->rawChannels = AttrAsUint32(input, "rawChannels");
descriptor->rawWidth = AttrAsUint32(input, "rawWidth"); descriptor->rawWidth = AttrAsUint32(input, "rawWidth");
descriptor->rawHeight = AttrAsUint32(input, "rawHeight"); descriptor->rawHeight = AttrAsUint32(input, "rawHeight");
@@ -128,11 +137,42 @@ namespace sharp {
descriptor->createBackground = AttrAsVectorOfDouble(input, "createBackground"); descriptor->createBackground = AttrAsVectorOfDouble(input, "createBackground");
} }
} }
// Create new image with text
if (HasAttr(input, "textValue")) {
descriptor->textValue = AttrAsStr(input, "textValue");
if (HasAttr(input, "textFont")) {
descriptor->textFont = AttrAsStr(input, "textFont");
}
if (HasAttr(input, "textFontfile")) {
descriptor->textFontfile = AttrAsStr(input, "textFontfile");
}
if (HasAttr(input, "textWidth")) {
descriptor->textWidth = AttrAsUint32(input, "textWidth");
}
if (HasAttr(input, "textHeight")) {
descriptor->textHeight = AttrAsUint32(input, "textHeight");
}
if (HasAttr(input, "textAlign")) {
descriptor->textAlign = AttrAsEnum<VipsAlign>(input, "textAlign", VIPS_TYPE_ALIGN);
}
if (HasAttr(input, "textJustify")) {
descriptor->textJustify = AttrAsBool(input, "textJustify");
}
if (HasAttr(input, "textDpi")) {
descriptor->textDpi = AttrAsUint32(input, "textDpi");
}
if (HasAttr(input, "textRgba")) {
descriptor->textRgba = AttrAsBool(input, "textRgba");
}
if (HasAttr(input, "textSpacing")) {
descriptor->textSpacing = AttrAsUint32(input, "textSpacing");
}
}
// 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 = AttrAsUint32(input, "limitInputPixels"); descriptor->limitInputPixels = static_cast<uint64_t>(AttrAsInt64(input, "limitInputPixels"));
// Allow switch from random to sequential access // Allow switch from random to sequential 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 SVG/PNG input // Remove safety features and allow unlimited input
descriptor->unlimited = AttrAsBool(input, "unlimited"); descriptor->unlimited = AttrAsBool(input, "unlimited");
return descriptor; return descriptor;
} }
@@ -175,6 +215,9 @@ namespace sharp {
bool IsAvif(std::string const &str) { bool IsAvif(std::string const &str) {
return EndsWith(str, ".avif") || EndsWith(str, ".AVIF"); return EndsWith(str, ".avif") || EndsWith(str, ".AVIF");
} }
bool IsJxl(std::string const &str) {
return EndsWith(str, ".jxl") || EndsWith(str, ".JXL");
}
bool IsDz(std::string const &str) { bool IsDz(std::string const &str) {
return EndsWith(str, ".dzi") || EndsWith(str, ".DZI"); return EndsWith(str, ".dzi") || EndsWith(str, ".DZI");
} }
@@ -205,6 +248,7 @@ namespace sharp {
case ImageType::PPM: id = "ppm"; break; case ImageType::PPM: id = "ppm"; break;
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::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;
@@ -245,10 +289,12 @@ namespace sharp {
{ "VipsForeignLoadMagickBuffer", ImageType::MAGICK }, { "VipsForeignLoadMagickBuffer", ImageType::MAGICK },
{ "VipsForeignLoadMagick7File", ImageType::MAGICK }, { "VipsForeignLoadMagick7File", ImageType::MAGICK },
{ "VipsForeignLoadMagick7Buffer", ImageType::MAGICK }, { "VipsForeignLoadMagick7Buffer", ImageType::MAGICK },
{ "VipsForeignLoadOpenslide", ImageType::OPENSLIDE }, { "VipsForeignLoadOpenslideFile", ImageType::OPENSLIDE },
{ "VipsForeignLoadPpmFile", ImageType::PPM }, { "VipsForeignLoadPpmFile", ImageType::PPM },
{ "VipsForeignLoadFits", ImageType::FITS }, { "VipsForeignLoadFitsFile", ImageType::FITS },
{ "VipsForeignLoadOpenexr", ImageType::EXR }, { "VipsForeignLoadOpenexr", ImageType::EXR },
{ "VipsForeignLoadJxlFile", ImageType::JXL },
{ "VipsForeignLoadJxlBuffer", ImageType::JXL },
{ "VipsForeignLoadVips", ImageType::VIPS }, { "VipsForeignLoadVips", ImageType::VIPS },
{ "VipsForeignLoadVipsFile", ImageType::VIPS }, { "VipsForeignLoadVipsFile", ImageType::VIPS },
{ "VipsForeignLoadRaw", ImageType::RAW } { "VipsForeignLoadRaw", ImageType::RAW }
@@ -302,6 +348,17 @@ namespace sharp {
imageType == ImageType::PDF; imageType == ImageType::PDF;
} }
/*
Does this image type support removal of safety limits?
*/
bool ImageTypeSupportsUnlimited(ImageType imageType) {
return
imageType == ImageType::JPEG ||
imageType == ImageType::PNG ||
imageType == ImageType::SVG ||
imageType == ImageType::HEIF;
}
/* /*
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)
*/ */
@@ -329,8 +386,8 @@ namespace sharp {
try { try {
vips::VOption *option = VImage::option() vips::VOption *option = VImage::option()
->set("access", descriptor->access) ->set("access", descriptor->access)
->set("fail", descriptor->failOnError); ->set("fail_on", descriptor->failOn);
if (descriptor->unlimited && (imageType == ImageType::SVG || imageType == ImageType::PNG)) { if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {
option->set("unlimited", TRUE); option->set("unlimited", TRUE);
} }
if (imageType == ImageType::SVG || imageType == ImageType::PDF) { if (imageType == ImageType::SVG || imageType == ImageType::PDF) {
@@ -361,51 +418,79 @@ namespace sharp {
} }
} }
} else { } else {
if (descriptor->createChannels > 0) { int const channels = descriptor->createChannels;
if (channels > 0) {
// Create new image // Create new image
if (descriptor->createNoiseType == "gaussian") { if (descriptor->createNoiseType == "gaussian") {
int const channels = descriptor->createChannels;
image = VImage::new_matrix(descriptor->createWidth, descriptor->createHeight);
std::vector<VImage> bands = {}; std::vector<VImage> bands = {};
bands.reserve(channels); bands.reserve(channels);
for (int _band = 0; _band < channels; _band++) { for (int _band = 0; _band < channels; _band++) {
bands.push_back(image.gaussnoise( bands.push_back(VImage::gaussnoise(descriptor->createWidth, descriptor->createHeight, VImage::option()
descriptor->createWidth, ->set("mean", descriptor->createNoiseMean)
descriptor->createHeight, ->set("sigma", descriptor->createNoiseSigma)));
VImage::option()->set("mean", descriptor->createNoiseMean)->set("sigma", descriptor->createNoiseSigma)));
}
image = image.bandjoin(bands);
image = image.cast(VipsBandFormat::VIPS_FORMAT_UCHAR);
if (channels < 3) {
image = image.colourspace(VIPS_INTERPRETATION_B_W);
} else {
image = image.colourspace(VIPS_INTERPRETATION_sRGB);
} }
image = VImage::bandjoin(bands).copy(VImage::option()->set("interpretation",
channels < 3 ? VIPS_INTERPRETATION_B_W: VIPS_INTERPRETATION_sRGB));
} else { } else {
std::vector<double> background = { std::vector<double> background = {
descriptor->createBackground[0], descriptor->createBackground[0],
descriptor->createBackground[1], descriptor->createBackground[1],
descriptor->createBackground[2] descriptor->createBackground[2]
}; };
if (descriptor->createChannels == 4) { if (channels == 4) {
background.push_back(descriptor->createBackground[3]); background.push_back(descriptor->createBackground[3]);
} }
image = VImage::new_matrix(descriptor->createWidth, descriptor->createHeight).new_from_image(background); image = VImage::new_matrix(descriptor->createWidth, descriptor->createHeight)
.copy(VImage::option()->set("interpretation",
channels < 3 ? VIPS_INTERPRETATION_B_W : VIPS_INTERPRETATION_sRGB))
.new_from_image(background);
}
image = image.cast(VIPS_FORMAT_UCHAR);
imageType = ImageType::RAW;
} else if (descriptor->textValue.length() > 0) {
// Create a new image with text
vips::VOption *textOptions = VImage::option()
->set("align", descriptor->textAlign)
->set("justify", descriptor->textJustify)
->set("rgba", descriptor->textRgba)
->set("spacing", descriptor->textSpacing)
->set("autofit_dpi", &descriptor->textAutofitDpi);
if (descriptor->textWidth > 0) {
textOptions->set("width", descriptor->textWidth);
}
// Ignore dpi if height is set
if (descriptor->textWidth > 0 && descriptor->textHeight > 0) {
textOptions->set("height", descriptor->textHeight);
} else if (descriptor->textDpi > 0) {
textOptions->set("dpi", descriptor->textDpi);
}
if (descriptor->textFont.length() > 0) {
textOptions->set("font", const_cast<char*>(descriptor->textFont.data()));
}
if (descriptor->textFontfile.length() > 0) {
textOptions->set("fontfile", const_cast<char*>(descriptor->textFontfile.data()));
}
image = VImage::text(const_cast<char *>(descriptor->textValue.data()), textOptions);
if (!descriptor->textRgba) {
image = image.copy(VImage::option()->set("interpretation", VIPS_INTERPRETATION_B_W));
} }
image.get_image()->Type = VIPS_INTERPRETATION_sRGB;
imageType = ImageType::RAW; imageType = ImageType::RAW;
} else { } else {
// From filesystem // From filesystem
imageType = DetermineImageType(descriptor->file.data()); imageType = DetermineImageType(descriptor->file.data());
if (imageType == ImageType::MISSING) { if (imageType == ImageType::MISSING) {
throw vips::VError("Input file is missing"); if (descriptor->file.find("<svg") != std::string::npos) {
throw vips::VError("Input file is missing, did you mean "
"sharp(Buffer.from('" + descriptor->file.substr(0, 8) + "...')?");
}
throw vips::VError("Input file is missing: " + descriptor->file);
} }
if (imageType != ImageType::UNKNOWN) { if (imageType != ImageType::UNKNOWN) {
try { try {
vips::VOption *option = VImage::option() vips::VOption *option = VImage::option()
->set("access", descriptor->access) ->set("access", descriptor->access)
->set("fail", descriptor->failOnError); ->set("fail_on", descriptor->failOn);
if (descriptor->unlimited && (imageType == ImageType::SVG || imageType == ImageType::PNG)) { if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {
option->set("unlimited", TRUE); option->set("unlimited", TRUE);
} }
if (imageType == ImageType::SVG || imageType == ImageType::PDF) { if (imageType == ImageType::SVG || imageType == ImageType::PDF) {
@@ -436,9 +521,10 @@ namespace sharp {
} }
} }
} }
// 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
if (descriptor->limitInputPixels > 0 && if (descriptor->limitInputPixels > 0 &&
static_cast<uint64_t>(image.width() * image.height()) > static_cast<uint64_t>(descriptor->limitInputPixels)) { static_cast<uint64_t>(image.width()) * image.height() > descriptor->limitInputPixels) {
throw vips::VError("Input image exceeds pixel limit"); throw vips::VError("Input image exceeds pixel limit");
} }
return std::make_tuple(image, imageType); return std::make_tuple(image, imageType);
@@ -485,6 +571,7 @@ namespace sharp {
VImage RemoveExifOrientation(VImage image) { VImage RemoveExifOrientation(VImage image) {
VImage copy = image.copy(); VImage copy = image.copy();
copy.remove(VIPS_META_ORIENTATION); copy.remove(VIPS_META_ORIENTATION);
copy.remove("exif-ifd0-Orientation");
return copy; return copy;
} }
@@ -633,7 +720,6 @@ namespace sharp {
Event listener for progress updates, used to detect timeout Event listener for progress updates, used to detect timeout
*/ */
void VipsProgressCallBack(VipsImage *im, VipsProgress *progress, int *timeout) { void VipsProgressCallBack(VipsImage *im, VipsProgress *progress, int *timeout) {
// printf("VipsProgressCallBack progress=%d run=%d timeout=%d\n", progress->percent, progress->run, *timeout);
if (*timeout > 0 && progress->run >= *timeout) { if (*timeout > 0 && progress->run >= *timeout) {
vips_image_set_kill(im, TRUE); vips_image_set_kill(im, TRUE);
vips_error("timeout", "%d%% complete", progress->percent); vips_error("timeout", "%d%% complete", progress->percent);
@@ -790,22 +876,6 @@ namespace sharp {
return Is16Bit(interpretation) ? 65535.0 : 255.0; return Is16Bit(interpretation) ? 65535.0 : 255.0;
} }
/*
Get boolean operation type from string
*/
VipsOperationBoolean GetBooleanOperation(std::string const opStr) {
return static_cast<VipsOperationBoolean>(
vips_enum_from_nick(nullptr, VIPS_TYPE_OPERATION_BOOLEAN, opStr.data()));
}
/*
Get interpretation type from string
*/
VipsInterpretation GetInterpretation(std::string const typeStr) {
return static_cast<VipsInterpretation>(
vips_enum_from_nick(nullptr, VIPS_TYPE_INTERPRETATION, typeStr.data()));
}
/* /*
Convert RGBA value to another colourspace Convert RGBA value to another colourspace
*/ */
@@ -857,7 +927,7 @@ namespace sharp {
// 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 && !HasAlpha(image)) {
image = image.bandjoin( image = image.bandjoin(
VImage::new_matrix(image.width(), image.height()).new_from_image(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);
} }
@@ -885,8 +955,8 @@ namespace sharp {
} }
std::pair<double, double> ResolveShrink(int width, int height, int targetWidth, int targetHeight, std::pair<double, double> ResolveShrink(int width, int height, int targetWidth, int targetHeight,
Canvas canvas, bool swap, bool withoutEnlargement) { Canvas canvas, bool swap, bool withoutEnlargement, bool withoutReduction) {
if (swap) { if (swap && canvas != Canvas::IGNORE_ASPECT) {
// Swap input width and height when requested. // Swap input width and height when requested.
std::swap(width, height); std::swap(width, height);
} }
@@ -917,9 +987,6 @@ namespace sharp {
} }
break; break;
case Canvas::IGNORE_ASPECT: case Canvas::IGNORE_ASPECT:
if (swap) {
std::swap(hshrink, vshrink);
}
break; break;
} }
} else if (targetWidth > 0) { } else if (targetWidth > 0) {
@@ -940,9 +1007,14 @@ namespace sharp {
} }
} }
// We should not enlarge (oversample) the output image, // We should not reduce or enlarge the output image, if
// if withoutEnlargement is specified. // withoutReduction or withoutEnlargement is specified.
if (withoutEnlargement) { if (withoutReduction) {
// Equivalent of VIPS_SIZE_UP
hshrink = std::min(1.0, hshrink);
vshrink = std::min(1.0, vshrink);
} else if (withoutEnlargement) {
// Equivalent of VIPS_SIZE_DOWN
hshrink = std::max(1.0, hshrink); hshrink = std::max(1.0, hshrink);
vshrink = std::max(1.0, vshrink); vshrink = std::max(1.0, vshrink);
} }

View File

@@ -25,9 +25,9 @@
// 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 < 12) || \ (VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION < 13) || \
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION == 12 && VIPS_MICRO_VERSION < 2) (VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION == 13 && VIPS_MICRO_VERSION < 3)
#error "libvips version 8.12.2+ is required - please see https://sharp.pixelplumbing.com/install" #error "libvips version 8.13.3+ 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(__clang__)) && defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 6)))
@@ -48,8 +48,8 @@ namespace sharp {
std::string name; std::string name;
std::string file; std::string file;
char *buffer; char *buffer;
bool failOnError; VipsFailOn failOn;
int limitInputPixels; uint64_t limitInputPixels;
bool unlimited; bool unlimited;
VipsAccess access; VipsAccess access;
size_t bufferLength; size_t bufferLength;
@@ -71,10 +71,21 @@ namespace sharp {
std::string createNoiseType; std::string createNoiseType;
double createNoiseMean; double createNoiseMean;
double createNoiseSigma; double createNoiseSigma;
std::string textValue;
std::string textFont;
std::string textFontfile;
int textWidth;
int textHeight;
VipsAlign textAlign;
bool textJustify;
int textDpi;
bool textRgba;
int textSpacing;
int textAutofitDpi;
InputDescriptor(): InputDescriptor():
buffer(nullptr), buffer(nullptr),
failOnError(TRUE), failOn(VIPS_FAIL_ON_WARNING),
limitInputPixels(0x3FFF * 0x3FFF), limitInputPixels(0x3FFF * 0x3FFF),
unlimited(FALSE), unlimited(FALSE),
access(VIPS_ACCESS_RANDOM), access(VIPS_ACCESS_RANDOM),
@@ -95,7 +106,15 @@ namespace sharp {
createHeight(0), createHeight(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),
textWidth(0),
textHeight(0),
textAlign(VIPS_ALIGN_LOW),
textJustify(FALSE),
textDpi(72),
textRgba(FALSE),
textSpacing(0),
textAutofitDpi(0) {}
}; };
// Convenience methods to access the attributes of a Napi::Object // Convenience methods to access the attributes of a Napi::Object
@@ -110,6 +129,11 @@ namespace sharp {
bool AttrAsBool(Napi::Object obj, std::string attr); bool AttrAsBool(Napi::Object obj, std::string attr);
std::vector<double> AttrAsVectorOfDouble(Napi::Object obj, std::string attr); std::vector<double> AttrAsVectorOfDouble(Napi::Object obj, std::string attr);
std::vector<int32_t> AttrAsInt32Vector(Napi::Object obj, std::string attr); std::vector<int32_t> AttrAsInt32Vector(Napi::Object obj, std::string attr);
template <class T> T AttrAsEnum(Napi::Object obj, std::string attr, GType type) {
return static_cast<T>(
vips_enum_from_nick(nullptr, type, AttrAsStr(obj, attr).data()));
}
Napi::Buffer<char> NewOrCopyBuffer(Napi::Env env, char* data, size_t len);
// Create an InputDescriptor instance from a Napi::Object describing an input image // Create an InputDescriptor instance from a Napi::Object describing an input image
InputDescriptor* CreateInputDescriptor(Napi::Object input); InputDescriptor* CreateInputDescriptor(Napi::Object input);
@@ -129,6 +153,7 @@ namespace sharp {
PPM, PPM,
FITS, FITS,
EXR, EXR,
JXL,
VIPS, VIPS,
RAW, RAW,
UNKNOWN, UNKNOWN,
@@ -159,6 +184,7 @@ namespace sharp {
bool IsHeic(std::string const &str); bool IsHeic(std::string const &str);
bool IsHeif(std::string const &str); bool IsHeif(std::string const &str);
bool IsAvif(std::string const &str); bool IsAvif(std::string const &str);
bool IsJxl(std::string const &str);
bool IsDz(std::string const &str); bool IsDz(std::string const &str);
bool IsDzZip(std::string const &str); bool IsDzZip(std::string const &str);
bool IsV(std::string const &str); bool IsV(std::string const &str);
@@ -183,6 +209,11 @@ namespace sharp {
*/ */
bool ImageTypeSupportsPage(ImageType imageType); bool ImageTypeSupportsPage(ImageType imageType);
/*
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)
*/ */
@@ -307,16 +338,6 @@ namespace sharp {
*/ */
double MaximumImageAlpha(VipsInterpretation const interpretation); double MaximumImageAlpha(VipsInterpretation const interpretation);
/*
Get boolean operation type from string
*/
VipsOperationBoolean GetBooleanOperation(std::string const opStr);
/*
Get interpretation type from string
*/
VipsInterpretation GetInterpretation(std::string const typeStr);
/* /*
Convert RGBA value to another colourspace Convert RGBA value to another colourspace
*/ */
@@ -345,7 +366,7 @@ namespace sharp {
the required thumbnail width/height and canvas mode. the required thumbnail width/height and canvas mode.
*/ */
std::pair<double, double> ResolveShrink(int width, int height, int targetWidth, int targetHeight, std::pair<double, double> ResolveShrink(int width, int height, int targetWidth, int targetHeight,
Canvas canvas, bool swap, bool withoutEnlargement); Canvas canvas, bool swap, bool withoutEnlargement, bool withoutReduction);
} // namespace sharp } // namespace sharp

View File

@@ -31,7 +31,6 @@
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include <config.h> #include <config.h>
#endif /*HAVE_CONFIG_H*/ #endif /*HAVE_CONFIG_H*/
#include <vips/intl.h>
#include <vips/vips8> #include <vips/vips8>

View File

@@ -30,7 +30,6 @@
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include <config.h> #include <config.h>
#endif /*HAVE_CONFIG_H*/ #endif /*HAVE_CONFIG_H*/
#include <vips/intl.h>
#include <vips/vips8> #include <vips/vips8>

View File

@@ -38,7 +38,6 @@
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include <config.h> #include <config.h>
#endif /*HAVE_CONFIG_H*/ #endif /*HAVE_CONFIG_H*/
#include <vips/intl.h>
#include <vips/vips8> #include <vips/vips8>
@@ -733,7 +732,7 @@ VImage::write_to_buffer( const char *suffix, void **buf, size_t *size,
set( "in", *this )-> set( "in", *this )->
set( "target", target ) ); set( "target", target ) );
g_object_get( target.get_target(), "blob", &blob, NULL ); g_object_get( target.get_target(), "blob", &blob, (void *) NULL );
} }
else if( (operation_name = vips_foreign_find_save_buffer( filename )) ) { else if( (operation_name = vips_foreign_find_save_buffer( filename )) ) {
call_option_string( operation_name, option_string, call_option_string( operation_name, option_string,
@@ -778,6 +777,32 @@ VImage::write_to_target( const char *suffix, VTarget target,
set( "target", target ) ); set( "target", target ) );
} }
VRegion
VImage::region() const
{
return VRegion::new_from_image( *this );
}
VRegion
VImage::region( VipsRect *rect ) const
{
VRegion region = VRegion::new_from_image( *this );
region.prepare( rect );
return region;
}
VRegion
VImage::region( int left, int top, int width, int height ) const
{
VRegion region = VRegion::new_from_image( *this );
region.prepare( left, top, width, height );
return region;
}
#include "vips-operators.cpp" #include "vips-operators.cpp"
std::vector<VImage> std::vector<VImage>

View File

@@ -31,7 +31,6 @@
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include <config.h> #include <config.h>
#endif /*HAVE_CONFIG_H*/ #endif /*HAVE_CONFIG_H*/
#include <vips/intl.h>
#include <vips/vips8> #include <vips/vips8>

View File

@@ -0,0 +1,27 @@
// Object part of VRegion class
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /*HAVE_CONFIG_H*/
#include <vips/vips8>
#include <vips/debug.h>
VIPS_NAMESPACE_START
VRegion
VRegion::new_from_image( VImage image )
{
VipsRegion *region;
if( !(region = vips_region_new( image.get_image() )) ) {
throw VError();
}
VRegion out( region );
return( out );
}
VIPS_NAMESPACE_END

View File

@@ -1,5 +1,4 @@
// bodies for vips operations // bodies for vips operations
// Mon Nov 1 03:31:09 PM CET 2021
// this file is generated automatically, do not edit! // this file is generated automatically, do not edit!
VImage VImage::CMC2LCh( VOption *options ) const VImage VImage::CMC2LCh( VOption *options ) const
@@ -943,6 +942,14 @@ VipsBlob *VImage::dzsave_buffer( VOption *options ) const
return( buffer ); return( buffer );
} }
void VImage::dzsave_target( VTarget target, VOption *options ) const
{
call( "dzsave_target",
(options ? options : VImage::option())->
set( "in", *this )->
set( "target", target ) );
}
VImage VImage::embed( int x, int y, int width, int height, VOption *options ) const VImage VImage::embed( int x, int y, int width, int height, VOption *options ) const
{ {
VImage out; VImage out;
@@ -3521,6 +3528,14 @@ VipsBlob *VImage::tiffsave_buffer( VOption *options ) const
return( buffer ); return( buffer );
} }
void VImage::tiffsave_target( VTarget target, VOption *options ) const
{
call( "tiffsave_target",
(options ? options : VImage::option())->
set( "in", *this )->
set( "target", target ) );
}
VImage VImage::tilecache( VOption *options ) const VImage VImage::tilecache( VOption *options ) const
{ {
VImage out; VImage out;

View File

@@ -235,20 +235,20 @@ class MetadataWorker : public Napi::AsyncWorker {
info.Set("orientation", baton->orientation); info.Set("orientation", baton->orientation);
} }
if (baton->exifLength > 0) { if (baton->exifLength > 0) {
info.Set("exif", Napi::Buffer<char>::New(env, baton->exif, baton->exifLength, sharp::FreeCallback)); info.Set("exif", sharp::NewOrCopyBuffer(env, baton->exif, baton->exifLength));
} }
if (baton->iccLength > 0) { if (baton->iccLength > 0) {
info.Set("icc", Napi::Buffer<char>::New(env, baton->icc, baton->iccLength, sharp::FreeCallback)); info.Set("icc", sharp::NewOrCopyBuffer(env, baton->icc, baton->iccLength));
} }
if (baton->iptcLength > 0) { if (baton->iptcLength > 0) {
info.Set("iptc", Napi::Buffer<char>::New(env, baton->iptc, baton->iptcLength, sharp::FreeCallback)); info.Set("iptc", sharp::NewOrCopyBuffer(env, baton->iptc, baton->iptcLength));
} }
if (baton->xmpLength > 0) { if (baton->xmpLength > 0) {
info.Set("xmp", Napi::Buffer<char>::New(env, baton->xmp, baton->xmpLength, sharp::FreeCallback)); info.Set("xmp", sharp::NewOrCopyBuffer(env, baton->xmp, baton->xmpLength));
} }
if (baton->tifftagPhotoshopLength > 0) { if (baton->tifftagPhotoshopLength > 0) {
info.Set("tifftagPhotoshop", info.Set("tifftagPhotoshop",
Napi::Buffer<char>::New(env, baton->tifftagPhotoshop, baton->tifftagPhotoshopLength, sharp::FreeCallback)); sharp::NewOrCopyBuffer(env, baton->tifftagPhotoshop, baton->tifftagPhotoshopLength));
} }
Callback().MakeCallback(Receiver().Value(), { env.Null(), info }); Callback().MakeCallback(Receiver().Value(), { env.Null(), info });
} else { } else {

View File

@@ -68,10 +68,9 @@ namespace sharp {
// Extract luminance // Extract luminance
VImage luminance = lab[0]; VImage luminance = lab[0];
// Find luminance range // Find luminance range
VImage stats = luminance.stats(); int const min = luminance.percent(1);
double min = stats(0, 0)[0]; int const max = luminance.percent(99);
double max = stats(1, 0)[0]; if (std::abs(max - min) > 1) {
if (min != max) {
// Extract chroma // Extract chroma
VImage chroma = lab.extract_band(1, VImage::option()->set("n", 2)); VImage chroma = lab.extract_band(1, VImage::option()->set("n", 2));
// Calculate multiplication factor and addition // Calculate multiplication factor and addition
@@ -112,6 +111,19 @@ namespace sharp {
} }
} }
/*
* Flatten image to remove alpha channel
*/
VImage Flatten(VImage image, std::vector<double> flattenBackground) {
double const multiplier = sharp::Is16Bit(image.interpretation()) ? 256.0 : 1.0;
std::vector<double> background {
flattenBackground[0] * multiplier,
flattenBackground[1] * multiplier,
flattenBackground[2] * multiplier
};
return image.flatten(VImage::option()->set("background", background));
}
/** /**
* Produce the "negative" of the image. * Produce the "negative" of the image.
*/ */
@@ -209,7 +221,8 @@ namespace sharp {
/* /*
* 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.
*/ */
VImage Sharpen(VImage image, double const sigma, double const flat, double const jagged) { VImage Sharpen(VImage image, double const sigma, double const m1, double const m2,
double const x1, double const y2, double const y3) {
if (sigma == -1.0) { if (sigma == -1.0) {
// Fast, mild sharpen // Fast, mild sharpen
VImage sharpen = VImage::new_matrixv(3, 3, VImage sharpen = VImage::new_matrixv(3, 3,
@@ -224,8 +237,14 @@ namespace sharp {
if (colourspaceBeforeSharpen == VIPS_INTERPRETATION_RGB) { if (colourspaceBeforeSharpen == VIPS_INTERPRETATION_RGB) {
colourspaceBeforeSharpen = VIPS_INTERPRETATION_sRGB; colourspaceBeforeSharpen = VIPS_INTERPRETATION_sRGB;
} }
return image.sharpen( return image
VImage::option()->set("sigma", sigma)->set("m1", flat)->set("m2", jagged)) .sharpen(VImage::option()
->set("sigma", sigma)
->set("m1", m1)
->set("m2", m2)
->set("x1", x1)
->set("y2", y2)
->set("y3", y3))
.colourspace(colourspaceBeforeSharpen); .colourspace(colourspaceBeforeSharpen);
} }
} }
@@ -255,45 +274,80 @@ namespace sharp {
/* /*
Trim an image Trim an image
*/ */
VImage Trim(VImage image, double const threshold) { VImage Trim(VImage image, std::vector<double> background, double threshold) {
if (image.width() < 3 && image.height() < 3) { if (image.width() < 3 && image.height() < 3) {
throw VError("Image to trim must be at least 3x3 pixels"); throw VError("Image to trim must be at least 3x3 pixels");
} }
// Top-left pixel provides the background colour
VImage background = image.extract_area(0, 0, 1, 1); // Scale up 8-bit values to match 16-bit input image
if (HasAlpha(background)) { double multiplier = sharp::Is16Bit(image.interpretation()) ? 256.0 : 1.0;
background = background.flatten(); threshold *= multiplier;
std::vector<double> backgroundAlpha(1);
if (background.size() == 0) {
// Top-left pixel provides the default background colour if none is given
background = image.extract_area(0, 0, 1, 1)(0, 0);
multiplier = 1.0;
}
if (HasAlpha(image) && background.size() == 4) {
// Just discard the alpha because flattening the background colour with
// itself (effectively what find_trim() does) gives the same result
backgroundAlpha[0] = background[3] * multiplier;
}
if (image.bands() > 2) {
background = {
background[0] * multiplier,
background[1] * multiplier,
background[2] * multiplier
};
} else {
background[0] = background[0] * multiplier;
} }
int left, top, width, height; int left, top, width, height;
left = image.find_trim(&top, &width, &height, VImage::option() left = image.find_trim(&top, &width, &height, VImage::option()
->set("background", background(0, 0)) ->set("background", background)
->set("threshold", threshold)); ->set("threshold", threshold));
if (width == 0 || height == 0) { if (HasAlpha(image)) {
if (HasAlpha(image)) { // Search alpha channel (A)
// Search alpha channel int leftA, topA, widthA, heightA;
VImage alpha = image[image.bands() - 1]; VImage alpha = image[image.bands() - 1];
VImage backgroundAlpha = alpha.extract_area(0, 0, 1, 1); leftA = alpha.find_trim(&topA, &widthA, &heightA, VImage::option()
left = alpha.find_trim(&top, &width, &height, VImage::option() ->set("background", backgroundAlpha)
->set("background", backgroundAlpha(0, 0)) ->set("threshold", threshold));
->set("threshold", threshold)); if (widthA > 0 && heightA > 0) {
} if (width > 0 && height > 0) {
if (width == 0 || height == 0) { // Combined bounding box (B)
throw VError("Unexpected error while trimming. Try to lower the tolerance"); int const leftB = std::min(left, leftA);
int const topB = std::min(top, topA);
int const widthB = std::max(left + width, leftA + widthA) - leftB;
int const heightB = std::max(top + height, topA + heightA) - topB;
return image.extract_area(leftB, topB, widthB, heightB);
} else {
// Use alpha only
return image.extract_area(leftA, topA, widthA, heightA);
}
} }
} }
return image.extract_area(left, top, width, height); if (width > 0 && height > 0) {
return image.extract_area(left, top, width, height);
}
return image;
} }
/* /*
* Calculate (a * in + b) * Calculate (a * in + b)
*/ */
VImage Linear(VImage image, double const a, double const b) { VImage Linear(VImage image, std::vector<double> const a, std::vector<double> const b) {
if (HasAlpha(image)) { size_t const bands = static_cast<size_t>(image.bands());
if (a.size() > bands) {
throw VError("Band expansion using linear is unsupported");
}
if (HasAlpha(image) && a.size() != bands && (a.size() == 1 || a.size() == bands - 1 || bands - 1 == 1)) {
// Separate alpha channel // Separate alpha channel
VImage alpha = image[image.bands() - 1]; VImage alpha = image[bands - 1];
return RemoveAlpha(image).linear(a, b).bandjoin(alpha); return RemoveAlpha(image).linear(a, b, VImage::option()->set("uchar", TRUE)).bandjoin(alpha);
} else { } else {
return image.linear(a, b); return image.linear(a, b, VImage::option()->set("uchar", TRUE));
} }
} }

View File

@@ -45,6 +45,11 @@ namespace sharp {
*/ */
VImage Gamma(VImage image, double const exponent); VImage Gamma(VImage image, double const exponent);
/*
* Flatten image to remove alpha channel
*/
VImage Flatten(VImage image, std::vector<double> flattenBackground);
/* /*
* Produce the "negative" of the image. * Produce the "negative" of the image.
*/ */
@@ -64,7 +69,8 @@ namespace sharp {
/* /*
* 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.
*/ */
VImage Sharpen(VImage image, double const sigma, double const flat, double const jagged); VImage Sharpen(VImage image, double const sigma, double const m1, double const m2,
double const x1, double const y2, double const y3);
/* /*
Threshold an image Threshold an image
@@ -84,12 +90,12 @@ namespace sharp {
/* /*
Trim an image Trim an image
*/ */
VImage Trim(VImage image, double const threshold); VImage Trim(VImage image, std::vector<double> background, double const threshold);
/* /*
* Linear adjustment (a * in + b) * Linear adjustment (a * in + b)
*/ */
VImage Linear(VImage image, double const a, double const b); VImage Linear(VImage image, std::vector<double> const a, std::vector<double> const b);
/* /*
* Recomb with a Matrix of the given bands/channel size. * Recomb with a Matrix of the given bands/channel size.

View File

@@ -81,29 +81,46 @@ class PipelineWorker : public Napi::AsyncWorker {
int pageHeight = sharp::GetPageHeight(image); int pageHeight = sharp::GetPageHeight(image);
// Calculate angle of rotation // Calculate angle of rotation
VipsAngle rotation; VipsAngle rotation = VIPS_ANGLE_D0;
bool flip = FALSE; VipsAngle autoRotation = VIPS_ANGLE_D0;
bool flop = FALSE; bool autoFlip = FALSE;
bool autoFlop = FALSE;
if (baton->useExifOrientation) { if (baton->useExifOrientation) {
// Rotate and flip image according to Exif orientation // Rotate and flip image according to Exif orientation
std::tie(rotation, flip, flop) = CalculateExifRotationAndFlip(sharp::ExifOrientation(image)); std::tie(autoRotation, autoFlip, autoFlop) = CalculateExifRotationAndFlip(sharp::ExifOrientation(image));
image = sharp::RemoveExifOrientation(image);
} else { } else {
rotation = CalculateAngleRotation(baton->angle); rotation = CalculateAngleRotation(baton->angle);
} }
// Rotate pre-extract // Rotate pre-extract
if (baton->rotateBeforePreExtract) { bool const shouldRotateBefore = baton->rotateBeforePreExtract &&
(rotation != VIPS_ANGLE_D0 || autoRotation != VIPS_ANGLE_D0 ||
autoFlip || baton->flip || autoFlop || baton->flop ||
baton->rotationAngle != 0.0);
if (shouldRotateBefore) {
if (autoRotation != VIPS_ANGLE_D0) {
image = image.rot(autoRotation);
autoRotation = VIPS_ANGLE_D0;
}
if (autoFlip) {
image = image.flip(VIPS_DIRECTION_VERTICAL);
autoFlip = FALSE;
} else if (baton->flip) {
image = image.flip(VIPS_DIRECTION_VERTICAL);
baton->flip = FALSE;
}
if (autoFlop) {
image = image.flip(VIPS_DIRECTION_HORIZONTAL);
autoFlop = FALSE;
} else if (baton->flop) {
image = image.flip(VIPS_DIRECTION_HORIZONTAL);
baton->flop = FALSE;
}
if (rotation != VIPS_ANGLE_D0) { if (rotation != VIPS_ANGLE_D0) {
image = image.rot(rotation); image = image.rot(rotation);
if (flip) { rotation = VIPS_ANGLE_D0;
image = image.flip(VIPS_DIRECTION_VERTICAL);
flip = FALSE;
}
if (flop) {
image = image.flip(VIPS_DIRECTION_HORIZONTAL);
flop = FALSE;
}
image = sharp::RemoveExifOrientation(image);
} }
if (baton->rotationAngle != 0.0) { if (baton->rotationAngle != 0.0) {
MultiPageUnsupported(nPages, "Rotate"); MultiPageUnsupported(nPages, "Rotate");
@@ -116,7 +133,7 @@ class PipelineWorker : public Napi::AsyncWorker {
// Trim // Trim
if (baton->trimThreshold > 0.0) { if (baton->trimThreshold > 0.0) {
MultiPageUnsupported(nPages, "Trim"); MultiPageUnsupported(nPages, "Trim");
image = sharp::Trim(image, baton->trimThreshold); image = sharp::Trim(image, baton->trimBackground, baton->trimThreshold);
baton->trimOffsetLeft = image.xoffset(); baton->trimOffsetLeft = image.xoffset();
baton->trimOffsetTop = image.yoffset(); baton->trimOffsetTop = image.yoffset();
} }
@@ -138,17 +155,6 @@ class PipelineWorker : public Napi::AsyncWorker {
pageHeight = inputHeight; pageHeight = inputHeight;
} }
// If withoutReduction is specified,
// Override target width and height if less than respective value from input file
if (baton->withoutReduction) {
if (baton->width < inputWidth) {
baton->width = inputWidth;
}
if (baton->height < inputHeight) {
baton->height = inputHeight;
}
}
// Scaling calculations // Scaling calculations
double hshrink; double hshrink;
double vshrink; double vshrink;
@@ -156,12 +162,14 @@ class PipelineWorker : public Napi::AsyncWorker {
int targetResizeHeight = baton->height; int targetResizeHeight = baton->height;
// Swap input output width and height when rotating by 90 or 270 degrees // Swap input output width and height when rotating by 90 or 270 degrees
bool swap = !baton->rotateBeforePreExtract && (rotation == VIPS_ANGLE_D90 || rotation == VIPS_ANGLE_D270); bool swap = !baton->rotateBeforePreExtract &&
(rotation == VIPS_ANGLE_D90 || rotation == VIPS_ANGLE_D270 ||
autoRotation == VIPS_ANGLE_D90 || autoRotation == VIPS_ANGLE_D270);
// Shrink to pageHeight, so we work for multi-page images // Shrink to pageHeight, so we work for multi-page images
std::tie(hshrink, vshrink) = sharp::ResolveShrink( std::tie(hshrink, vshrink) = sharp::ResolveShrink(
inputWidth, pageHeight, targetResizeWidth, targetResizeHeight, inputWidth, pageHeight, targetResizeWidth, targetResizeHeight,
baton->canvas, swap, baton->withoutEnlargement); baton->canvas, swap, baton->withoutEnlargement, baton->withoutReduction);
// The jpeg preload shrink. // The jpeg preload shrink.
int jpegShrinkOnLoad = 1; int jpegShrinkOnLoad = 1;
@@ -176,7 +184,7 @@ class PipelineWorker : public Napi::AsyncWorker {
// - input colourspace is not specified; // - input colourspace is not specified;
bool const shouldPreShrink = (targetResizeWidth > 0 || targetResizeHeight > 0) && bool const shouldPreShrink = (targetResizeWidth > 0 || targetResizeHeight > 0) &&
baton->gamma == 0 && baton->topOffsetPre == -1 && baton->trimThreshold == 0.0 && baton->gamma == 0 && baton->topOffsetPre == -1 && baton->trimThreshold == 0.0 &&
baton->colourspaceInput == VIPS_INTERPRETATION_LAST; baton->colourspaceInput == VIPS_INTERPRETATION_LAST && !shouldRotateBefore;
if (shouldPreShrink) { if (shouldPreShrink) {
// The common part of the shrink: the bit by which both axes must be shrunk // The common part of the shrink: the bit by which both axes must be shrunk
@@ -184,7 +192,7 @@ class PipelineWorker : public Napi::AsyncWorker {
if (inputImageType == sharp::ImageType::JPEG) { if (inputImageType == sharp::ImageType::JPEG) {
// Leave at least a factor of two for the final resize step, when fastShrinkOnLoad: false // Leave at least a factor of two for the final resize step, when fastShrinkOnLoad: false
// for more consistent results and avoid occasional small image shifting // for more consistent results and to avoid extra sharpness to the image
int factor = baton->fastShrinkOnLoad ? 1 : 2; int factor = baton->fastShrinkOnLoad ? 1 : 2;
if (shrink >= 8 * factor) { if (shrink >= 8 * factor) {
jpegShrinkOnLoad = 8; jpegShrinkOnLoad = 8;
@@ -193,8 +201,14 @@ class PipelineWorker : public Napi::AsyncWorker {
} else if (shrink >= 2 * factor) { } else if (shrink >= 2 * factor) {
jpegShrinkOnLoad = 2; jpegShrinkOnLoad = 2;
} }
} else if (inputImageType == sharp::ImageType::WEBP || // Lower shrink-on-load for known libjpeg rounding errors
inputImageType == sharp::ImageType::SVG || if (jpegShrinkOnLoad > 1 && static_cast<int>(shrink) == jpegShrinkOnLoad) {
jpegShrinkOnLoad /= 2;
}
} else if (inputImageType == sharp::ImageType::WEBP && shrink > 1.0) {
// Avoid upscaling via webp
scale = 1.0 / shrink;
} else if (inputImageType == sharp::ImageType::SVG ||
inputImageType == sharp::ImageType::PDF) { inputImageType == sharp::ImageType::PDF) {
scale = 1.0 / shrink; scale = 1.0 / shrink;
} }
@@ -207,7 +221,8 @@ class PipelineWorker : public Napi::AsyncWorker {
vips::VOption *option = VImage::option() vips::VOption *option = VImage::option()
->set("access", baton->input->access) ->set("access", baton->input->access)
->set("shrink", jpegShrinkOnLoad) ->set("shrink", jpegShrinkOnLoad)
->set("fail", baton->input->failOnError); ->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);
@@ -221,7 +236,7 @@ class PipelineWorker : public Napi::AsyncWorker {
vips::VOption *option = VImage::option() vips::VOption *option = VImage::option()
->set("access", baton->input->access) ->set("access", baton->input->access)
->set("scale", scale) ->set("scale", scale)
->set("fail", baton->input->failOnError); ->set("fail_on", baton->input->failOn);
if (inputImageType == sharp::ImageType::WEBP) { if (inputImageType == sharp::ImageType::WEBP) {
option->set("n", baton->input->pages); option->set("n", baton->input->pages);
option->set("page", baton->input->page); option->set("page", baton->input->page);
@@ -248,8 +263,10 @@ class PipelineWorker : public Napi::AsyncWorker {
// Reload SVG file // Reload SVG file
image = VImage::svgload(const_cast<char*>(baton->input->file.data()), option); image = VImage::svgload(const_cast<char*>(baton->input->file.data()), option);
} }
sharp::SetDensity(image, baton->input->density); sharp::SetDensity(image, baton->input->density);
if (image.width() > 32767 || image.height() > 32767) {
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("n", baton->input->pages);
option->set("page", baton->input->page); option->set("page", baton->input->page);
@@ -267,38 +284,35 @@ class PipelineWorker : public Napi::AsyncWorker {
sharp::SetDensity(image, baton->input->density); sharp::SetDensity(image, baton->input->density);
} }
} else {
if (inputImageType == sharp::ImageType::SVG && (image.width() > 32767 || image.height() > 32767)) {
throw vips::VError("Input SVG image exceeds 32767x32767 pixel limit");
}
} }
// Any pre-shrinking may already have been done // Any pre-shrinking may already have been done
int thumbWidth = image.width(); inputWidth = image.width();
int thumbHeight = image.height(); inputHeight = image.height();
// After pre-shrink, but before the main shrink stage // After pre-shrink, but before the main shrink stage
// Reuse the initial pageHeight if we didn't pre-shrink // Reuse the initial pageHeight if we didn't pre-shrink
int preshrunkPageHeight = shouldPreShrink ? sharp::GetPageHeight(image) : pageHeight; if (shouldPreShrink) {
pageHeight = sharp::GetPageHeight(image);
if (baton->fastShrinkOnLoad && jpegShrinkOnLoad > 1) {
// JPEG shrink-on-load rounds the output dimensions down, which
// may cause incorrect dimensions when fastShrinkOnLoad is enabled
// Just recalculate vshrink / hshrink on the main image instead of
// the pre-shrunk image when this is the case
hshrink = static_cast<double>(thumbWidth) / (static_cast<double>(inputWidth) / hshrink);
vshrink = static_cast<double>(preshrunkPageHeight) / (static_cast<double>(pageHeight) / vshrink);
} else {
// Shrink to preshrunkPageHeight, so we work for multi-page images
std::tie(hshrink, vshrink) = sharp::ResolveShrink(
thumbWidth, preshrunkPageHeight, targetResizeWidth, targetResizeHeight,
baton->canvas, swap, baton->withoutEnlargement);
} }
int targetHeight = static_cast<int>(std::rint(static_cast<double>(preshrunkPageHeight) / vshrink)); // Shrink to pageHeight, so we work for multi-page images
std::tie(hshrink, vshrink) = sharp::ResolveShrink(
inputWidth, pageHeight, targetResizeWidth, targetResizeHeight,
baton->canvas, swap, baton->withoutEnlargement, baton->withoutReduction);
int targetHeight = static_cast<int>(std::rint(static_cast<double>(pageHeight) / vshrink));
int targetPageHeight = targetHeight; int targetPageHeight = targetHeight;
// In toilet-roll mode, we must adjust vshrink so that we exactly hit // In toilet-roll mode, we must adjust vshrink so that we exactly hit
// preshrunkPageHeight or we'll have pixels straddling pixel boundaries // pageHeight or we'll have pixels straddling pixel boundaries
if (thumbHeight > preshrunkPageHeight) { if (inputHeight > pageHeight) {
targetHeight *= nPages; targetHeight *= nPages;
vshrink = static_cast<double>(thumbHeight) / targetHeight; vshrink = static_cast<double>(inputHeight) / targetHeight;
} }
// Ensure we're using a device-independent colour space // Ensure we're using a device-independent colour space
@@ -325,16 +339,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 && sharp::HasAlpha(image)) {
// Scale up 8-bit values to match 16-bit input image image = sharp::Flatten(image, baton->flattenBackground);
double const multiplier = sharp::Is16Bit(image.interpretation()) ? 256.0 : 1.0;
// Background colour
std::vector<double> background {
baton->flattenBackground[0] * multiplier,
baton->flattenBackground[1] * multiplier,
baton->flattenBackground[2] * multiplier
};
image = image.flatten(VImage::option()
->set("background", background));
} }
// Negate the colours in the image // Negate the colours in the image
@@ -356,65 +361,41 @@ class PipelineWorker : public Napi::AsyncWorker {
bool const shouldBlur = baton->blurSigma != 0.0; bool const shouldBlur = baton->blurSigma != 0.0;
bool const shouldConv = baton->convKernelWidth * baton->convKernelHeight > 0; bool const shouldConv = baton->convKernelWidth * baton->convKernelHeight > 0;
bool const shouldSharpen = baton->sharpenSigma != 0.0; bool const shouldSharpen = baton->sharpenSigma != 0.0;
bool const shouldApplyMedian = baton->medianSize > 0;
bool const shouldComposite = !baton->composite.empty(); bool const shouldComposite = !baton->composite.empty();
bool const shouldModulate = baton->brightness != 1.0 || baton->saturation != 1.0 ||
baton->hue != 0.0 || baton->lightness != 0.0;
bool const shouldApplyClahe = baton->claheWidth != 0 && baton->claheHeight != 0;
if (shouldComposite && !sharp::HasAlpha(image)) { if (shouldComposite && !sharp::HasAlpha(image)) {
image = sharp::EnsureAlpha(image, 1); image = sharp::EnsureAlpha(image, 1);
} }
bool const shouldPremultiplyAlpha = sharp::HasAlpha(image) && bool const shouldPremultiplyAlpha = sharp::HasAlpha(image) &&
(shouldResize || shouldBlur || shouldConv || shouldSharpen || shouldComposite); (shouldResize || shouldBlur || shouldConv || shouldSharpen);
// Premultiply image alpha channel before all transformations to avoid
// dark fringing around bright pixels
// See: http://entropymine.com/imageworsener/resizealpha/
if (shouldPremultiplyAlpha) { if (shouldPremultiplyAlpha) {
image = image.premultiply(); image = image.premultiply();
} }
// Resize // Resize
if (shouldResize) { if (shouldResize) {
VipsKernel kernel = static_cast<VipsKernel>(
vips_enum_from_nick(nullptr, VIPS_TYPE_KERNEL, baton->kernel.data()));
if (
kernel != VIPS_KERNEL_NEAREST && kernel != VIPS_KERNEL_CUBIC && kernel != VIPS_KERNEL_LANCZOS2 &&
kernel != VIPS_KERNEL_LANCZOS3 && kernel != VIPS_KERNEL_MITCHELL
) {
throw vips::VError("Unknown kernel");
}
image = image.resize(1.0 / hshrink, VImage::option() image = image.resize(1.0 / hshrink, VImage::option()
->set("vscale", 1.0 / vshrink) ->set("vscale", 1.0 / vshrink)
->set("kernel", kernel)); ->set("kernel", baton->kernel));
} }
// Rotate post-extract 90-angle // Auto-rotate post-extract
if (!baton->rotateBeforePreExtract && rotation != VIPS_ANGLE_D0) { if (autoRotation != VIPS_ANGLE_D0) {
image = image.rot(rotation); image = image.rot(autoRotation);
if (flip) {
image = image.flip(VIPS_DIRECTION_VERTICAL);
flip = FALSE;
}
if (flop) {
image = image.flip(VIPS_DIRECTION_HORIZONTAL);
flop = FALSE;
}
image = sharp::RemoveExifOrientation(image);
} }
// Flip (mirror about Y axis) // Flip (mirror about Y axis)
if (baton->flip || flip) { if (baton->flip || autoFlip) {
image = image.flip(VIPS_DIRECTION_VERTICAL); image = image.flip(VIPS_DIRECTION_VERTICAL);
image = sharp::RemoveExifOrientation(image);
} }
// Flop (mirror about X axis) // Flop (mirror about X axis)
if (baton->flop || flop) { if (baton->flop || autoFlop) {
image = image.flip(VIPS_DIRECTION_HORIZONTAL); image = image.flip(VIPS_DIRECTION_HORIZONTAL);
image = sharp::RemoveExifOrientation(image); }
// Rotate post-extract 90-angle
if (rotation != VIPS_ANGLE_D0) {
image = image.rot(rotation);
} }
// Join additional color channels to the image // Join additional color channels to the image
@@ -448,18 +429,12 @@ class PipelineWorker : public Napi::AsyncWorker {
std::tie(image, background) = sharp::ApplyAlpha(image, baton->resizeBackground, shouldPremultiplyAlpha); std::tie(image, background) = sharp::ApplyAlpha(image, baton->resizeBackground, shouldPremultiplyAlpha);
// Embed // Embed
// Calculate where to position the embedded image if gravity specified, else center.
int left; int left;
int top; int top;
left = static_cast<int>(round((baton->width - inputWidth) / 2));
top = static_cast<int>(round((baton->height - inputHeight) / 2));
int width = std::max(inputWidth, baton->width);
int height = std::max(inputHeight, baton->height);
std::tie(left, top) = sharp::CalculateEmbedPosition( std::tie(left, top) = sharp::CalculateEmbedPosition(
inputWidth, inputHeight, baton->width, baton->height, baton->position); inputWidth, inputHeight, baton->width, baton->height, baton->position);
int width = std::max(inputWidth, baton->width);
int height = std::max(inputHeight, baton->height);
image = nPages > 1 image = nPages > 1
? sharp::EmbedMultiPage(image, ? sharp::EmbedMultiPage(image,
@@ -532,12 +507,14 @@ class PipelineWorker : public Napi::AsyncWorker {
MultiPageUnsupported(nPages, "Affine"); MultiPageUnsupported(nPages, "Affine");
std::vector<double> background; std::vector<double> background;
std::tie(image, background) = sharp::ApplyAlpha(image, baton->affineBackground, shouldPremultiplyAlpha); std::tie(image, background) = sharp::ApplyAlpha(image, baton->affineBackground, shouldPremultiplyAlpha);
vips::VInterpolate interp = vips::VInterpolate::new_from_name(
const_cast<char*>(baton->affineInterpolator.data()));
image = image.affine(baton->affineMatrix, VImage::option()->set("background", background) image = image.affine(baton->affineMatrix, VImage::option()->set("background", background)
->set("idx", baton->affineIdx) ->set("idx", baton->affineIdx)
->set("idy", baton->affineIdy) ->set("idy", baton->affineIdy)
->set("odx", baton->affineOdx) ->set("odx", baton->affineOdx)
->set("ody", baton->affineOdy) ->set("ody", baton->affineOdy)
->set("interpolate", baton->affineInterpolator)); ->set("interpolate", interp));
} }
// Extend edges // Extend edges
@@ -556,7 +533,7 @@ class PipelineWorker : public Napi::AsyncWorker {
VImage::option()->set("extend", VIPS_EXTEND_BACKGROUND)->set("background", background)); VImage::option()->set("extend", VIPS_EXTEND_BACKGROUND)->set("background", background));
} }
// Median - must happen before blurring, due to the utility of blurring after thresholding // Median - must happen before blurring, due to the utility of blurring after thresholding
if (shouldApplyMedian) { if (baton->medianSize > 0) {
image = image.median(baton->medianSize); image = image.median(baton->medianSize);
} }
// Threshold - must happen before blurring, due to the utility of blurring after thresholding // Threshold - must happen before blurring, due to the utility of blurring after thresholding
@@ -582,17 +559,33 @@ class PipelineWorker : public Napi::AsyncWorker {
image = sharp::Recomb(image, baton->recombMatrix); image = sharp::Recomb(image, baton->recombMatrix);
} }
if (shouldModulate) { // Modulate
if (baton->brightness != 1.0 || baton->saturation != 1.0 || baton->hue != 0.0 || baton->lightness != 0.0) {
image = sharp::Modulate(image, baton->brightness, baton->saturation, baton->hue, baton->lightness); image = sharp::Modulate(image, baton->brightness, baton->saturation, baton->hue, baton->lightness);
} }
// Sharpen // Sharpen
if (shouldSharpen) { if (shouldSharpen) {
image = sharp::Sharpen(image, baton->sharpenSigma, baton->sharpenFlat, baton->sharpenJagged); image = sharp::Sharpen(image, baton->sharpenSigma, baton->sharpenM1, baton->sharpenM2,
baton->sharpenX1, baton->sharpenY2, baton->sharpenY3);
} }
// Reverse premultiplication after all transformations
if (shouldPremultiplyAlpha) {
image = image.unpremultiply();
// Cast pixel values to integer
if (sharp::Is16Bit(image.interpretation())) {
image = image.cast(VIPS_FORMAT_USHORT);
} else {
image = image.cast(VIPS_FORMAT_UCHAR);
}
}
baton->premultiplied = shouldPremultiplyAlpha;
// Composite // Composite
if (shouldComposite) { if (shouldComposite) {
std::vector<VImage> images = { image };
std::vector<int> modes, xs, ys;
for (Composite *composite : baton->composite) { for (Composite *composite : baton->composite) {
VImage compositeImage; VImage compositeImage;
sharp::ImageType compositeImageType = sharp::ImageType::UNKNOWN; sharp::ImageType compositeImageType = sharp::ImageType::UNKNOWN;
@@ -607,14 +600,14 @@ class PipelineWorker : public Napi::AsyncWorker {
int across = 0; int across = 0;
int down = 0; int down = 0;
// Use gravity in overlay // Use gravity in overlay
if (compositeImage.width() <= baton->width) { if (compositeImage.width() <= image.width()) {
across = static_cast<int>(ceil(static_cast<double>(image.width()) / compositeImage.width())); across = static_cast<int>(ceil(static_cast<double>(image.width()) / compositeImage.width()));
// Ensure odd number of tiles across when gravity is centre, north or south // Ensure odd number of tiles across when gravity is centre, north or south
if (composite->gravity == 0 || composite->gravity == 1 || composite->gravity == 3) { if (composite->gravity == 0 || composite->gravity == 1 || composite->gravity == 3) {
across |= 1; across |= 1;
} }
} }
if (compositeImage.height() <= baton->height) { if (compositeImage.height() <= image.height()) {
down = static_cast<int>(ceil(static_cast<double>(image.height()) / compositeImage.height())); down = static_cast<int>(ceil(static_cast<double>(image.height()) / compositeImage.height()));
// Ensure odd number of tiles down when gravity is centre, east or west // Ensure odd number of tiles down when gravity is centre, east or west
if (composite->gravity == 0 || composite->gravity == 2 || composite->gravity == 4) { if (composite->gravity == 0 || composite->gravity == 2 || composite->gravity == 4) {
@@ -638,12 +631,12 @@ 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 premultiplied alpha // Ensure image to composite is sRGB with unpremultiplied alpha
compositeImage = compositeImage.colourspace(VIPS_INTERPRETATION_sRGB); compositeImage = compositeImage.colourspace(VIPS_INTERPRETATION_sRGB);
if (!sharp::HasAlpha(compositeImage)) { if (!sharp::HasAlpha(compositeImage)) {
compositeImage = sharp::EnsureAlpha(compositeImage, 1); compositeImage = sharp::EnsureAlpha(compositeImage, 1);
} }
if (!composite->premultiplied) compositeImage = compositeImage.premultiply(); if (composite->premultiplied) compositeImage = compositeImage.unpremultiply();
// Calculate position // Calculate position
int left; int left;
int top; int top;
@@ -661,33 +654,21 @@ class PipelineWorker : public Napi::AsyncWorker {
std::tie(left, top) = sharp::CalculateCrop(image.width(), image.height(), std::tie(left, top) = sharp::CalculateCrop(image.width(), image.height(),
compositeImage.width(), compositeImage.height(), composite->gravity); compositeImage.width(), compositeImage.height(), composite->gravity);
} }
// Composite images.push_back(compositeImage);
image = image.composite2(compositeImage, composite->mode, VImage::option() modes.push_back(composite->mode);
->set("premultiplied", TRUE) xs.push_back(left);
->set("x", left) ys.push_back(top);
->set("y", top));
} }
image = VImage::composite(images, modes, VImage::option()->set("x", xs)->set("y", ys));
} }
// Reverse premultiplication after all transformations:
if (shouldPremultiplyAlpha) {
image = image.unpremultiply();
// Cast pixel values to integer
if (sharp::Is16Bit(image.interpretation())) {
image = image.cast(VIPS_FORMAT_USHORT);
} else {
image = image.cast(VIPS_FORMAT_UCHAR);
}
}
baton->premultiplied = shouldPremultiplyAlpha;
// Gamma decoding (brighten) // Gamma decoding (brighten)
if (baton->gammaOut >= 1 && baton->gammaOut <= 3) { if (baton->gammaOut >= 1 && baton->gammaOut <= 3) {
image = sharp::Gamma(image, baton->gammaOut); image = sharp::Gamma(image, baton->gammaOut);
} }
// Linear adjustment (a * in + b) // Linear adjustment (a * in + b)
if (baton->linearA != 1.0 || baton->linearB != 0.0) { if (!baton->linearA.empty()) {
image = sharp::Linear(image, baton->linearA, baton->linearB); image = sharp::Linear(image, baton->linearA, baton->linearB);
} }
@@ -697,7 +678,7 @@ class PipelineWorker : public Napi::AsyncWorker {
} }
// Apply contrast limiting adaptive histogram equalization (CLAHE) // Apply contrast limiting adaptive histogram equalization (CLAHE)
if (shouldApplyClahe) { if (baton->claheWidth != 0 && baton->claheHeight != 0) {
image = sharp::Clahe(image, baton->claheWidth, baton->claheHeight, baton->claheMaxSlope); image = sharp::Clahe(image, baton->claheWidth, baton->claheHeight, baton->claheMaxSlope);
} }
@@ -720,24 +701,6 @@ class PipelineWorker : public Napi::AsyncWorker {
image = sharp::Tint(image, baton->tintA, baton->tintB); image = sharp::Tint(image, baton->tintA, baton->tintB);
} }
// Extract an image channel (aka vips band)
if (baton->extractChannel > -1) {
if (baton->extractChannel >= image.bands()) {
if (baton->extractChannel == 3 && sharp::HasAlpha(image)) {
baton->extractChannel = image.bands() - 1;
} else {
(baton->err).append("Cannot extract channel from image. Too few channels in image.");
return Error();
}
}
VipsInterpretation const interpretation = sharp::Is16Bit(image.interpretation())
? VIPS_INTERPRETATION_GREY16
: VIPS_INTERPRETATION_B_W;
image = image
.extract_band(baton->extractChannel)
.copy(VImage::option()->set("interpretation", interpretation));
}
// Remove alpha channel, if any // Remove alpha channel, if any
if (baton->removeAlpha) { if (baton->removeAlpha) {
image = sharp::RemoveAlpha(image); image = sharp::RemoveAlpha(image);
@@ -763,6 +726,26 @@ class PipelineWorker : public Napi::AsyncWorker {
} }
} }
// Extract channel
if (baton->extractChannel > -1) {
if (baton->extractChannel >= image.bands()) {
if (baton->extractChannel == 3 && sharp::HasAlpha(image)) {
baton->extractChannel = image.bands() - 1;
} else {
(baton->err)
.append("Cannot extract channel ").append(std::to_string(baton->extractChannel))
.append(" from image with channels 0-").append(std::to_string(image.bands() - 1));
return Error();
}
}
VipsInterpretation colourspace = sharp::Is16Bit(image.interpretation())
? VIPS_INTERPRETATION_GREY16
: VIPS_INTERPRETATION_B_W;
image = image
.extract_band(baton->extractChannel)
.copy(VImage::option()->set("interpretation", colourspace));
}
// Apply output ICC profile // Apply output ICC profile
if (!baton->withMetadataIcc.empty()) { if (!baton->withMetadataIcc.empty()) {
image = image.icc_transform( image = image.icc_transform(
@@ -871,6 +854,8 @@ class PipelineWorker : public Napi::AsyncWorker {
->set("near_lossless", baton->webpNearLossless) ->set("near_lossless", baton->webpNearLossless)
->set("smart_subsample", baton->webpSmartSubsample) ->set("smart_subsample", baton->webpSmartSubsample)
->set("effort", baton->webpEffort) ->set("effort", baton->webpEffort)
->set("min_size", baton->webpMinSize)
->set("mixed", baton->webpMixed)
->set("alpha_q", baton->webpAlphaQuality))); ->set("alpha_q", baton->webpAlphaQuality)));
baton->bufferOut = static_cast<char*>(area->data); baton->bufferOut = static_cast<char*>(area->data);
baton->bufferOutLength = area->length; baton->bufferOutLength = area->length;
@@ -885,6 +870,9 @@ class PipelineWorker : public Napi::AsyncWorker {
->set("strip", !baton->withMetadata) ->set("strip", !baton->withMetadata)
->set("bitdepth", baton->gifBitdepth) ->set("bitdepth", baton->gifBitdepth)
->set("effort", baton->gifEffort) ->set("effort", baton->gifEffort)
->set("reoptimise", baton->gifReoptimise)
->set("interframe_maxerror", baton->gifInterFrameMaxError)
->set("interpalette_maxerror", baton->gifInterPaletteMaxError)
->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;
@@ -923,12 +911,13 @@ class PipelineWorker : public Napi::AsyncWorker {
} else if (baton->formatOut == "heif" || } else if (baton->formatOut == "heif" ||
(baton->formatOut == "input" && inputImageType == sharp::ImageType::HEIF)) { (baton->formatOut == "input" && inputImageType == sharp::ImageType::HEIF)) {
// Write HEIF to buffer // Write HEIF to buffer
image = sharp::RemoveAnimationProperties(image); image = sharp::RemoveAnimationProperties(image).cast(VIPS_FORMAT_UCHAR);
VipsArea *area = reinterpret_cast<VipsArea*>(image.heifsave_buffer(VImage::option() VipsArea *area = reinterpret_cast<VipsArea*>(image.heifsave_buffer(VImage::option()
->set("strip", !baton->withMetadata) ->set("strip", !baton->withMetadata)
->set("Q", baton->heifQuality) ->set("Q", baton->heifQuality)
->set("compression", baton->heifCompression) ->set("compression", baton->heifCompression)
->set("effort", baton->heifEffort) ->set("effort", baton->heifEffort)
->set("bitdepth", 8)
->set("subsample_mode", baton->heifChromaSubsampling == "4:4:4" ->set("subsample_mode", baton->heifChromaSubsampling == "4:4:4"
? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON) ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON)
->set("lossless", baton->heifLossless))); ->set("lossless", baton->heifLossless)));
@@ -937,6 +926,34 @@ class PipelineWorker : public Napi::AsyncWorker {
area->free_fn = nullptr; area->free_fn = nullptr;
vips_area_unref(area); vips_area_unref(area);
baton->formatOut = "heif"; baton->formatOut = "heif";
} else if (baton->formatOut == "dz") {
// Write DZ to buffer
baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP;
if (!sharp::HasAlpha(image)) {
baton->tileBackground.pop_back();
}
vips::VOption *options = BuildOptionsDZ(baton);
VipsArea *area = reinterpret_cast<VipsArea*>(image.dzsave_buffer(options));
baton->bufferOut = static_cast<char*>(area->data);
baton->bufferOutLength = area->length;
area->free_fn = nullptr;
vips_area_unref(area);
baton->formatOut = "dz";
} else if (baton->formatOut == "jxl" ||
(baton->formatOut == "input" && inputImageType == sharp::ImageType::JXL)) {
// Write JXL to buffer
image = sharp::RemoveAnimationProperties(image);
VipsArea *area = reinterpret_cast<VipsArea*>(image.jxlsave_buffer(VImage::option()
->set("strip", !baton->withMetadata)
->set("distance", baton->jxlDistance)
->set("tier", baton->jxlDecodingTier)
->set("effort", baton->jxlEffort)
->set("lossless", baton->jxlLossless)));
baton->bufferOut = static_cast<char*>(area->data);
baton->bufferOutLength = area->length;
area->free_fn = nullptr;
vips_area_unref(area);
baton->formatOut = "jxl";
} else if (baton->formatOut == "raw" || } else if (baton->formatOut == "raw" ||
(baton->formatOut == "input" && inputImageType == sharp::ImageType::RAW)) { (baton->formatOut == "input" && inputImageType == sharp::ImageType::RAW)) {
// Write raw, uncompressed image data to buffer // Write raw, uncompressed image data to buffer
@@ -975,6 +992,7 @@ class PipelineWorker : public Napi::AsyncWorker {
bool const isTiff = sharp::IsTiff(baton->fileOut); bool const isTiff = sharp::IsTiff(baton->fileOut);
bool const isJp2 = sharp::IsJp2(baton->fileOut); bool const isJp2 = sharp::IsJp2(baton->fileOut);
bool const isHeif = sharp::IsHeif(baton->fileOut); bool const isHeif = sharp::IsHeif(baton->fileOut);
bool const isJxl = sharp::IsJxl(baton->fileOut);
bool const isDz = sharp::IsDz(baton->fileOut); bool const isDz = sharp::IsDz(baton->fileOut);
bool const isDzZip = sharp::IsDzZip(baton->fileOut); bool const isDzZip = sharp::IsDzZip(baton->fileOut);
bool const isV = sharp::IsV(baton->fileOut); bool const isV = sharp::IsV(baton->fileOut);
@@ -1038,6 +1056,8 @@ class PipelineWorker : public Napi::AsyncWorker {
->set("near_lossless", baton->webpNearLossless) ->set("near_lossless", baton->webpNearLossless)
->set("smart_subsample", baton->webpSmartSubsample) ->set("smart_subsample", baton->webpSmartSubsample)
->set("effort", baton->webpEffort) ->set("effort", baton->webpEffort)
->set("min_size", baton->webpMinSize)
->set("mixed", baton->webpMixed)
->set("alpha_q", baton->webpAlphaQuality)); ->set("alpha_q", baton->webpAlphaQuality));
baton->formatOut = "webp"; baton->formatOut = "webp";
} else if (baton->formatOut == "gif" || (mightMatchInput && isGif) || } else if (baton->formatOut == "gif" || (mightMatchInput && isGif) ||
@@ -1048,6 +1068,7 @@ class PipelineWorker : public Napi::AsyncWorker {
->set("strip", !baton->withMetadata) ->set("strip", !baton->withMetadata)
->set("bitdepth", baton->gifBitdepth) ->set("bitdepth", baton->gifBitdepth)
->set("effort", baton->gifEffort) ->set("effort", baton->gifEffort)
->set("reoptimise", baton->gifReoptimise)
->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) ||
@@ -1078,75 +1099,37 @@ class PipelineWorker : public Napi::AsyncWorker {
} else if (baton->formatOut == "heif" || (mightMatchInput && isHeif) || } else if (baton->formatOut == "heif" || (mightMatchInput && isHeif) ||
(willMatchInput && inputImageType == sharp::ImageType::HEIF)) { (willMatchInput && inputImageType == sharp::ImageType::HEIF)) {
// Write HEIF to file // Write HEIF to file
image = sharp::RemoveAnimationProperties(image); image = sharp::RemoveAnimationProperties(image).cast(VIPS_FORMAT_UCHAR);
image.heifsave(const_cast<char*>(baton->fileOut.data()), VImage::option() image.heifsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
->set("strip", !baton->withMetadata) ->set("strip", !baton->withMetadata)
->set("Q", baton->heifQuality) ->set("Q", baton->heifQuality)
->set("compression", baton->heifCompression) ->set("compression", baton->heifCompression)
->set("effort", baton->heifEffort) ->set("effort", baton->heifEffort)
->set("bitdepth", 8)
->set("subsample_mode", baton->heifChromaSubsampling == "4:4:4" ->set("subsample_mode", baton->heifChromaSubsampling == "4:4:4"
? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON) ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON)
->set("lossless", baton->heifLossless)); ->set("lossless", baton->heifLossless));
baton->formatOut = "heif"; baton->formatOut = "heif";
} else if (baton->formatOut == "jxl" || (mightMatchInput && isJxl) ||
(willMatchInput && inputImageType == sharp::ImageType::JXL)) {
// Write JXL to file
image = sharp::RemoveAnimationProperties(image);
image.jxlsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
->set("strip", !baton->withMetadata)
->set("distance", baton->jxlDistance)
->set("tier", baton->jxlDecodingTier)
->set("effort", baton->jxlEffort)
->set("lossless", baton->jxlLossless));
baton->formatOut = "jxl";
} else if (baton->formatOut == "dz" || isDz || isDzZip) { } else if (baton->formatOut == "dz" || isDz || isDzZip) {
// Write DZ to file
if (isDzZip) { if (isDzZip) {
baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP; baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP;
} }
// Forward format options through suffix
std::string suffix;
if (baton->tileFormat == "png") {
std::vector<std::pair<std::string, std::string>> options {
{"interlace", baton->pngProgressive ? "TRUE" : "FALSE"},
{"compression", std::to_string(baton->pngCompressionLevel)},
{"filter", baton->pngAdaptiveFiltering ? "all" : "none"}
};
suffix = AssembleSuffixString(".png", options);
} else if (baton->tileFormat == "webp") {
std::vector<std::pair<std::string, std::string>> options {
{"Q", std::to_string(baton->webpQuality)},
{"alpha_q", std::to_string(baton->webpAlphaQuality)},
{"lossless", baton->webpLossless ? "TRUE" : "FALSE"},
{"near_lossless", baton->webpNearLossless ? "TRUE" : "FALSE"},
{"smart_subsample", baton->webpSmartSubsample ? "TRUE" : "FALSE"},
{"effort", std::to_string(baton->webpEffort)}
};
suffix = AssembleSuffixString(".webp", options);
} else {
std::vector<std::pair<std::string, std::string>> options {
{"Q", std::to_string(baton->jpegQuality)},
{"interlace", baton->jpegProgressive ? "TRUE" : "FALSE"},
{"subsample_mode", baton->jpegChromaSubsampling == "4:4:4" ? "off" : "on"},
{"trellis_quant", baton->jpegTrellisQuantisation ? "TRUE" : "FALSE"},
{"quant_table", std::to_string(baton->jpegQuantisationTable)},
{"overshoot_deringing", baton->jpegOvershootDeringing ? "TRUE": "FALSE"},
{"optimize_scans", baton->jpegOptimiseScans ? "TRUE": "FALSE"},
{"optimize_coding", baton->jpegOptimiseCoding ? "TRUE": "FALSE"}
};
std::string extname = baton->tileLayout == VIPS_FOREIGN_DZ_LAYOUT_DZ ? ".jpeg" : ".jpg";
suffix = AssembleSuffixString(extname, options);
}
// Remove alpha channel from tile background if image does not contain an alpha channel
if (!sharp::HasAlpha(image)) { if (!sharp::HasAlpha(image)) {
baton->tileBackground.pop_back(); baton->tileBackground.pop_back();
} }
// Write DZ to file vips::VOption *options = BuildOptionsDZ(baton);
vips::VOption *options = VImage::option()
->set("strip", !baton->withMetadata)
->set("tile_size", baton->tileSize)
->set("overlap", baton->tileOverlap)
->set("container", baton->tileContainer)
->set("layout", baton->tileLayout)
->set("suffix", const_cast<char*>(suffix.data()))
->set("angle", CalculateAngleRotation(baton->tileAngle))
->set("background", baton->tileBackground)
->set("centre", baton->tileCentre)
->set("id", const_cast<char*>(baton->tileId.data()))
->set("skip_blanks", baton->tileSkipBlanks);
// libvips chooses a default depth based on layout. Instead of replicating that logic here by
// not passing anything - libvips will handle choice
if (baton->tileDepth < VIPS_FOREIGN_DZ_DEPTH_LAST) {
options->set("depth", baton->tileDepth);
}
image.dzsave(const_cast<char*>(baton->fileOut.data()), options); image.dzsave(const_cast<char*>(baton->fileOut.data()), options);
baton->formatOut = "dz"; baton->formatOut = "dz";
} else if (baton->formatOut == "v" || (mightMatchInput && isV) || } else if (baton->formatOut == "v" || (mightMatchInput && isV) ||
@@ -1215,12 +1198,16 @@ class PipelineWorker : public Napi::AsyncWorker {
info.Set("trimOffsetTop", static_cast<int32_t>(baton->trimOffsetTop)); info.Set("trimOffsetTop", static_cast<int32_t>(baton->trimOffsetTop));
} }
if (baton->input->textAutofitDpi) {
info.Set("textAutofitDpi", static_cast<uint32_t>(baton->input->textAutofitDpi));
}
if (baton->bufferOutLength > 0) { if (baton->bufferOutLength > 0) {
// Add buffer size to info // Add buffer size to info
info.Set("size", static_cast<uint32_t>(baton->bufferOutLength)); info.Set("size", static_cast<uint32_t>(baton->bufferOutLength));
// Pass ownership of output data to Buffer instance // Pass ownership of output data to Buffer instance
Napi::Buffer<char> data = Napi::Buffer<char>::New(env, static_cast<char*>(baton->bufferOut), Napi::Buffer<char> data = sharp::NewOrCopyBuffer(env, static_cast<char*>(baton->bufferOut),
baton->bufferOutLength, sharp::FreeCallback); baton->bufferOutLength);
Callback().MakeCallback(Receiver().Value(), { env.Null(), data, info }); Callback().MakeCallback(Receiver().Value(), { env.Null(), data, info });
} else { } else {
// Add file size to info // Add file size to info
@@ -1303,7 +1290,7 @@ class PipelineWorker : public Napi::AsyncWorker {
/* /*
Assemble the suffix argument to dzsave, which is the format (by extname) Assemble the suffix argument to dzsave, which is the format (by extname)
alongisde comma-separated arguments to the corresponding `formatsave` vips alongside comma-separated arguments to the corresponding `formatsave` vips
action. action.
*/ */
std::string std::string
@@ -1318,6 +1305,67 @@ class PipelineWorker : public Napi::AsyncWorker {
return extname + "[" + argument + "]"; return extname + "[" + argument + "]";
} }
/*
Build VOption for dzsave
*/
vips::VOption*
BuildOptionsDZ(PipelineBaton *baton) {
// Forward format options through suffix
std::string suffix;
if (baton->tileFormat == "png") {
std::vector<std::pair<std::string, std::string>> options {
{"interlace", baton->pngProgressive ? "TRUE" : "FALSE"},
{"compression", std::to_string(baton->pngCompressionLevel)},
{"filter", baton->pngAdaptiveFiltering ? "all" : "none"}
};
suffix = AssembleSuffixString(".png", options);
} else if (baton->tileFormat == "webp") {
std::vector<std::pair<std::string, std::string>> options {
{"Q", std::to_string(baton->webpQuality)},
{"alpha_q", std::to_string(baton->webpAlphaQuality)},
{"lossless", baton->webpLossless ? "TRUE" : "FALSE"},
{"near_lossless", baton->webpNearLossless ? "TRUE" : "FALSE"},
{"smart_subsample", baton->webpSmartSubsample ? "TRUE" : "FALSE"},
{"min_size", baton->webpMinSize ? "TRUE" : "FALSE"},
{"mixed", baton->webpMixed ? "TRUE" : "FALSE"},
{"effort", std::to_string(baton->webpEffort)}
};
suffix = AssembleSuffixString(".webp", options);
} else {
std::vector<std::pair<std::string, std::string>> options {
{"Q", std::to_string(baton->jpegQuality)},
{"interlace", baton->jpegProgressive ? "TRUE" : "FALSE"},
{"subsample_mode", baton->jpegChromaSubsampling == "4:4:4" ? "off" : "on"},
{"trellis_quant", baton->jpegTrellisQuantisation ? "TRUE" : "FALSE"},
{"quant_table", std::to_string(baton->jpegQuantisationTable)},
{"overshoot_deringing", baton->jpegOvershootDeringing ? "TRUE": "FALSE"},
{"optimize_scans", baton->jpegOptimiseScans ? "TRUE": "FALSE"},
{"optimize_coding", baton->jpegOptimiseCoding ? "TRUE": "FALSE"}
};
std::string extname = baton->tileLayout == VIPS_FOREIGN_DZ_LAYOUT_DZ ? ".jpeg" : ".jpg";
suffix = AssembleSuffixString(extname, options);
}
vips::VOption *options = VImage::option()
->set("strip", !baton->withMetadata)
->set("tile_size", baton->tileSize)
->set("overlap", baton->tileOverlap)
->set("container", baton->tileContainer)
->set("layout", baton->tileLayout)
->set("suffix", const_cast<char*>(suffix.data()))
->set("angle", CalculateAngleRotation(baton->tileAngle))
->set("background", baton->tileBackground)
->set("centre", baton->tileCentre)
->set("id", const_cast<char*>(baton->tileId.data()))
->set("skip_blanks", baton->tileSkipBlanks);
if (baton->tileDepth < VIPS_FOREIGN_DZ_DEPTH_LAST) {
options->set("depth", baton->tileDepth);
}
if (!baton->tileBasename.empty()) {
options->set("basename", const_cast<char*>(baton->tileBasename.data()));
}
return options;
}
/* /*
Clear all thread-local data. Clear all thread-local data.
*/ */
@@ -1363,17 +1411,13 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
} else if (canvas == "ignore_aspect") { } else if (canvas == "ignore_aspect") {
baton->canvas = sharp::Canvas::IGNORE_ASPECT; baton->canvas = sharp::Canvas::IGNORE_ASPECT;
} }
// Tint chroma
baton->tintA = sharp::AttrAsDouble(options, "tintA");
baton->tintB = sharp::AttrAsDouble(options, "tintB");
// Composite // Composite
Napi::Array compositeArray = options.Get("composite").As<Napi::Array>(); Napi::Array compositeArray = options.Get("composite").As<Napi::Array>();
for (unsigned int i = 0; i < compositeArray.Length(); i++) { for (unsigned int i = 0; i < compositeArray.Length(); i++) {
Napi::Object compositeObject = compositeArray.Get(i).As<Napi::Object>(); Napi::Object compositeObject = compositeArray.Get(i).As<Napi::Object>();
Composite *composite = new Composite; Composite *composite = new Composite;
composite->input = sharp::CreateInputDescriptor(compositeObject.Get("input").As<Napi::Object>()); composite->input = sharp::CreateInputDescriptor(compositeObject.Get("input").As<Napi::Object>());
composite->mode = static_cast<VipsBlendMode>( composite->mode = sharp::AttrAsEnum<VipsBlendMode>(compositeObject, "blend", VIPS_TYPE_BLEND_MODE);
vips_enum_from_nick(nullptr, VIPS_TYPE_BLEND_MODE, sharp::AttrAsStr(compositeObject, "blend").data()));
composite->gravity = sharp::AttrAsUint32(compositeObject, "gravity"); composite->gravity = sharp::AttrAsUint32(compositeObject, "gravity");
composite->left = sharp::AttrAsInt32(compositeObject, "left"); composite->left = sharp::AttrAsInt32(compositeObject, "left");
composite->top = sharp::AttrAsInt32(compositeObject, "top"); composite->top = sharp::AttrAsInt32(compositeObject, "top");
@@ -1387,7 +1431,7 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
baton->withoutReduction = sharp::AttrAsBool(options, "withoutReduction"); baton->withoutReduction = sharp::AttrAsBool(options, "withoutReduction");
baton->position = sharp::AttrAsInt32(options, "position"); baton->position = sharp::AttrAsInt32(options, "position");
baton->resizeBackground = sharp::AttrAsVectorOfDouble(options, "resizeBackground"); baton->resizeBackground = sharp::AttrAsVectorOfDouble(options, "resizeBackground");
baton->kernel = sharp::AttrAsStr(options, "kernel"); baton->kernel = sharp::AttrAsEnum<VipsKernel>(options, "kernel", VIPS_TYPE_KERNEL);
baton->fastShrinkOnLoad = sharp::AttrAsBool(options, "fastShrinkOnLoad"); baton->fastShrinkOnLoad = sharp::AttrAsBool(options, "fastShrinkOnLoad");
// Join Channel Options // Join Channel Options
if (options.Has("joinChannelIn")) { if (options.Has("joinChannelIn")) {
@@ -1409,17 +1453,23 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
baton->lightness = sharp::AttrAsDouble(options, "lightness"); baton->lightness = sharp::AttrAsDouble(options, "lightness");
baton->medianSize = sharp::AttrAsUint32(options, "medianSize"); baton->medianSize = sharp::AttrAsUint32(options, "medianSize");
baton->sharpenSigma = sharp::AttrAsDouble(options, "sharpenSigma"); baton->sharpenSigma = sharp::AttrAsDouble(options, "sharpenSigma");
baton->sharpenFlat = sharp::AttrAsDouble(options, "sharpenFlat"); baton->sharpenM1 = sharp::AttrAsDouble(options, "sharpenM1");
baton->sharpenJagged = sharp::AttrAsDouble(options, "sharpenJagged"); baton->sharpenM2 = sharp::AttrAsDouble(options, "sharpenM2");
baton->sharpenX1 = sharp::AttrAsDouble(options, "sharpenX1");
baton->sharpenY2 = sharp::AttrAsDouble(options, "sharpenY2");
baton->sharpenY3 = sharp::AttrAsDouble(options, "sharpenY3");
baton->threshold = sharp::AttrAsInt32(options, "threshold"); baton->threshold = sharp::AttrAsInt32(options, "threshold");
baton->thresholdGrayscale = sharp::AttrAsBool(options, "thresholdGrayscale"); baton->thresholdGrayscale = sharp::AttrAsBool(options, "thresholdGrayscale");
baton->trimBackground = sharp::AttrAsVectorOfDouble(options, "trimBackground");
baton->trimThreshold = sharp::AttrAsDouble(options, "trimThreshold"); baton->trimThreshold = sharp::AttrAsDouble(options, "trimThreshold");
baton->gamma = sharp::AttrAsDouble(options, "gamma"); baton->gamma = sharp::AttrAsDouble(options, "gamma");
baton->gammaOut = sharp::AttrAsDouble(options, "gammaOut"); baton->gammaOut = sharp::AttrAsDouble(options, "gammaOut");
baton->linearA = sharp::AttrAsDouble(options, "linearA"); baton->linearA = sharp::AttrAsVectorOfDouble(options, "linearA");
baton->linearB = sharp::AttrAsDouble(options, "linearB"); baton->linearB = sharp::AttrAsVectorOfDouble(options, "linearB");
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->tintA = sharp::AttrAsDouble(options, "tintA");
baton->tintB = sharp::AttrAsDouble(options, "tintB");
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");
@@ -1442,15 +1492,15 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
baton->affineIdy = sharp::AttrAsDouble(options, "affineIdy"); baton->affineIdy = sharp::AttrAsDouble(options, "affineIdy");
baton->affineOdx = sharp::AttrAsDouble(options, "affineOdx"); baton->affineOdx = sharp::AttrAsDouble(options, "affineOdx");
baton->affineOdy = sharp::AttrAsDouble(options, "affineOdy"); baton->affineOdy = sharp::AttrAsDouble(options, "affineOdy");
baton->affineInterpolator = vips::VInterpolate::new_from_name(sharp::AttrAsStr(options, "affineInterpolator").data()); baton->affineInterpolator = sharp::AttrAsStr(options, "affineInterpolator");
baton->removeAlpha = sharp::AttrAsBool(options, "removeAlpha"); baton->removeAlpha = sharp::AttrAsBool(options, "removeAlpha");
baton->ensureAlpha = sharp::AttrAsDouble(options, "ensureAlpha"); baton->ensureAlpha = sharp::AttrAsDouble(options, "ensureAlpha");
if (options.Has("boolean")) { if (options.Has("boolean")) {
baton->boolean = sharp::CreateInputDescriptor(options.Get("boolean").As<Napi::Object>()); baton->boolean = sharp::CreateInputDescriptor(options.Get("boolean").As<Napi::Object>());
baton->booleanOp = sharp::GetBooleanOperation(sharp::AttrAsStr(options, "booleanOp")); baton->booleanOp = sharp::AttrAsEnum<VipsOperationBoolean>(options, "booleanOp", VIPS_TYPE_OPERATION_BOOLEAN);
} }
if (options.Has("bandBoolOp")) { if (options.Has("bandBoolOp")) {
baton->bandBoolOp = sharp::GetBooleanOperation(sharp::AttrAsStr(options, "bandBoolOp")); baton->bandBoolOp = sharp::AttrAsEnum<VipsOperationBoolean>(options, "bandBoolOp", VIPS_TYPE_OPERATION_BOOLEAN);
} }
if (options.Has("convKernel")) { if (options.Has("convKernel")) {
Napi::Object kernel = options.Get("convKernel").As<Napi::Object>(); Napi::Object kernel = options.Get("convKernel").As<Napi::Object>();
@@ -1472,11 +1522,12 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
baton->recombMatrix[i] = sharp::AttrAsDouble(recombMatrix, i); baton->recombMatrix[i] = sharp::AttrAsDouble(recombMatrix, i);
} }
} }
baton->colourspaceInput = sharp::GetInterpretation(sharp::AttrAsStr(options, "colourspaceInput")); baton->colourspaceInput = sharp::AttrAsEnum<VipsInterpretation>(
options, "colourspaceInput", VIPS_TYPE_INTERPRETATION);
if (baton->colourspaceInput == VIPS_INTERPRETATION_ERROR) { if (baton->colourspaceInput == VIPS_INTERPRETATION_ERROR) {
baton->colourspaceInput = VIPS_INTERPRETATION_LAST; baton->colourspaceInput = VIPS_INTERPRETATION_LAST;
} }
baton->colourspace = sharp::GetInterpretation(sharp::AttrAsStr(options, "colourspace")); baton->colourspace = sharp::AttrAsEnum<VipsInterpretation>(options, "colourspace", VIPS_TYPE_INTERPRETATION);
if (baton->colourspace == VIPS_INTERPRETATION_ERROR) { if (baton->colourspace == VIPS_INTERPRETATION_ERROR) {
baton->colourspace = VIPS_INTERPRETATION_sRGB; baton->colourspace = VIPS_INTERPRETATION_sRGB;
} }
@@ -1491,7 +1542,9 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
Napi::Array mdStrKeys = mdStrs.GetPropertyNames(); Napi::Array mdStrKeys = mdStrs.GetPropertyNames();
for (unsigned int i = 0; i < mdStrKeys.Length(); i++) { for (unsigned int i = 0; i < mdStrKeys.Length(); i++) {
std::string k = sharp::AttrAsStr(mdStrKeys, i); std::string k = sharp::AttrAsStr(mdStrKeys, i);
baton->withMetadataStrs.insert(std::make_pair(k, sharp::AttrAsStr(mdStrs, k))); if (mdStrs.HasOwnProperty(k)) {
baton->withMetadataStrs.insert(std::make_pair(k, sharp::AttrAsStr(mdStrs, k)));
}
} }
baton->timeoutSeconds = sharp::AttrAsUint32(options, "timeoutSeconds"); baton->timeoutSeconds = sharp::AttrAsUint32(options, "timeoutSeconds");
// Format-specific // Format-specific
@@ -1522,9 +1575,14 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
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->webpEffort = sharp::AttrAsUint32(options, "webpEffort"); baton->webpEffort = sharp::AttrAsUint32(options, "webpEffort");
baton->webpMinSize = sharp::AttrAsBool(options, "webpMinSize");
baton->webpMixed = sharp::AttrAsBool(options, "webpMixed");
baton->gifBitdepth = sharp::AttrAsUint32(options, "gifBitdepth"); baton->gifBitdepth = sharp::AttrAsUint32(options, "gifBitdepth");
baton->gifEffort = sharp::AttrAsUint32(options, "gifEffort"); baton->gifEffort = sharp::AttrAsUint32(options, "gifEffort");
baton->gifDither = sharp::AttrAsDouble(options, "gifDither"); baton->gifDither = sharp::AttrAsDouble(options, "gifDither");
baton->gifInterFrameMaxError = sharp::AttrAsDouble(options, "gifInterFrameMaxError");
baton->gifInterPaletteMaxError = sharp::AttrAsDouble(options, "gifInterPaletteMaxError");
baton->gifReoptimise = sharp::AttrAsBool(options, "gifReoptimise");
baton->tiffQuality = sharp::AttrAsUint32(options, "tiffQuality"); baton->tiffQuality = sharp::AttrAsUint32(options, "tiffQuality");
baton->tiffPyramid = sharp::AttrAsBool(options, "tiffPyramid"); baton->tiffPyramid = sharp::AttrAsBool(options, "tiffPyramid");
baton->tiffBitdepth = sharp::AttrAsUint32(options, "tiffBitdepth"); baton->tiffBitdepth = sharp::AttrAsUint32(options, "tiffBitdepth");
@@ -1536,28 +1594,23 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
if (baton->tiffXres == 1.0 && baton->tiffYres == 1.0 && baton->withMetadataDensity > 0) { if (baton->tiffXres == 1.0 && baton->tiffYres == 1.0 && baton->withMetadataDensity > 0) {
baton->tiffXres = baton->tiffYres = baton->withMetadataDensity / 25.4; baton->tiffXres = baton->tiffYres = baton->withMetadataDensity / 25.4;
} }
// tiff compression options baton->tiffCompression = sharp::AttrAsEnum<VipsForeignTiffCompression>(
baton->tiffCompression = static_cast<VipsForeignTiffCompression>( options, "tiffCompression", VIPS_TYPE_FOREIGN_TIFF_COMPRESSION);
vips_enum_from_nick(nullptr, VIPS_TYPE_FOREIGN_TIFF_COMPRESSION, baton->tiffPredictor = sharp::AttrAsEnum<VipsForeignTiffPredictor>(
sharp::AttrAsStr(options, "tiffCompression").data())); options, "tiffPredictor", VIPS_TYPE_FOREIGN_TIFF_PREDICTOR);
baton->tiffPredictor = static_cast<VipsForeignTiffPredictor>( baton->tiffResolutionUnit = sharp::AttrAsEnum<VipsForeignTiffResunit>(
vips_enum_from_nick(nullptr, VIPS_TYPE_FOREIGN_TIFF_PREDICTOR, options, "tiffResolutionUnit", VIPS_TYPE_FOREIGN_TIFF_RESUNIT);
sharp::AttrAsStr(options, "tiffPredictor").data()));
baton->tiffResolutionUnit = static_cast<VipsForeignTiffResunit>(
vips_enum_from_nick(nullptr, VIPS_TYPE_FOREIGN_TIFF_RESUNIT,
sharp::AttrAsStr(options, "tiffResolutionUnit").data()));
baton->heifQuality = sharp::AttrAsUint32(options, "heifQuality"); baton->heifQuality = sharp::AttrAsUint32(options, "heifQuality");
baton->heifLossless = sharp::AttrAsBool(options, "heifLossless"); baton->heifLossless = sharp::AttrAsBool(options, "heifLossless");
baton->heifCompression = static_cast<VipsForeignHeifCompression>( baton->heifCompression = sharp::AttrAsEnum<VipsForeignHeifCompression>(
vips_enum_from_nick(nullptr, VIPS_TYPE_FOREIGN_HEIF_COMPRESSION, options, "heifCompression", VIPS_TYPE_FOREIGN_HEIF_COMPRESSION);
sharp::AttrAsStr(options, "heifCompression").data()));
baton->heifEffort = sharp::AttrAsUint32(options, "heifEffort"); baton->heifEffort = sharp::AttrAsUint32(options, "heifEffort");
baton->heifChromaSubsampling = sharp::AttrAsStr(options, "heifChromaSubsampling"); baton->heifChromaSubsampling = sharp::AttrAsStr(options, "heifChromaSubsampling");
// Raw output baton->jxlDistance = sharp::AttrAsDouble(options, "jxlDistance");
baton->rawDepth = static_cast<VipsBandFormat>( baton->jxlDecodingTier = sharp::AttrAsUint32(options, "jxlDecodingTier");
vips_enum_from_nick(nullptr, VIPS_TYPE_BAND_FORMAT, baton->jxlEffort = sharp::AttrAsUint32(options, "jxlEffort");
sharp::AttrAsStr(options, "rawDepth").data())); baton->jxlLossless = sharp::AttrAsBool(options, "jxlLossless");
baton->rawDepth = sharp::AttrAsEnum<VipsBandFormat>(options, "rawDepth", VIPS_TYPE_BAND_FORMAT);
// Animated output properties // Animated output properties
if (sharp::HasAttr(options, "loop")) { if (sharp::HasAttr(options, "loop")) {
baton->loop = sharp::AttrAsUint32(options, "loop"); baton->loop = sharp::AttrAsUint32(options, "loop");
@@ -1565,24 +1618,19 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
if (sharp::HasAttr(options, "delay")) { if (sharp::HasAttr(options, "delay")) {
baton->delay = sharp::AttrAsInt32Vector(options, "delay"); baton->delay = sharp::AttrAsInt32Vector(options, "delay");
} }
// Tile output
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");
baton->tileBackground = sharp::AttrAsVectorOfDouble(options, "tileBackground"); baton->tileBackground = sharp::AttrAsVectorOfDouble(options, "tileBackground");
baton->tileSkipBlanks = sharp::AttrAsInt32(options, "tileSkipBlanks"); baton->tileSkipBlanks = sharp::AttrAsInt32(options, "tileSkipBlanks");
baton->tileContainer = static_cast<VipsForeignDzContainer>( baton->tileContainer = sharp::AttrAsEnum<VipsForeignDzContainer>(
vips_enum_from_nick(nullptr, VIPS_TYPE_FOREIGN_DZ_CONTAINER, options, "tileContainer", VIPS_TYPE_FOREIGN_DZ_CONTAINER);
sharp::AttrAsStr(options, "tileContainer").data())); baton->tileLayout = sharp::AttrAsEnum<VipsForeignDzLayout>(options, "tileLayout", VIPS_TYPE_FOREIGN_DZ_LAYOUT);
baton->tileLayout = static_cast<VipsForeignDzLayout>(
vips_enum_from_nick(nullptr, VIPS_TYPE_FOREIGN_DZ_LAYOUT,
sharp::AttrAsStr(options, "tileLayout").data()));
baton->tileFormat = sharp::AttrAsStr(options, "tileFormat"); baton->tileFormat = sharp::AttrAsStr(options, "tileFormat");
baton->tileDepth = static_cast<VipsForeignDzDepth>( baton->tileDepth = sharp::AttrAsEnum<VipsForeignDzDepth>(options, "tileDepth", VIPS_TYPE_FOREIGN_DZ_DEPTH);
vips_enum_from_nick(nullptr, VIPS_TYPE_FOREIGN_DZ_DEPTH,
sharp::AttrAsStr(options, "tileDepth").data()));
baton->tileCentre = sharp::AttrAsBool(options, "tileCentre"); baton->tileCentre = sharp::AttrAsBool(options, "tileCentre");
baton->tileId = sharp::AttrAsStr(options, "tileId"); baton->tileId = sharp::AttrAsStr(options, "tileId");
baton->tileBasename = sharp::AttrAsStr(options, "tileBasename");
// Force random access for certain operations // Force random access for certain operations
if (baton->input->access == VIPS_ACCESS_SEQUENTIAL) { if (baton->input->access == VIPS_ACCESS_SEQUENTIAL) {

View File

@@ -67,6 +67,7 @@ struct PipelineBaton {
int width; int width;
int height; int height;
int channels; int channels;
VipsKernel kernel;
sharp::Canvas canvas; sharp::Canvas canvas;
int position; int position;
std::vector<double> resizeBackground; std::vector<double> resizeBackground;
@@ -75,7 +76,6 @@ struct PipelineBaton {
int cropOffsetTop; int cropOffsetTop;
bool premultiplied; bool premultiplied;
bool tileCentre; bool tileCentre;
std::string kernel;
bool fastShrinkOnLoad; bool fastShrinkOnLoad;
double tintA; double tintA;
double tintB; double tintB;
@@ -90,15 +90,19 @@ struct PipelineBaton {
double lightness; double lightness;
int medianSize; int medianSize;
double sharpenSigma; double sharpenSigma;
double sharpenFlat; double sharpenM1;
double sharpenJagged; double sharpenM2;
double sharpenX1;
double sharpenY2;
double sharpenY3;
int threshold; int threshold;
bool thresholdGrayscale; bool thresholdGrayscale;
std::vector<double> trimBackground;
double trimThreshold; double trimThreshold;
int trimOffsetLeft; int trimOffsetLeft;
int trimOffsetTop; int trimOffsetTop;
double linearA; std::vector<double> linearA;
double linearB; std::vector<double> linearB;
double gamma; double gamma;
double gammaOut; double gammaOut;
bool greyscale; bool greyscale;
@@ -126,7 +130,7 @@ struct PipelineBaton {
double affineIdy; double affineIdy;
double affineOdx; double affineOdx;
double affineOdy; double affineOdy;
vips::VInterpolate affineInterpolator; std::string affineInterpolator;
int jpegQuality; int jpegQuality;
bool jpegProgressive; bool jpegProgressive;
std::string jpegChromaSubsampling; std::string jpegChromaSubsampling;
@@ -154,9 +158,14 @@ struct PipelineBaton {
bool webpLossless; bool webpLossless;
bool webpSmartSubsample; bool webpSmartSubsample;
int webpEffort; int webpEffort;
bool webpMinSize;
bool webpMixed;
int gifBitdepth; int gifBitdepth;
int gifEffort; int gifEffort;
double gifDither; double gifDither;
double gifInterFrameMaxError;
double gifInterPaletteMaxError;
bool gifReoptimise;
int tiffQuality; int tiffQuality;
VipsForeignTiffCompression tiffCompression; VipsForeignTiffCompression tiffCompression;
VipsForeignTiffPredictor tiffPredictor; VipsForeignTiffPredictor tiffPredictor;
@@ -173,6 +182,10 @@ struct PipelineBaton {
int heifEffort; int heifEffort;
std::string heifChromaSubsampling; std::string heifChromaSubsampling;
bool heifLossless; bool heifLossless;
double jxlDistance;
int jxlDecodingTier;
int jxlEffort;
bool jxlLossless;
VipsBandFormat rawDepth; VipsBandFormat rawDepth;
std::string err; std::string err;
bool withMetadata; bool withMetadata;
@@ -206,6 +219,7 @@ struct PipelineBaton {
int tileSkipBlanks; int tileSkipBlanks;
VipsForeignDzDepth tileDepth; VipsForeignDzDepth tileDepth;
std::string tileId; std::string tileId;
std::string tileBasename;
std::unique_ptr<double[]> recombMatrix; std::unique_ptr<double[]> recombMatrix;
PipelineBaton(): PipelineBaton():
@@ -214,6 +228,7 @@ struct PipelineBaton {
topOffsetPre(-1), topOffsetPre(-1),
topOffsetPost(-1), topOffsetPost(-1),
channels(0), channels(0),
kernel(VIPS_KERNEL_LANCZOS3),
canvas(sharp::Canvas::CROP), canvas(sharp::Canvas::CROP),
position(0), position(0),
resizeBackground{ 0.0, 0.0, 0.0, 255.0 }, resizeBackground{ 0.0, 0.0, 0.0, 255.0 },
@@ -234,15 +249,19 @@ struct PipelineBaton {
lightness(0), lightness(0),
medianSize(0), medianSize(0),
sharpenSigma(0.0), sharpenSigma(0.0),
sharpenFlat(1.0), sharpenM1(1.0),
sharpenJagged(2.0), sharpenM2(2.0),
sharpenX1(2.0),
sharpenY2(10.0),
sharpenY3(20.0),
threshold(0), threshold(0),
thresholdGrayscale(true), thresholdGrayscale(true),
trimBackground{},
trimThreshold(0.0), trimThreshold(0.0),
trimOffsetLeft(0), trimOffsetLeft(0),
trimOffsetTop(0), trimOffsetTop(0),
linearA(1.0), linearA{},
linearB(0.0), linearB{},
gamma(0.0), gamma(0.0),
greyscale(false), greyscale(false),
normalise(false), normalise(false),
@@ -268,7 +287,7 @@ struct PipelineBaton {
affineIdy(0), affineIdy(0),
affineOdx(0), affineOdx(0),
affineOdy(0), affineOdy(0),
affineInterpolator(vips::VInterpolate::new_from_name("bicubic")), affineInterpolator("bicubic"),
jpegQuality(80), jpegQuality(80),
jpegProgressive(false), jpegProgressive(false),
jpegChromaSubsampling("4:2:0"), jpegChromaSubsampling("4:2:0"),
@@ -296,6 +315,14 @@ struct PipelineBaton {
webpLossless(false), webpLossless(false),
webpSmartSubsample(false), webpSmartSubsample(false),
webpEffort(4), webpEffort(4),
webpMinSize(false),
webpMixed(false),
gifBitdepth(8),
gifEffort(7),
gifDither(1.0),
gifInterFrameMaxError(0.0),
gifInterPaletteMaxError(3.0),
gifReoptimise(false),
tiffQuality(80), tiffQuality(80),
tiffCompression(VIPS_FOREIGN_TIFF_COMPRESSION_JPEG), tiffCompression(VIPS_FOREIGN_TIFF_COMPRESSION_JPEG),
tiffPredictor(VIPS_FOREIGN_TIFF_PREDICTOR_HORIZONTAL), tiffPredictor(VIPS_FOREIGN_TIFF_PREDICTOR_HORIZONTAL),
@@ -312,6 +339,10 @@ struct PipelineBaton {
heifEffort(4), heifEffort(4),
heifChromaSubsampling("4:4:4"), heifChromaSubsampling("4:4:4"),
heifLossless(false), heifLossless(false),
jxlDistance(1.0),
jxlDecodingTier(0),
jxlEffort(7),
jxlLossless(false),
rawDepth(VIPS_FORMAT_UCHAR), rawDepth(VIPS_FORMAT_UCHAR),
withMetadata(false), withMetadata(false),
withMetadataOrientation(-1), withMetadataOrientation(-1),

View File

@@ -13,7 +13,6 @@
// limitations under the License. // limitations under the License.
#include <napi.h> #include <napi.h>
#include <cstdlib>
#include <vips/vips8> #include <vips/vips8>
#include "common.h" #include "common.h"
@@ -22,16 +21,7 @@
#include "utilities.h" #include "utilities.h"
#include "stats.h" #include "stats.h"
#if defined(_MSC_VER) && _MSC_VER >= 1400 // MSVC 2005/8
static void empty_invalid_parameter_handler(const wchar_t* expression,
const wchar_t* function, const wchar_t* file, unsigned int line,
uintptr_t reserved) {
// No-op.
}
#endif
static void* sharp_vips_init(void*) { static void* sharp_vips_init(void*) {
g_setenv("VIPS_MIN_STACK_SIZE", "2m", FALSE);
vips_init("sharp"); vips_init("sharp");
return nullptr; return nullptr;
} }
@@ -43,13 +33,6 @@ Napi::Object init(Napi::Env env, Napi::Object exports) {
g_log_set_handler("VIPS", static_cast<GLogLevelFlags>(G_LOG_LEVEL_WARNING), g_log_set_handler("VIPS", static_cast<GLogLevelFlags>(G_LOG_LEVEL_WARNING),
static_cast<GLogFunc>(sharp::VipsWarningCallback), nullptr); static_cast<GLogFunc>(sharp::VipsWarningCallback), nullptr);
// Tell the CRT to not exit the application when an invalid parameter is
// passed. The main issue is that invalid FDs will trigger this behaviour.
// See: https://github.com/libvips/libvips/pull/2571.
#if defined(_MSC_VER) && _MSC_VER >= 1400 // MSVC 2005/8
_set_invalid_parameter_handler(empty_invalid_parameter_handler);
#endif
// Methods available to JavaScript // Methods available to JavaScript
exports.Set("metadata", Napi::Function::New(env, metadata)); exports.Set("metadata", Napi::Function::New(env, metadata));
exports.Set("pipeline", Napi::Function::New(env, pipeline)); exports.Set("pipeline", Napi::Function::New(env, pipeline));

View File

@@ -176,6 +176,7 @@ Napi::Value stats(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>());
baton->input->access = VIPS_ACCESS_RANDOM;
// Function to notify of libvips warnings // Function to notify of libvips warnings
Napi::Function debuglog = options.Get("debuglog").As<Napi::Function>(); Napi::Function debuglog = options.Get("debuglog").As<Napi::Function>();

View File

@@ -115,17 +115,28 @@ 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" "ppm", "fits", "gif", "svg", "heif", "pdf", "vips", "jp2k", "jxl"
}) { }) {
// Input // Input
Napi::Boolean hasInputFile = const VipsObjectClass *oc = vips_class_find("VipsOperation", (f + "load").c_str());
Napi::Boolean::New(env, vips_type_find("VipsOperation", (f + "load").c_str())); Napi::Boolean hasInputFile = Napi::Boolean::New(env, oc);
Napi::Boolean hasInputBuffer = Napi::Boolean hasInputBuffer =
Napi::Boolean::New(env, vips_type_find("VipsOperation", (f + "load_buffer").c_str())); Napi::Boolean::New(env, vips_type_find("VipsOperation", (f + "load_buffer").c_str()));
Napi::Object input = Napi::Object::New(env); Napi::Object input = Napi::Object::New(env);
input.Set("file", hasInputFile); input.Set("file", hasInputFile);
input.Set("buffer", hasInputBuffer); input.Set("buffer", hasInputBuffer);
input.Set("stream", hasInputBuffer); input.Set("stream", hasInputBuffer);
if (hasInputFile) {
const VipsForeignClass *fc = VIPS_FOREIGN_CLASS(oc);
if (fc->suffs) {
Napi::Array fileSuffix = Napi::Array::New(env);
const char **suffix = fc->suffs;
for (int i = 0; *suffix; i++, suffix++) {
fileSuffix.Set(i, Napi::String::New(env, *suffix));
}
input.Set("fileSuffix", fileSuffix);
}
}
// Output // Output
Napi::Boolean hasOutputFile = Napi::Boolean hasOutputFile =
Napi::Boolean::New(env, vips_type_find("VipsOperation", (f + "save").c_str())); Napi::Boolean::New(env, vips_type_find("VipsOperation", (f + "save").c_str()));

21
test/beforeEach.js Normal file
View File

@@ -0,0 +1,21 @@
'use strict';
const sharp = require('../');
const usingCache = !process.env.G_DEBUG;
const usingSimd = !process.env.VIPS_NOVECTOR;
const concurrency = Number(process.env.VIPS_CONCURRENCY) || 0;
exports.mochaHooks = {
beforeEach () {
sharp.cache(usingCache);
sharp.simd(usingSimd);
sharp.concurrency(concurrency);
},
afterEach () {
if (global.gc) {
global.gc();
}
}
};

26
test/bench/Dockerfile Normal file
View File

@@ -0,0 +1,26 @@
FROM ubuntu:22.04
ARG BRANCH=main
# Install basic dependencies
RUN apt-get -y update && apt-get install -y build-essential curl git
# Install latest Node.js LTS
RUN curl -fsSL https://deb.nodesource.com/setup_16.x | bash -
RUN apt-get install -y nodejs
# Install benchmark dependencies
RUN apt-get install -y imagemagick libmagick++-dev graphicsmagick
# Install sharp
RUN mkdir /tmp/sharp
RUN cd /tmp && git clone --single-branch --branch $BRANCH https://github.com/lovell/sharp.git
RUN cd /tmp/sharp && npm install --build-from-source
# Install benchmark test
RUN cd /tmp/sharp/test/bench && npm install --omit optional
RUN cat /etc/os-release | grep VERSION=
RUN node -v
WORKDIR /tmp/sharp/test/bench
CMD [ "node", "perf" ]

View File

@@ -7,16 +7,19 @@
"scripts": { "scripts": {
"test": "node perf && node random && node parallel" "test": "node perf && node random && node parallel"
}, },
"devDependencies": { "dependencies": {
"@squoosh/cli": "0.7.2", "@squoosh/cli": "0.7.2",
"@squoosh/lib": "0.4.0", "@squoosh/lib": "0.4.0",
"async": "3.2.3", "async": "3.2.4",
"benchmark": "2.1.4", "benchmark": "2.1.4",
"gm": "1.23.1", "gm": "1.25.0",
"imagemagick": "0.1.3", "imagemagick": "0.1.3",
"jimp": "0.16.1", "jimp": "0.16.2",
"mapnik": "4.5.9", "semver": "7.3.8"
"semver": "7.3.5" },
"optionalDependencies": {
"@tensorflow/tfjs-node": "4.1.0",
"mapnik": "4.5.9"
}, },
"license": "Apache-2.0", "license": "Apache-2.0",
"engines": { "engines": {

View File

@@ -5,16 +5,24 @@ const fs = require('fs');
const { exec } = require('child_process'); const { exec } = require('child_process');
const async = require('async'); const async = require('async');
const assert = require('assert');
const Benchmark = require('benchmark'); const Benchmark = require('benchmark');
const safeRequire = (name) => {
try {
return require(name);
} catch (err) {}
return null;
};
// Contenders // Contenders
const sharp = require('../../'); const sharp = require('../../');
const gm = require('gm'); const gm = require('gm');
const imagemagick = require('imagemagick'); const imagemagick = require('imagemagick');
const mapnik = require('mapnik'); const mapnik = safeRequire('mapnik');
const jimp = require('jimp'); const jimp = require('jimp');
const squoosh = require('@squoosh/lib'); const squoosh = require('@squoosh/lib');
process.env.TF_CPP_MIN_LOG_LEVEL = 1;
const tfjs = safeRequire('@tensorflow/tfjs-node');
const fixtures = require('../fixtures'); const fixtures = require('../fixtures');
@@ -137,7 +145,7 @@ async.series({
} }
}); });
// mapnik // mapnik
jpegSuite.add('mapnik-file-file', { mapnik && jpegSuite.add('mapnik-file-file', {
defer: true, defer: true,
fn: function (deferred) { fn: function (deferred) {
mapnik.Image.open(fixtures.inputJpg, function (err, img) { mapnik.Image.open(fixtures.inputJpg, function (err, img) {
@@ -212,11 +220,10 @@ async.series({
.filter('Lanczos') .filter('Lanczos')
.resize(width, height) .resize(width, height)
.quality(80) .quality(80)
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -243,16 +250,33 @@ async.series({
.filter('Lanczos') .filter('Lanczos')
.resize(width, height) .resize(width, height)
.quality(80) .quality(80)
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
} }
}); });
// tfjs
tfjs && jpegSuite.add('tfjs-node-buffer-buffer', {
defer: true,
fn: function (deferred) {
const decoded = tfjs.node.decodeJpeg(inputJpgBuffer);
const resized = tfjs.image.resizeBilinear(decoded, [height, width]);
tfjs
.node
.encodeJpeg(resized, 'rgb', 80)
.then(function () {
deferred.resolve();
tfjs.disposeVariables();
})
.catch(function (err) {
throw err;
});
}
});
// sharp // sharp
jpegSuite.add('sharp-buffer-file', { jpegSuite.add('sharp-buffer-file', {
defer: true, defer: true,
@@ -272,11 +296,10 @@ async.series({
fn: function (deferred) { fn: function (deferred) {
sharp(inputJpgBuffer) sharp(inputJpgBuffer)
.resize(width, height) .resize(width, height)
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -311,11 +334,10 @@ async.series({
fn: function (deferred) { fn: function (deferred) {
sharp(fixtures.inputJpg) sharp(fixtures.inputJpg)
.resize(width, height) .resize(width, height)
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -326,8 +348,7 @@ async.series({
sharp(inputJpgBuffer) sharp(inputJpgBuffer)
.resize(width, height) .resize(width, height)
.toBuffer() .toBuffer()
.then(function (buffer) { .then(function () {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
}) })
.catch(function (err) { .catch(function (err) {
@@ -350,11 +371,10 @@ async.series({
sharp(inputJpgBuffer) sharp(inputJpgBuffer)
.resize(width, height) .resize(width, height)
.sharpen() .sharpen()
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -365,11 +385,10 @@ async.series({
sharp(inputJpgBuffer) sharp(inputJpgBuffer)
.resize(width, height) .resize(width, height)
.sharpen(3, 1, 3) .sharpen(3, 1, 3)
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -380,11 +399,10 @@ async.series({
sharp(inputJpgBuffer) sharp(inputJpgBuffer)
.resize(width, height) .resize(width, height)
.blur() .blur()
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -395,11 +413,10 @@ async.series({
sharp(inputJpgBuffer) sharp(inputJpgBuffer)
.resize(width, height) .resize(width, height)
.blur(3) .blur(3)
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -410,11 +427,10 @@ async.series({
sharp(inputJpgBuffer) sharp(inputJpgBuffer)
.resize(width, height) .resize(width, height)
.gamma() .gamma()
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -425,11 +441,10 @@ async.series({
sharp(inputJpgBuffer) sharp(inputJpgBuffer)
.resize(width, height) .resize(width, height)
.normalise() .normalise()
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -440,11 +455,10 @@ async.series({
sharp(inputJpgBuffer) sharp(inputJpgBuffer)
.resize(width, height) .resize(width, height)
.greyscale() .greyscale()
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -456,11 +470,10 @@ async.series({
.resize(width, height) .resize(width, height)
.gamma() .gamma()
.greyscale() .greyscale()
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -471,11 +484,10 @@ async.series({
sharp(inputJpgBuffer) sharp(inputJpgBuffer)
.resize(width, height) .resize(width, height)
.jpeg({ progressive: true }) .jpeg({ progressive: true })
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -486,11 +498,10 @@ async.series({
sharp(inputJpgBuffer) sharp(inputJpgBuffer)
.resize(width, height) .resize(width, height)
.jpeg({ chromaSubsampling: '4:4:4' }) .jpeg({ chromaSubsampling: '4:4:4' })
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -501,11 +512,10 @@ async.series({
sharp(inputJpgBuffer) sharp(inputJpgBuffer)
.rotate(90) .rotate(90)
.resize(width, height) .resize(width, height)
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -516,12 +526,11 @@ async.series({
sharp.simd(false); sharp.simd(false);
sharp(inputJpgBuffer) sharp(inputJpgBuffer)
.resize(width, height) .resize(width, height)
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
sharp.simd(true); sharp.simd(true);
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -531,11 +540,10 @@ async.series({
fn: function (deferred) { fn: function (deferred) {
sharp(inputJpgBuffer, { sequentialRead: true }) sharp(inputJpgBuffer, { sequentialRead: true })
.resize(width, height) .resize(width, height)
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -548,11 +556,10 @@ async.series({
fit: 'cover', fit: 'cover',
position: sharp.strategy.entropy position: sharp.strategy.entropy
}) })
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -565,11 +572,10 @@ async.series({
fit: 'cover', fit: 'cover',
position: sharp.strategy.attention position: sharp.strategy.attention
}) })
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -588,11 +594,10 @@ async.series({
fn: function (deferred) { fn: function (deferred) {
sharp(inputJpgBuffer) sharp(inputJpgBuffer)
.resize(width, height, { kernel: 'cubic' }) .resize(width, height, { kernel: 'cubic' })
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -602,11 +607,10 @@ async.series({
fn: function (deferred) { fn: function (deferred) {
sharp(inputJpgBuffer) sharp(inputJpgBuffer)
.resize(width, height, { kernel: 'lanczos2' }) .resize(width, height, { kernel: 'lanczos2' })
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -616,11 +620,10 @@ async.series({
fn: function (deferred) { fn: function (deferred) {
sharp(inputJpgBuffer) sharp(inputJpgBuffer)
.resize(width, height, { kernel: 'lanczos3' }) .resize(width, height, { kernel: 'lanczos3' })
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -681,7 +684,7 @@ async.series({
} }
}); });
// mapnik // mapnik
pngSuite.add('mapnik-file-file', { mapnik && pngSuite.add('mapnik-file-file', {
defer: true, defer: true,
fn: function (deferred) { fn: function (deferred) {
mapnik.Image.open(fixtures.inputPngAlphaPremultiplicationLarge, function (err, img) { mapnik.Image.open(fixtures.inputPngAlphaPremultiplicationLarge, function (err, img) {
@@ -774,11 +777,10 @@ async.series({
.resize(width, height) .resize(width, height)
.define('PNG:compression-level=6') .define('PNG:compression-level=6')
.define('PNG:compression-filter=0') .define('PNG:compression-filter=0')
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -807,11 +809,10 @@ async.series({
sharp(inputPngBuffer) sharp(inputPngBuffer)
.resize(width, height) .resize(width, height)
.png({ compressionLevel: 6 }) .png({ compressionLevel: 6 })
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -838,11 +839,10 @@ async.series({
sharp(fixtures.inputPngAlphaPremultiplicationLarge) sharp(fixtures.inputPngAlphaPremultiplicationLarge)
.resize(width, height) .resize(width, height)
.png({ compressionLevel: 6 }) .png({ compressionLevel: 6 })
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -854,11 +854,10 @@ async.series({
sharp(inputPngBuffer) sharp(inputPngBuffer)
.resize(width, height) .resize(width, height)
.png({ compressionLevel: 6, progressive: true }) .png({ compressionLevel: 6, progressive: true })
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -870,11 +869,10 @@ async.series({
sharp(inputPngBuffer) sharp(inputPngBuffer)
.resize(width, height) .resize(width, height)
.png({ adaptiveFiltering: true, compressionLevel: 6 }) .png({ adaptiveFiltering: true, compressionLevel: 6 })
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -886,11 +884,10 @@ async.series({
sharp(inputPngBuffer) sharp(inputPngBuffer)
.resize(width, height) .resize(width, height)
.png({ compressionLevel: 9 }) .png({ compressionLevel: 9 })
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -923,11 +920,10 @@ async.series({
fn: function (deferred) { fn: function (deferred) {
sharp(inputWebPBuffer) sharp(inputWebPBuffer)
.resize(width, height) .resize(width, height)
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -950,11 +946,10 @@ async.series({
fn: function (deferred) { fn: function (deferred) {
sharp(fixtures.inputWebP) sharp(fixtures.inputWebP)
.resize(width, height) .resize(width, height)
.toBuffer(function (err, buffer) { .toBuffer(function (err) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
assert.notStrictEqual(null, buffer);
deferred.resolve(); deferred.resolve();
} }
}); });
@@ -966,7 +961,9 @@ async.series({
}).run(); }).run();
} }
}, function (err, results) { }, function (err, results) {
assert(!err, err); if (err) {
throw err;
}
Object.keys(results).forEach(function (format) { Object.keys(results).forEach(function (format) {
if (results[format].toString().substr(0, 5) !== 'sharp') { if (results[format].toString().substr(0, 5) !== 'sharp') {
console.log('sharp was slower than ' + results[format] + ' for ' + format); console.log('sharp was slower than ' + results[format] + ' for ' + format);

13
test/bench/run-with-docker.sh Executable file
View File

@@ -0,0 +1,13 @@
#!/usr/bin/env bash
set -e
if ! type docker >/dev/null; then
echo "Please install docker"
exit 1
fi
BRANCH=$(git branch --show-current)
echo "Running sharp performance tests using $BRANCH branch"
docker build --build-arg "BRANCH=$BRANCH" -t sharp-test-bench .
docker run --rm -it sharp-test-bench

View File

@@ -1,6 +0,0 @@
#!/bin/sh
CPPFLAGS="--coverage" LDFLAGS="--coverage" npm rebuild
npm test
geninfo --no-external --base-directory src --output-file coverage/sharp.info build/Release/obj.target/sharp/src
genhtml --title sharp --demangle-cpp --output-directory coverage/sharp coverage/*.info

BIN
test/fixtures/65536-uint32-limit.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 510 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 812 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 794 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 222 B

After

Width:  |  Height:  |  Size: 320 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 197 B

After

Width:  |  Height:  |  Size: 292 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 197 B

After

Width:  |  Height:  |  Size: 292 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 194 B

After

Width:  |  Height:  |  Size: 286 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 192 B

After

Width:  |  Height:  |  Size: 285 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.6 KiB

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 270 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 265 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 277 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 424 KiB

After

Width:  |  Height:  |  Size: 424 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 943 KiB

After

Width:  |  Height:  |  Size: 943 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 161 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

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