Compare commits

..

2254 Commits
v0.0.1 ... main

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

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

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

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

Co-authored-by: Lovell Fuller <github@lovell.info>
2024-05-24 17:45:39 +01:00
Lovell Fuller
cc96c21e42 CI: Upgrade to macOS 12 (as 11 will be removed soon) 2024-05-21 11:40:11 +01:00
Lovell Fuller
1d344888ec Bump dep: emnapi 2024-05-21 11:39:41 +01:00
Lovell Fuller
bee235ee76 Docs: fix CSP 2024-05-21 11:39:08 +01:00
Lovell Fuller
19d0e272e6 Release v0.33.4 2024-05-16 12:48:29 +01:00
Lovell Fuller
16b764f1c1 Prerelease v0.33.4-rc.0 2024-05-16 12:16:41 +01:00
Lovell Fuller
1593ee3838 Bump devDeps 2024-05-16 12:15:49 +01:00
Lovell Fuller
668b5ba8bc Docs: changelog and credit for #4096 2024-05-14 16:59:20 +01:00
Adriaan Meuris
29336f4cc7
Ensure negate op occurs after profile conversion (#4096)
- Adds CMYK to CMYK profile conversion tests
- Fixes existing greyscale plus alpha test expectation
2024-05-13 12:23:11 +01:00
Lovell Fuller
b5fddd7c5e Install: log node-addon-api version if available 2024-05-10 10:43:15 +01:00
Lovell Fuller
da655a1859 Reduce default concurrency for musl thread over-subscription
https://github.com/lovell/sharp-libvips/issues/229
2024-04-30 19:23:44 +01:00
Lovell Fuller
93c615d39f Bump devDeps 2024-04-30 19:23:36 +01:00
Lovell Fuller
f325dc3ec9 Refactor to use C++ boolean literals rather than macros 2024-04-30 19:23:31 +01:00
Skyf0l
0fde71c783
Ensure all contributor email addresses are valid (#4088) 2024-04-28 18:17:44 +01:00
Lovell Fuller
9c8fbaa1cc Issue template: fix markdown links from a9e662e 2024-04-25 11:31:45 +01:00
Lovell Fuller
a9e662e612 Issue template: add a couple of the most commonly-reported problems
This should allow more people to help themselves and prevent
extraneous issues from being opened.
2024-04-25 11:25:14 +01:00
Lovell Fuller
ba843002be Docs: use libc flag for npm Linux cross-installs 2024-04-24 08:30:50 +01:00
Lovell Fuller
7f3d452bc5 Docs: changelog and credit for #4074 2024-04-19 15:21:21 +01:00
Kleis Auke Wolthuizen
aa8bc19362
Simplify StaySequential operation (#4074) 2024-04-19 14:47:49 +01:00
Lovell Fuller
36e60bf040 CI: Upgrade linux-s390x to Debian 11
Debian LTS does not include s390x and Debian 10 is EOL so this
platform will now require a minimum version of glibc 2.31.
2024-04-19 13:13:48 +01:00
Lovell Fuller
a1309aa3b8 Tighten constructor text property validation #4071 2024-04-19 12:48:47 +01:00
Lovell Fuller
3e8a0fc522 Ensure only one StaySequential operation per pipeline
This should reduce memory consumption for more complex pipelines
that combine multiple operations without sequential access support
e.g. flip and Gaussian blur.
2024-04-19 11:27:54 +01:00
Lovell Fuller
397ee492d9 Ensure extend op is sequential for multi-page TIFF #4069 2024-04-18 11:05:04 +01:00
Lovell Fuller
52b9dc0f63 Docs: add a few more stop-words 2024-04-11 10:31:38 +01:00
Lovell Fuller
a715c73fc2 Docs: remove GA, allow for possible use of CF 2024-04-11 10:23:27 +01:00
Lovell Fuller
579cf93030 Install: advanced option to force global libvips #4060 2024-04-10 09:25:53 +01:00
Lovell Fuller
f67228e5ea Remove experimental status from pipelineColourspace 2024-04-09 22:32:17 +01:00
Lovell Fuller
6257994746 Expose bilinear resize kernel and improve docs #4061 2024-04-09 22:21:52 +01:00
Lovell Fuller
7950fc0ea3 Docs: changelog entry for #4048 2024-04-02 19:23:11 +01:00
Lovell Fuller
fc93ab3b82 Bump devDeps 2024-04-02 19:22:42 +01:00
ike
0981b24f60
TypeScript: add missing definitions for OverlayOptions (#4048) 2024-04-02 14:42:10 +01:00
Lovell Fuller
02fd565476 CI: bump write-file-action 2024-03-29 13:01:51 +00:00
Lovell Fuller
e55bb93b10 Bump devDeps 2024-03-29 13:01:32 +00:00
Lovell Fuller
55466f122c Release v0.33.3 2024-03-23 11:58:44 +00:00
Lovell Fuller
ede8217ab3 Prerelease v0.33.3-rc.0 2024-03-22 12:41:51 +00:00
Lovell Fuller
2689fb4e65 Bump deps 2024-03-22 11:19:08 +00:00
Lovell Fuller
eaf31a59e5 Docs: changelog and credit for #4036 2024-03-21 18:34:35 +00:00
Lovell Fuller
aa1bbcb5c1 Guard heif bitdepth property for prebuilt binaries 2024-03-21 18:33:57 +00:00
Mert
3c26080c39
Add bitdepth option to heif output (#4036)
Prebuilt binaries support only AVIF with a bitdepth of 8
2024-03-21 14:36:17 +00:00
Lovell Fuller
dc07fd4e9c Upgrade to libvips v8.15.2 2024-03-18 15:55:01 +00:00
Lovell Fuller
7bc74feb11 Ensure clone takes deep copy of options #4029 2024-03-17 09:42:21 +00:00
Lovell Fuller
c5f318ed4d Docs: add changelog and credit for #4028 2024-03-17 09:10:42 +00:00
Aaron Che
8fbb1cd154
Ensure text.wrap property can accept word-char as value (#4028) 2024-03-17 08:15:03 +00:00
Lovell Fuller
88aee8a887 Bump devDeps 2024-03-06 21:00:44 +00:00
Lovell Fuller
0f77b18078 Rename internal property name to better reflect use
This property is used for the processing pipeline colourspace
rather than the input colourspace, so the name was confusing.
2024-03-06 20:49:47 +00:00
Lovell Fuller
3eeaee71c0 Ensure pipelineColourspace handles CMYK profiles #3906 2024-03-06 20:20:04 +00:00
Lovell Fuller
045d54e2e6 Docs: include use of fetch() in Stream-based example 2024-02-28 13:15:47 +00:00
Lovell Fuller
75fedf1b75 Ensure keepIccProfile retains P3 input profiles #4008 2024-02-26 15:23:50 +00:00
Lovell Fuller
debdacb726 Bump deps 2024-02-23 09:11:35 +00:00
Lovell Fuller
1c8ae67ed2 CI: Upgrade OS on Linux ARM64 runners 2024-02-23 09:08:11 +00:00
Lovell Fuller
0eb57698ec Docs: clarify how to achieve 16-bit PNG output 2024-02-14 10:03:18 +00:00
Lovell Fuller
bc95531f2d Docs: clarify skipBlanks default for tile-based output 2024-02-13 22:40:10 +00:00
Lovell Fuller
60f4048d6c CI: Upgrade to Python 3.12 2024-02-11 20:45:16 +00:00
Lovell Fuller
fb70fbb09f Ensure keepIccProfile retains CMYK input profiles #3906 2024-02-11 20:10:18 +00:00
idchlife
fc439bedf1 Docs: add section to help those bundling via Vite 2024-02-08 09:31:28 +00:00
Lovell Fuller
26d0b7147d Bump devDeps 2024-02-03 21:22:35 +00:00
Lovell Fuller
af6aa8a690 CI: Add macOS 14 (ARM64)
Replaces runner previously and very kindly donated by MacStadium
2024-02-01 13:21:43 +00:00
hugo-syn
bd4f1abba2
TypeScript: Fix typo s/introducted/introduced/ (#3962) 2024-01-19 11:07:41 +00:00
hugo-syn
d2656a3679
Tests: fix typo s/implict/implicit (#3961) 2024-01-19 10:30:04 +00:00
Niels de Vos
a3b45ceccc
Docs: update link to new JSDoc site (#3950) 2024-01-16 08:20:45 +00:00
Lovell Fuller
0dcc7d50a8 Docs: add note about libvips 8.15.1 upgrade 2024-01-12 11:25:13 +00:00
Lovell Fuller
bcb22af034 Release v0.33.2 2024-01-12 10:58:45 +00:00
Lovell Fuller
d04dc62666 Prerelease v0.33.2-rc.1 2024-01-12 09:04:00 +00:00
Lovell Fuller
c30d355f97 CI: Fix npm smoke test expectation
libvips v8.15.1 added jfif to suffixes
2024-01-11 18:47:24 +00:00
Lovell Fuller
49cb148b38 Prerelease v0.33.2-rc.0 2024-01-11 16:43:59 +00:00
Lovell Fuller
3bc31a8b20 CI: Verify emscripten versions match 2024-01-11 16:23:12 +00:00
Kleis Auke Wolthuizen
c28523e70e
CI: Update Emscripten Docker image to 3.1.51 (#3907) 2024-01-11 16:21:53 +00:00
Lovell Fuller
278f393f74 Upgrade to libvips v8.15.1 2024-01-11 15:44:57 +00:00
Lovell Fuller
cbf68c1395 Improve error for unsupported multi-page rotation #3940 2024-01-11 11:59:01 +00:00
Lovell Fuller
45e8071599 Add runtime check for outdated Node.js version 2024-01-10 13:50:20 +00:00
Lovell Fuller
b96389d975 Docs: refresh index 2024-01-10 13:50:09 +00:00
Erika
a77ac6ae25
Docs: correct semver for supported Node.js versions (#3937) 2024-01-10 09:06:40 +00:00
Lovell Fuller
9bcf399b4c Ensure extend op stays sequential when copying px #3928 2024-01-04 09:24:41 +00:00
Lovell Fuller
4aacee8055 Docs: include img-scoped packages in electron asarUnpack 2024-01-04 08:57:26 +00:00
Lovell Fuller
0b18aeff62 CI: Remove use of nodesource repos 2024-01-03 11:40:42 +00:00
Lovell Fuller
bed1c2ac18 Bump deps 2024-01-03 10:01:29 +00:00
Lovell Fuller
8cd832656b Docs: add electron to bundlers section
If you're using asar, you'll also need to configure asarUnpack.
2024-01-03 09:40:21 +00:00
Lovell Fuller
0499f59e71 Docs: add minimum dep versions to build from source 2023-12-29 10:01:56 +00:00
Lovell Fuller
1fa59bf9b3 Remove any suggestion to --force install
This is probably a bad idea in the long run as versions can
get out of sync and other genuine warnings might be ignored.
2023-12-28 11:24:46 +00:00
Lovell Fuller
db40ee6912 Docs: add note about Lambda lacking symlink support
Some package managers use symlinks. If you need to deploy to AWS,
please do not use symlinks.
2023-12-28 11:23:26 +00:00
Lovell Fuller
02b98b8e1b Issue template: ask for complete error message
The error messages generated by sharp are designed to provide
people with as much information about the situation as possible.
If someone is asked to copy/paste the error, it's more likely
they might actually read it, which might then allow them to help
themselves without the need to open a new issue.
2023-12-27 09:23:21 +00:00
Lovell Fuller
31fef216e4 Docs: changelog entry for #3914 2023-12-27 09:21:23 +00:00
Abhishek V
77ab5d7a51
TypeScript: add definition for keepMetadata (#3914) 2023-12-24 10:24:54 +00:00
Lovell Fuller
cd5cf7ce2d Docs: direct cross-platform Lambda users to relevant section
This should reduce repetition in the docs, ensuring any users
wishing to support multi or cross platform installs have one
place to look.
2023-12-19 16:43:21 +00:00
Lovell Fuller
39cb9d9a6c Issue template: yarn pnp is now supported 2023-12-17 20:47:23 +00:00
Lovell Fuller
4919bc5134 Release v0.33.1 2023-12-17 20:10:30 +00:00
Lovell Fuller
a4e64eb01f Prerelease v0.33.1-rc.3 2023-12-17 19:32:36 +00:00
Lovell Fuller
328b18df88 CI: Split yarn pnp package tests into separate jobs 2023-12-17 19:00:14 +00:00
Lovell Fuller
5e7bf32e5e Docs: refresh index and homepage link 2023-12-17 18:51:49 +00:00
Lovell Fuller
04403f4e5f Prerelease v0.33.1-rc.2 2023-12-17 17:13:34 +00:00
Lovell Fuller
420e0822b4 CI: Pin Node.js 18 to avoid npm 10 on 32-bit Windows
npm 10 seems to be opening thousands of network connections,
leading to resource starvation in Node.js 18. This does not
appear to impact Node.js 20.
2023-12-17 16:53:12 +00:00
Lovell Fuller
f7a3ea6415 Prerelease v0.33.1-rc.1 2023-12-17 10:35:27 +00:00
Lovell Fuller
f28e79ef4f Improve resilience of installation check 2023-12-17 09:46:28 +00:00
Lovell Fuller
5cd787bf85 CI: Upgrade to latest FreeBSD, improve test resilience 2023-12-17 09:39:05 +00:00
Lovell Fuller
021d637fd6 Docs: changelog and credit for #3897 2023-12-15 19:08:14 +00:00
Tamás András Horváth
2e14096af7
Ensure VIPS_NOVECTOR env var is respected (#3897) 2023-12-15 18:51:32 +00:00
Lovell Fuller
fe2b298a2f Emit warning for invalid ICC profile #3895 2023-12-15 12:13:57 +00:00
Lovell Fuller
c9e3996007 Tests: attempt to reduce chance of race condition 2023-12-13 13:22:59 +00:00
Lovell Fuller
3a0c375692 Docs: improve cross-platform help messaging
tldr; don't use npm for multi-platform installs
2023-12-13 12:59:14 +00:00
Lovell Fuller
c5eaeb2ddb Add help when possibly using an unsupported libc 2023-12-12 21:01:09 +00:00
Lovell Fuller
19fa4cd1d3 Docs: update liborc references to highway 2023-12-12 12:01:41 +00:00
Lovell Fuller
0adf7ef16f CI: Ensure Yarn pnp linker uses ESM 2023-12-12 12:01:11 +00:00
Lovell Fuller
8f7fb96a44 Prerelease v0.33.1-rc.0 2023-12-12 09:12:57 +00:00
Lovell Fuller
9e3b021b1a Add help text for Node.js snap failures
The official Node.js Snap as distributed via the Ubuntu Snap Store
does not provide support for native modules.

Sometimes, if the version of the core matches the version of the
underlying OS, then it will appear to work.

There are quite a few open issues relating to this in the
nodejs/snap repo.
2023-12-11 22:56:51 +00:00
Lovell Fuller
25164d4cef Tests: tighten yarn locator test for multi-platform 2023-12-11 21:51:20 +00:00
Lovell Fuller
516b1ec332 Improve help text displayed on failure of require 2023-12-11 21:28:09 +00:00
Lovell Fuller
95ba045a69 Tests: improve yarn locator coverage 2023-12-11 21:14:40 +00:00
Lovell Fuller
6e02f9288e CI: Add package test for Yarn Plug'n'Play 2023-12-10 20:02:17 +00:00
Lovell Fuller
a584ae093e Allow yarn locator hash calc to fail e.g. Windows 2023-12-10 19:51:21 +00:00
Lovell Fuller
1592f96b7b Add support for Yarn Plug'n'Play filesystem layout #3888 2023-12-10 19:38:03 +00:00
Lovell Fuller
004fff975f Docs: clarify yarn v1 vs yarn v3+ installation #3871 2023-12-04 08:46:48 +00:00
Lovell Fuller
4d049ee8f5 Docs: make use of optional dependencies even clearer 2023-12-02 09:20:42 +00:00
Lovell Fuller
c80e92fa16 Docs: highlight that optional deps must be allowed 2023-11-30 12:11:07 +00:00
Lovell Fuller
545e09fad2 Release v0.33.0 2023-11-29 11:55:31 +00:00
Lovell Fuller
133dc56ff4 Docs: note lack of native text rendering with Wasm 2023-11-28 09:08:52 +00:00
Lovell Fuller
9c877d93fa Docs: info about how animated images are loaded 2023-11-27 20:35:53 +00:00
Lovell Fuller
7ad86fed03 Docs: package-manager howto for cross-platform install 2023-11-27 09:30:21 +00:00
Lovell Fuller
31cf07f0ba Docs: update perf results for next release
Switch from orc to highway is ~25% faster
2023-11-26 14:41:44 +00:00
Lovell Fuller
4ffb48711a Tests: update benchmark deps/env to latest 2023-11-24 13:22:11 +00:00
Lovell Fuller
3da96a86e6 Docs: clarify that Wasm requires Node.js compatible runtime 2023-11-24 12:00:14 +00:00
Lovell Fuller
45ed9ea9bf Tests: update leak config/suppressions 2023-11-24 11:59:29 +00:00
Lovell Fuller
61057f25bc Prerelease v0.33.0-rc.2 2023-11-22 12:17:25 +00:00
Lovell Fuller
68ef72cb61 CI: allow failure when attempting to rm native binary 2023-11-22 12:00:10 +00:00
Lovell Fuller
ef32dccb83 Prerelease v0.33.0-rc.1 2023-11-22 10:16:48 +00:00
Lovell Fuller
e78200cc84
Increase control over output metadata (#3856)
Add withX and keepX functions to take advantage of
libvips 8.15.0 new 'keep' metadata feature.
2023-11-22 09:03:57 +00:00
Lovell Fuller
3f7313d031
Improve tint luminance with weighting function (#3859)
Co-authored-by: John Cupitt <jcupitt@gmail.com>
2023-11-19 13:19:34 +00:00
Lovell Fuller
139e4b9f65 Show cast-function-type compiler warnings 2023-11-16 11:18:58 +00:00
Lovell Fuller
9680f00ddd CI: Ensure Wasm packaging test uses Wasm package 2023-11-15 19:28:18 +00:00
Lovell Fuller
0b0ebfe6f8 Bump dep: emnapi 2023-11-13 09:11:58 +00:00
Lovell Fuller
5aadb8294c Upgrade to libvips v8.15.0 2023-11-12 17:03:38 +00:00
Lovell Fuller
ace1681886 Packaging: use correct package when pop from release 2023-11-10 17:26:21 +00:00
Pooya Parsa
75ef61a958
Correctly check for when sharp is unavailable (#3848) 2023-11-10 15:30:01 +00:00
Lovell Fuller
2dba5b5451 Prerelease v0.33.0-alpha.11 2023-11-09 15:39:10 +00:00
Lovell Fuller
a8f68ba7f0
Add infrastructure to build and publish as wasm32 (#3840)
Co-authored-by: Ingvar Stepanyan <me@rreverser.com>
2023-11-09 14:46:07 +00:00
Lovell Fuller
475bf16b09 Tests: increase flaky text test range even further 2023-11-08 14:51:31 +00:00
Lovell Fuller
67f49a8dcd Tests: increase flaky text test range further 2023-11-08 14:12:03 +00:00
Lovell Fuller
074004392c Simplify logic to determine installation help 2023-11-06 16:49:53 +00:00
Lovell Fuller
8c5a493f68 Correct Deno package cache rpath from 8d1747a 2023-11-06 14:20:53 +00:00
Lovell Fuller
cccd1635c5 Small improvements to install error help text 2023-11-06 09:40:45 +00:00
Lovell Fuller
1915c1387e Docs: recommend use of npm cpu/os flags for cross-install 2023-11-05 14:08:31 +00:00
Lovell Fuller
4a37a27cca Improve worker thread support by preventing unload on dlclose 2023-11-04 22:23:01 +00:00
Lovell Fuller
ab8a4ed532 Tests: expand expected range of flaky text test
Cross-platform font discovery is complex
2023-11-04 21:34:45 +00:00
Lovell Fuller
12fd512b83 CI: simplify npm package smoke tests by using import 2023-11-04 21:15:18 +00:00
Lovell Fuller
239435a6dc Allow empty lib dir when populating npm packages 2023-11-04 20:08:17 +00:00
Lovell Fuller
7c1551bdc9 Tests: expect ranges for flaky text test 2023-11-04 17:22:08 +00:00
Lovell Fuller
bdcf02695f Prerelease v0.33.0-alpha.10 2023-11-04 15:54:19 +00:00
Lovell Fuller
d206fd5392 Tests: allow range for text image dimensions 2023-11-04 14:20:53 +00:00
Lovell Fuller
0bd1715f36 Options for trim op must be an Object, add lineArt #2363 2023-11-04 14:09:50 +00:00
Lovell Fuller
2e7c60675b Upgrade to libvips 8.15.0-rc2 2023-11-04 11:36:18 +00:00
Lovell Fuller
7caaa8e22b Tests: add debug to flaky text test 2023-11-03 11:42:57 +00:00
Lovell Fuller
839c92bf3d Docs: changelog and credit for #3812 2023-11-03 11:30:42 +00:00
Dennis Beatty
28aa176957 Add support for miniswhite when using TIFF output 2023-11-03 11:27:49 +00:00
Lovell Fuller
0f24f0f214 Add infrastructure (CI, npm) for sharp-linux-s390x package 2023-11-02 14:41:59 +00:00
Lovell Fuller
655da113c8 Ensure multi-page extract remains sequential #3837 2023-11-01 13:54:33 +00:00
Lovell Fuller
159b986cdd Tests: remove use of SVG fixture from median tests 2023-10-31 21:32:33 +00:00
Lovell Fuller
069d1786f5 The value of library_dirs is now common for all platforms 2023-10-20 11:15:23 +01:00
Lovell Fuller
f43829a16a Use Call semantics for C++ to JS callbacks
Reverts 4ec883e as no longer required
2023-10-19 16:14:21 +01:00
Lovell Fuller
65e61ad001 Tests: ensure SVG is well-formed, detect lack of pango 2023-10-19 16:08:34 +01:00
Lovell Fuller
0107a4de81 Docs: compatible with Node-API v9 runtimes 2023-10-14 15:46:02 +01:00
Lovell Fuller
337ce7b1c2 Docs: changelog entry for #3823 2023-10-14 09:19:53 +01:00
Lovell Fuller
3719f79065 Docs: simply language around failOn options 2023-10-14 09:19:28 +01:00
Lovell Fuller
8d1747aa6a Add rpath to match Deno package cache layout 2023-10-13 18:54:37 +01:00
Lovell Fuller
de9bdcba0a Prerelease 0.33.0-alpha.9 2023-10-13 14:32:21 +01:00
Lovell Fuller
f8b6cb6d5b Update package names to use 'img' npm organisation 2023-10-12 17:03:37 +01:00
Thomas
e6942805b4
TypeScript: withMetadata accepts boolean (#3823) 2023-10-11 20:38:13 +01:00
Lovell Fuller
47e76c9981 Ensure all Error objects contain a stack prop #3653 2023-10-11 14:59:21 +01:00
Lovell Fuller
68fa84ef6f Remove unused gitattributes 2023-10-11 14:48:40 +01:00
Lovell Fuller
ff2fb18c76 Remove extranous quote from help text 2023-10-11 10:03:07 +01:00
Lovell Fuller
28a9b1e9fa CI: Split npm package smoke tests into a matrix 2023-10-11 10:02:20 +01:00
Lovell Fuller
6377d5a73a Prerelease 0.33.0-alpha.8 2023-10-10 20:24:07 +01:00
Lovell Fuller
80e4707af1 Revert "Package managers cannot handle nested optionalDependencies"
This partially reverts commit 51e56f994ce1332f77daf625e23820a895de074d.

Ignoring plug'n'play, it looks like yarn and pnpm do get the
filesystem layout right for this scenario, which is good news.

It also looks like npm 10 will get it right too.
2023-10-10 19:34:36 +01:00
Lovell Fuller
ab00e34d0d Prerelease 0.33.0-alpha.7 2023-10-10 14:47:13 +01:00
Lovell Fuller
7c2f883b67 CI: add pnpm and yarn to npm smoke tests 2023-10-10 11:15:55 +01:00
Lovell Fuller
9b5eecba8f Yarn pnp unsupported, use alternative nodeLinker 2023-10-10 11:14:39 +01:00
Lovell Fuller
4b028edfe9 Revert "Remove extraneous rpath"
This reverts commit 3f54ef7525ed357ce64bf375ef7ce3d70a52ba61.

The filesystem layout used by pnpm means that a nesting of 2
directories deep is used in the wild and must remain.
2023-10-10 09:56:07 +01:00
Lovell Fuller
7e25dd7be1 Ensure versions prop detects use of global libvips 2023-10-10 09:18:25 +01:00
Lovell Fuller
09460d7af4 CI: use correct version of write-file action 2023-10-09 13:36:03 +01:00
Lovell Fuller
3b22640077 Use std::snprintf to concat libvips version parts 2023-10-09 13:35:20 +01:00
Lovell Fuller
946976ba8f Prerelease 0.33.0-alpha.6 2023-10-09 10:46:16 +01:00
Lovell Fuller
29a83250a4 CI: Add smoke test for npm-published package
These tests will fail on their first run as a tag will exist but
the matching packages will not yet have been published.

The workflow can be manually re-run after publishing to npm.

Eventually, when there's some form of automated publishing, this
logic can become part of the post-publish checks.
2023-10-09 07:59:47 +01:00
Lovell Fuller
3f54ef7525 Remove extraneous rpath
The sharp.node shared library should now always end up being
nested either 3 subdirectories deep into the package root or exist
within same namespace of the node_modules tree.
2023-10-09 07:58:14 +01:00
Lovell Fuller
4dc2467f49 CI: simplify prebuild file copying 2023-10-08 23:07:02 +01:00
Lovell Fuller
f54ceb0973 CI: create prebuilds in src directory 2023-10-08 21:49:58 +01:00
Lovell Fuller
8d033ae341 Prerelease 0.33.0-alpha.5 2023-10-08 20:27:42 +01:00
Lovell Fuller
f7da2e5970 Building from source now requires node-addon-api in dependencies
If you want to build sharp from source against a globally-installed
libvips then you will now need to add both node-addon-api and
node-gyp to the dependencies section of your package.json file.

The binding.gyp file is "hidden" inside the src directory to
prevent various build and package manager tooling from assuming
that everyone is going to build from source every time.
2023-10-08 15:39:02 +01:00
Lovell Fuller
51e56f994c Package managers cannot handle nested optionalDependencies 2023-10-07 11:09:45 +01:00
Lovell Fuller
68ac12292c Prerelease 0.33.0-alpha.4 2023-10-06 15:02:19 +01:00
Lovell Fuller
a9aa7339ce Prerelease 0.33.0-alpha.3 2023-10-06 09:48:44 +01:00
Lovell Fuller
08108f5fad Use std::once for vips_init call 2023-10-06 09:44:57 +01:00
Lovell Fuller
58e3c4c70e Ensure all package files make use of commonjs explicit 2023-10-05 20:00:32 +01:00
Lovell Fuller
f8cf25ca56 Ensure correct interp of 16-bit raw input #3808 2023-10-05 14:05:36 +01:00
Lovell Fuller
ca95979ecc Prefix node builtins, skips cache lookup 2023-10-05 12:09:19 +01:00
Lovell Fuller
392f6afb5e Commit fcc7e84 but do it properly this time 2023-10-04 21:30:05 +01:00
Lovell Fuller
7c97aabaf8 Ensure win32 packages contain version/notice files 2023-10-04 21:12:16 +01:00
Lovell Fuller
fcc7e84bee Revert target names as these are used for DLLs 2023-10-04 20:46:25 +01:00
Lovell Fuller
226a9a13ef Packaging: prerelease version bump 2023-10-04 15:48:23 +01:00
Lovell Fuller
4d3c9ae3d1 Packaging: clear existing lib directories 2023-10-04 15:47:57 +01:00
Lovell Fuller
f31011d759 CI: increase linux-arm timeout 2023-10-04 15:47:35 +01:00
Lovell Fuller
7cf4ae5648 Prerelease 0.33.0-alpha.2 2023-10-04 10:16:35 +01:00
Lovell Fuller
9161c605e1 Clarify extract-resize-extract operation ordering 2023-10-03 19:28:18 +01:00
Lovell Fuller
70ac6905c7 Use std::atomic for counters 2023-09-30 14:01:04 +01:00
Lovell Fuller
265d70111a Add licensing info to npm readme files 2023-09-28 15:42:13 +01:00
Lovell Fuller
59327bdd53 Install: libvips check takes precedence over flag 2023-09-27 16:20:04 +01:00
Lovell Fuller
3043e01171 Make heif compression option mandatory #3740 2023-09-27 11:55:42 +01:00
Lovell Fuller
36feb7551b Docs: changelog entry for removal of sharp.vendor 2023-09-27 11:50:55 +01:00
Lovell Fuller
a41c62be2b Upgrade semistandard, appease new linter rules 2023-09-26 21:25:15 +01:00
Lovell Fuller
854ed65016 Test: remove saliency directory
These scripts were originally used to help determine
some of the logic that is now part of the 'attention'
crop strategy in libvips itself.
2023-09-26 21:22:54 +01:00
Lovell Fuller
8f63d131a4 Upgrade exif-reader devDep to v2 2023-09-26 21:19:24 +01:00
Lovell Fuller
70a3067963 Test: update bench deps, use physical CPU core count 2023-09-26 21:16:46 +01:00
Lovell Fuller
aabbe1fa08 Distribute prebuilt binaries via the npm registry #3750
- Remove all custom download logic for prebuilt binaries
- Add scripts to populate package contents
- Specify minimum versions of common package managers
- Remove sharp.vendor runtime API as no-longer relevant
- Update installation docs and issue templates
2023-09-26 20:26:39 +01:00
Lovell Fuller
0f8bb9196e CI: merge all jobs that use GitHub runners 2023-09-24 16:08:56 +01:00
Lovell Fuller
efee9f1779 CI: Add linux-arm (v6, 32-bit) 2023-09-24 15:49:46 +01:00
Lovell Fuller
61c5cb4669 Ensure GitHub releases default to prerelease 2023-09-23 14:29:57 +01:00
Lovell Fuller
e618c17bd0 Upgrade to Node-API version 9 2023-09-23 10:53:53 +01:00
Christian Clauss
6578118f32
CI: Upgrade to Python 3.11 (#3460) 2023-09-23 10:01:54 +01:00
Lovell Fuller
ba20b8ada4 Drop support for Node.js 14 and 16, require >= 18.17.0 2023-09-23 09:48:05 +01:00
Lovell Fuller
eefaa99872 Release v0.32.6 2023-09-18 20:33:39 +01:00
Lovell Fuller
dbce6fab79 Upgrade to libvips v8.14.5 2023-09-18 20:09:54 +01:00
Lovell Fuller
af0fcb37c2 Docs: changelog for #3799 2023-09-18 14:56:03 +01:00
Lovell Fuller
c6f54e59da Bump devDeps 2023-09-18 14:53:44 +01:00
ldrick
846563e45f
TypeScript: add definitions for block and unblock (#3799) 2023-09-18 10:42:13 +01:00
Lovell Fuller
9c217ab580 Ensure withMetadata can add RGB16 profiles #3773 2023-08-31 12:49:50 +01:00
Lovell Fuller
e7381e522e Alternative fix for 4340d60, uses existing StaySequential 2023-08-31 12:09:11 +01:00
Lovell Fuller
4340d60ccf Ensure composite tile images fully decoded #3767 2023-08-31 09:04:51 +01:00
Lovell Fuller
7f64d464de Docs: add missing returns property to raw 2023-08-29 11:17:35 +01:00
Lovell Fuller
67e927bdb6 Docs: ensure all functions include method signature #3777 2023-08-29 11:16:18 +01:00
Lovell Fuller
9c7713ed54 Docs: remove mention of EXIF from flip/flop ops 2023-08-29 10:49:21 +01:00
Lovell Fuller
8be6da1def Docs: clarify when rotate op will remove EXIF Orientation 2023-08-29 10:19:07 +01:00
Lovell Fuller
95635683ac Ensure withMetadata skips default profile for RGB16 #3773 2023-08-24 18:13:00 +01:00
Lovell Fuller
44a0ee3fd3 Release v0.32.5 2023-08-15 19:29:42 +01:00
Lovell Fuller
ccd51c8cbf Upgrade to libvips v8.14.4 2023-08-15 16:40:22 +01:00
Lovell Fuller
bb7469b2d1 Ensure withMetadata adds default sRGB profile #3761 2023-08-15 13:02:20 +01:00
Kleis Auke Wolthuizen
a2cac61209
Simplify 90/270 orient-before-resize logic (#3762) 2023-08-15 07:56:07 +01:00
Lovell Fuller
5c19f6dd9b Ensure resize fit=inside respects 90/270 rotate #3756 2023-08-14 13:45:23 +01:00
Lovell Fuller
3d01775972 Docs: changelog entries for #3748 #3755 #3758 2023-08-14 13:33:13 +01:00
sho-xizz
87562a5111
TypeScript: Ensure WebpOptions minSize is boolean (#3758) 2023-08-09 13:45:10 +01:00
Kleis Auke Wolthuizen
2829e17743
Fix build with musl 1.2.4 (#3755) 2023-08-07 21:57:00 +01:00
pilotso11
ffefbd2ecc
TypeScript: add missing WebpPresetEnum (#3748) 2023-08-04 10:51:06 +01:00
Kleis Auke Wolthuizen
bc8f983329
Tests: ensure Jimp benchmark uses bicubic as resizing kernel (#3745) 2023-07-30 11:25:45 +01:00
Kleis Auke Wolthuizen
440936a699
Tests: update benchmark deps and container (#3744)
Use Node 18.x in benchmark container
2023-07-30 11:24:27 +01:00
Lovell Fuller
0bc79cdb95 Docs: include paletteBitDepth metadata 2023-07-28 16:04:02 +01:00
Lovell Fuller
9a66e25f53 Docs: ensure resize fit image supports dark mode 2023-07-25 10:06:44 +01:00
Lovell Fuller
8370935ccf Docs: ensure 'fit' values are clearly separated
Smaller text, slightly closer to image, varied fill colour
2023-07-21 23:07:57 +01:00
Kleis Auke Wolthuizen
f908987f35
Docs: use SVG image for the resize fit property example (#3735) 2023-07-21 21:58:02 +01:00
Lovell Fuller
aea368a3a0 Release v0.32.4 2023-07-21 11:41:08 +01:00
Lovell Fuller
7ecbc20d3d Upgrade to libvips v8.14.3 2023-07-21 11:10:21 +01:00
Lovell Fuller
cb0e2a91c4 Bump dep 2023-07-19 16:55:12 +01:00
Lovell Fuller
739b317a6f Expose ability to (un)block libvips ops by name 2023-07-19 16:53:52 +01:00
Lovell Fuller
a0e1c39785 Release v0.32.3 2023-07-14 11:03:39 +01:00
Lovell Fuller
85b26dab68 Expose preset option for WebP output #3639 2023-07-12 19:12:04 +01:00
Lovell Fuller
66f7cef253 Docs: fix a few typos 2023-07-12 14:22:29 +01:00
Lovell Fuller
863174f201 CI: FreeBSD: Use 13.2 stable, upgrade to Node.js 20 2023-07-12 12:10:31 +01:00
Lovell Fuller
bcd865cc96 Ensure decoding remains sequential for all ops #3725 2023-07-12 11:35:59 +01:00
Lovell Fuller
16ea04fe80 Release v0.32.2 2023-07-11 11:47:37 +01:00
Lovell Fuller
9c547dc321 Use copy rather than cache to prevent affine overcompute
More predictable behaviour, see commit 14c3346 for context
2023-07-10 13:56:42 +01:00
Lovell Fuller
5522060e9e Limit HEIF output dimensions to 16384x16384
This is a slightly breaking change to sync with the behaviour of a
forthcoming libvips patch release. It also matches the libavif
limit. Having an arbitrary limit is safer than no limit.
2023-07-10 10:24:14 +01:00
Lovell Fuller
d2f0fa855b Tests: loosen threshold for affine rotate then extract
Ignores rounding errors under Rosetta emulation
2023-07-10 08:12:13 +01:00
Lovell Fuller
2bb3ea8170 Bump deps 2023-07-09 11:57:05 +01:00
Lovell Fuller
3434eef5b9 Guard use of smartcrop premultiplied option #3710 2023-07-09 09:57:20 +01:00
Lovell Fuller
2f67823c3d Allow seq read for EXIF-based auto-orient #3725 2023-07-09 09:26:58 +01:00
Lovell Fuller
38c760cdd7 Update to latest (temporary) prebuild patch 2023-07-09 09:10:24 +01:00
Lovell Fuller
14c3346800 Prevent over-compute in affine rotate #3722 2023-07-09 09:04:07 +01:00
Lovell Fuller
0da55bab7e Tests: remove unused dependency 2023-06-29 09:11:25 +01:00
Lovell Fuller
cfb659f576 Bump deps 2023-06-23 08:19:41 +01:00
Lovell Fuller
cc5ac5385f Docs: clarify use of extract before composite 2023-06-23 08:08:39 +01:00
Lovell Fuller
93fafb0c18 CI: Upgrade to latest git v2 within centos 7 containers 2023-06-05 12:32:47 +01:00
Lovell Fuller
41e3c8ca09 Temporarily use patched prebuild with node-gyp v9 2023-06-05 09:45:12 +01:00
Lovell Fuller
da61ea0199 Docs: changelog and credit for #3674 2023-06-05 09:35:07 +01:00
BJJ
7e6a70af44 Improve detection of jp2 filename extensions #3674 2023-06-05 09:31:25 +01:00
Lovell Fuller
f5845c7e61 Ensure exceptions are not thrown when terminating #3569 2023-06-03 11:51:44 +01:00
Lovell Fuller
eb1e53db83 Bump deps 2023-06-03 11:51:12 +01:00
Lovell Fuller
3340120aea Types: include base input options for composite #3669 2023-05-16 13:55:28 +01:00
Lovell Fuller
de0fc07092 Ensure same access method for all inputs #3669 2023-05-16 13:53:31 +01:00
Lovell Fuller
dc4b39f73f Docs: multi-page images cannot be flipped 2023-05-13 08:54:21 +01:00
Lovell Fuller
e873978e53 Docs: clarify which axis is used when mirroring 2023-05-11 10:24:24 +01:00
Lovell Fuller
5255964c79 Docs: ensure headings with digits appear 2023-04-27 10:23:28 +01:00
Lovell Fuller
dea319daf6 Release v0.32.1 2023-04-27 09:58:40 +01:00
Lovell Fuller
a2ca678854 Docs: clarify text align applies to multi-line 2023-04-27 09:00:11 +01:00
Lovell Fuller
e98993a6e2 Bump node-addon-api for Buffer::NewOrCopy 2023-04-23 15:43:54 +01:00
Lovell Fuller
90abd927c9 Install: coerce libc version to semver (refactor) 2023-04-23 11:54:41 +01:00
Lovell Fuller
4d7957a043 Install: coerce libc version to semver #3641 2023-04-23 11:37:43 +01:00
Lovell Fuller
bf9bb56367 Docs: fix affine interpolator example 2023-04-22 13:56:33 +01:00
Lovell Fuller
8408e99aa3 Ensure trim op works with CMYK input #3636 2023-04-20 10:49:39 +01:00
Lovell Fuller
a39f959dcc Docs: add security policy
- Latest version is supported
- Report vulnerabilities via e-mail
2023-04-20 10:46:04 +01:00
Lovell Fuller
d08baa20e6 Install: log possible error when removing vendor dir 2023-04-19 11:06:16 +01:00
Lovell Fuller
391018ad3d Bump semver dep 2023-04-19 11:04:03 +01:00
Lovell Fuller
afed876f90 Docs: ensure inclusion of jp2 function
A misplaced code coverage comment was preventing this.
See ef849fd for the original commit where this broke.
2023-04-17 20:55:12 +01:00
Lovell Fuller
d6b60a60c6 Docs: add example of how to set EXIF GPS metadata 2023-04-17 20:35:47 +01:00
Lovell Fuller
5f8646d937 Support modulate op with non-sRGB pipeline colourspace #3620 2023-04-17 19:53:48 +01:00
Lovell Fuller
b763801d68 Ensure profile-less CMYK roundtrip skips space conv #3620 2023-04-11 20:31:57 +01:00
Lovell Fuller
2e0f789c9b Tests: add retries to text test suite
as font discovery is occasionally slow
in Windows CI environment.
2023-04-09 21:42:09 +01:00
Lovell Fuller
a8645f0f38 Smartcrop performance can take future advantage of
https://github.com/libvips/libvips/commit/de43eea
2023-04-09 21:17:08 +01:00
Lovell Fuller
7b58ad9360 Docs: changelog entry for #3615 2023-04-07 12:23:21 +01:00
TomWis97
9ebbcc3701
Logging: fix notation of proxy URL (#3615) 2023-04-07 12:19:04 +01:00
Lovell Fuller
e87204b92c Doc update and changelog entry for #3461 2023-04-07 11:21:15 +01:00
Anton Marsden
a4c6eba7d4
Add unflatten operation to create an alpha channel (#3461) 2023-04-07 11:01:29 +01:00
Lovell Fuller
b9c3851515 Ensure linear op works with 16-bit input #3605 2023-04-01 12:08:14 +01:00
Lovell Fuller
97cf69c26a Ensure use of flip op forces random access read #3600 2023-03-31 09:04:22 +01:00
Lovell Fuller
d5be024bfd Bump devDeps 2023-03-28 14:39:25 +01:00
Lovell Fuller
de01fc44e7 Docs: ensure API fn name linking is consistent 2023-03-28 14:00:52 +01:00
Lovell Fuller
ca102ebd6c Docs: fix perf result copypasta
An ARM64 value was incorrectly using an AMD64 result
2023-03-28 12:08:07 +01:00
Lovell Fuller
b9d4c30a9f Release v0.32.0 2023-03-24 17:05:59 +00:00
Lovell Fuller
148760fe55 Docs: clarify resize reduction/enlargement options refer to scaling
Types: options can be passed as first resize parameter
2023-03-24 15:19:21 +00:00
Lovell Fuller
98ed237734 Docs: use only first year of copyright to match code 2023-03-24 09:59:36 +00:00
Lovell Fuller
b55e58f31e Trim space from end of libvips error messages 2023-03-24 09:58:21 +00:00
Lovell Fuller
0af070ed93 Docs: update performance results, include PNG-based task 2023-03-23 18:57:43 +00:00
Lovell Fuller
9fbb4fcaef Tests: bump benchmark deps 2023-03-22 11:03:16 +00:00
Lovell Fuller
6008ff8a08 Docs: tile-based output requires libgsf 2023-03-22 09:17:07 +00:00
Lovell Fuller
cd5e11bd50 Docs: ensure parameters are indexed as they now appear in a table 2023-03-22 09:04:54 +00:00
Lovell Fuller
08d6822265 Upgrade to libvips v8.14.2 2023-03-21 21:21:24 +00:00
Lovell Fuller
8b8a815fbb Tests: tile-based output optional, will require custom libvips
The prebuilt binaries provided by v0.32.0 will not support
tile-based output, which is (hopefully) a temporary situation
until upstream licensing issues are resolved.
2023-03-21 21:19:56 +00:00
Lovell Fuller
a44da850c1 Docs: add open graph title and image 2023-03-21 12:56:44 +00:00
Lovell Fuller
c5ef4677b1 Bump tsd dep to pick up TypeScript 5 improvements 2023-03-21 12:43:29 +00:00
Lovell Fuller
f8a430bdd3 Tests: reduce CPU cost of RGBA linear test, ~2s faster 2023-03-21 12:42:50 +00:00
Lovell Fuller
cd419a261b Docs: changelog and refresh for #3583 2023-03-21 10:16:31 +00:00
LachlanNewman
d7776e3b98 Add support to normalise for lower and upper percentiles (#3583) 2023-03-21 10:13:12 +00:00
Lovell Fuller
1eefd4e562 Docs: how to provide new integrity values for custom binaries 2023-03-17 09:25:24 +00:00
cychub
0a16d26ec7
Docs: fix sharp_binary_host example by adding version (#3568) 2023-03-12 12:58:08 +00:00
Lovell Fuller
fc03fba602 Docs: clarify metadata ignores chained ops 2023-03-10 13:35:06 +00:00
Lovell Fuller
c87fe512b4 Bump devDeps 2023-03-08 16:59:20 +00:00
Lovell Fuller
2eaab59c48 Docs: add note about API Gateway integration 2023-03-08 16:54:49 +00:00
Lovell Fuller
4ec883eaa0 Wrap all async JS callbacks, help avoid possible race #3569 2023-03-01 12:41:11 +00:00
Lovell Fuller
0063df4d4f Ensure clahe op uses random read, simplify validation 2023-02-28 21:59:31 +00:00
Lovell Fuller
6c61ad256f Ensure all source code files contain SPDX licence 2023-02-28 17:01:58 +00:00
Lovell Fuller
b90474affa Docs: clarify formats that support multi-page/anim 2023-02-28 14:39:49 +00:00
Lovell Fuller
34cbc6dec3 Docs: clarify that paths are relative to process working dir 2023-02-23 10:33:13 +00:00
Lovell Fuller
bb8de0cc26 Docs: refresh search index 2023-02-18 12:51:42 +00:00
Lovell Fuller
863e37455a Docs: changelog and credit for #3556 2023-02-18 12:50:58 +00:00
Tomasz Janowski
6f0e6f2e65
Add support to extend for extendWith, allows copy/mirror/repeat (#3556) 2023-02-17 14:01:24 +00:00
Lovell Fuller
ebf4ccd124 Bump deps 2023-02-12 19:49:32 +00:00
Lovell Fuller
b96c8e8ba4 Tests: use native fs.rm instead of rimraf 2023-02-12 19:32:00 +00:00
Lovell Fuller
42d2f07e44 Add ignoreIcc input option to ignore embedded ICC profile 2023-02-12 17:51:24 +00:00
Lovell Fuller
a2988c9edc macOS: use 10.13 as minimum to match prebuilt libvips
This allows clang to use SSE4 intrinsics
2023-02-12 16:10:21 +00:00
Lovell Fuller
24b3344937 Docs: changelog for #3548 2023-02-05 09:49:06 +00:00
Jérémy Lal
9608f219bd
Add support for ArrayBuffer input (#3548) 2023-02-05 09:45:17 +00:00
Pascal Jufer
4798d9da64
Docs: clarify supported bit depth for AVIF images (#3541) 2023-02-02 17:47:07 +00:00
Lovell Fuller
8d8c6b70eb Prefer integer (un)premultiply for faster RGBA resize
Add changelog, loosen modulate test thresholds
2023-01-24 15:44:39 +00:00
Lovell Fuller
9e2207f376 Prefer integer (un)premultiply for faster RGBA resize 2023-01-24 15:24:58 +00:00
Lovell Fuller
802f560b9b Test: update benchmark dependencies 2023-01-24 15:21:31 +00:00
Lovell Fuller
a532659b0f Types: changes/additions relating to new v0.32.0 features
A separate commit is required as these were not part of the
initial definitions in the v0.31.3 snapshot.

From now on, new features and updates can include the relevant
TypeScript definition changes as part of the same
code/docs/tests commits.
2023-01-17 16:11:04 +00:00
Lovell Fuller
25c6da2bcd Docs: add a couple of missing params/props 2023-01-17 15:01:52 +00:00
Lovell Fuller
02f855d57a Expose own version as sharp.versions.sharp #3471 2023-01-17 09:56:58 +00:00
Lovell Fuller
c150263ef1 Respect fastShrinkOnLoad option for WebP input #3516 2023-01-17 09:39:23 +00:00
Lovell Fuller
9f79f80a93 Docs: fastShrinkOnLoad can round-down when auto-scaling 2023-01-16 12:06:50 +00:00
Lovell Fuller
069803b83d Docs: remove Heroku install section 2023-01-16 12:06:08 +00:00
Lovell Fuller
f79760b4f2 Docs: changelog and help for TypeScript defs #3369 #3370 2023-01-16 11:12:00 +00:00
Espen Hovlandsdal
aa5f0f4e40
Include and publish TypeScript definitions (#3370)
Definitions are a snapshot taken from `@types/sharp`,
which remain under the terms of MIT licensing.
2023-01-16 10:48:37 +00:00
Lovell Fuller
286a322622 Docs: changelog and doc refresh for #3470 2023-01-16 09:27:31 +00:00
Emanuel Jöbstl
6d404f4d2c
Add coords to output when using attention based crop (#3470) 2023-01-16 09:20:42 +00:00
Lovell Fuller
bdc50e1d6e Unpin node-addon-api, cast CallbackInfo access to size_t
See https://github.com/nodejs/node-addon-api/pull/1253
2023-01-16 09:00:42 +00:00
Lovell Fuller
a9bd0e79f8 Pin node-addon-api to workaround possible bug in 5.1.0 2023-01-15 19:35:27 +00:00
Lovell Fuller
a1e464cc5e Switch to sequential read as default where possible 2023-01-15 18:43:50 +00:00
Lovell Fuller
081debd055 Reduce sharpen op max sigma from 10000 to 10 #3521 2023-01-10 16:29:40 +00:00
Lovell Fuller
ef849fd639 Docs: switch to well-maintained jsdoc2md for JSDoc parsing 2023-01-08 10:15:38 +00:00
Lovell Fuller
a42a975c46 Bump devDeps 2023-01-06 19:25:27 +00:00
Lovell Fuller
e8273580af Docs: add note about use of fastShrinkOnLoad with resize kernel 2023-01-06 19:24:32 +00:00
Lovell Fuller
5be36c2deb Install: log Rosetta detection, improve related docs 2023-01-04 21:11:21 +00:00
Kleis Auke Wolthuizen
6cda090ce2
Tests: remove ICC profile from CIELAB fixture (#3510)
This ICC profile is considered incompatible with this image.

See: https://github.com/libvips/libvips/issues/730
2023-01-01 21:12:29 +00:00
Lovell Fuller
eac6e8b261 Upgrade to libvips v8.14.0-rc1
- Replace GIF 'optimise' option with 'reuse'
- Add 'progressive' option to GIF
- Add 'wrap' option to text creation
- Add 'formatMagick' property to *magick input metadata
2022-12-29 15:53:50 +00:00
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
659cdabd8e8c284901a0ea17ccdcb13e17350a8e,
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
Lovell Fuller
83bb6a4554 Release v0.30.0 2022-02-01 20:36:12 +00:00
Lovell Fuller
c72d42816d Docs: update performance test results for next release 2022-02-01 18:19:35 +00:00
Lovell Fuller
35a81a7af2 Upgrade to libvips v8.12.2 2022-02-01 10:52:02 +00:00
Lovell Fuller
9dc8db4370 Upgrade to libvips v8.12.2 2022-01-29 16:46:07 +00:00
Lovell Fuller
47ae1f52db Docs: metadata returns resolutionUnit, if present 2022-01-29 15:24:44 +00:00
Lovell Fuller
ec17d7f580 Bump deps: prebuild, for latest detect-libc 2022-01-29 15:11:50 +00:00
Lovell Fuller
da5453a7c0 Docs: changelog and refresh for #3023 2022-01-29 14:59:20 +00:00
ompal
f7bed69ffb Add resolutionUnit to metadata and as tiff option #3023
Co-authored-by: Lovell Fuller <github@lovell.info>
2022-01-29 14:31:47 +00:00
Kleis Auke Wolthuizen
7aa340232e
Ensure delays of the origin image is preserved (#3062)
By not initializing the delay vector, since we assume it's empty by default.

See: #3061.
2022-01-28 11:50:31 +00:00
Kleis Auke Wolthuizen
68823a5edb
Take page parameter into account when all frames are read (#3059) 2022-01-27 21:42:08 +00:00
Simon
1c3ba303ea
Update simple-get version (#3057)
Co-authored-by: Simon Tannai <stannai@socialkitchen.fr>
2022-01-27 10:57:56 +00:00
Lovell Fuller
76f8112952 Docs: npm v8 2022-01-27 09:24:29 +00:00
Lovell Fuller
24150eac89 Docs: Linux x64 binaries require CPU with SSE4.2
Intel has offered this since 2010, AMD since 2011
2022-01-24 13:51:19 +00:00
Lovell Fuller
51121a1440 Bump deps 2022-01-24 10:29:43 +00:00
Lovell Fuller
3b370b6c01 CI: add Rosetta-emulated x64 2022-01-24 10:19:04 +00:00
Lovell Fuller
884947a069 Upgrade to modern detect-libc 2022-01-19 11:27:24 +00:00
Lovell Fuller
f8340e1a82 Bump deps 2022-01-18 15:52:26 +00:00
Lovell Fuller
5101f4e79c CI: Fix linux-arm64v8 docker permission problems with npm v8 2022-01-18 15:50:25 +00:00
Lovell Fuller
161d127bf3 Docs refresh 2022-01-18 10:29:18 +00:00
Lovell Fuller
638d540371 Docs: mild blur is a box filter, add examples 2022-01-18 10:29:10 +00:00
Lovell Fuller
d8f1298511 Ensure rotate-then-extract works with EXIF mirroring #3024 2022-01-08 18:48:11 +00:00
Lovell Fuller
d67e09ba7c Add support for IIIF v3 tile-based output 2022-01-07 20:45:48 +00:00
Lovell Fuller
4c3a8a7007 Docs: fix example formatting, remove outdated warning 2021-12-21 12:31:29 +00:00
Lovell Fuller
92399ee5e2 Docs: correct gif resize example 2021-12-13 18:26:35 +00:00
Lovell Fuller
96992845ed Install: include platformAndArch in help after failure 2021-12-12 21:12:47 +00:00
Lovell Fuller
2b8e4d20de Docs: clarify that metadata is based on input, not output 2021-12-12 20:38:23 +00:00
Lovell Fuller
dd6583044b Docs: changelog and credit for #3006 2021-12-12 19:29:46 +00:00
Chris Banks
446e4e3c3a
Add withoutReduction option to resize operation (#3006) 2021-12-12 19:10:56 +00:00
Lovell Fuller
3b492ea423 Install: verify prebuilt binaries with Subresource Integrity check 2021-12-12 18:56:46 +00:00
Lovell Fuller
3da258f6fb Expose platform-arch of vendored binaries #2928 2021-12-12 13:38:00 +00:00
Lovell Fuller
9755629cfd
Ensure ops without multi-page support reject (#3010) 2021-12-12 09:14:26 +00:00
Lovell Fuller
5bb6702717 Bump dep: color 2021-12-11 21:51:23 +00:00
Lovell Fuller
8c0660d71e Docs: changelog and refresh for #2789 2021-12-11 21:41:41 +00:00
Kleis Auke Wolthuizen
513fb40f40
Improve multi-frame image resizing (#2789)
* Ports vips_thumbnail logic to sharp 
* Deprecates the pageHeight output option for WebP/GIF
2021-12-10 20:32:04 +00:00
Kleis Auke Wolthuizen
659cdabd8e
Windows: make invalid param errors recoverable by default (#3002)
* Tests: ensure writing to missing directory fails

Co-authored-by: Lovell Fuller <github@lovell.info>
2021-12-06 10:08:32 +00:00
Lovell Fuller
add4c7928f Upgrade to libvips v8.12.1 2021-11-25 22:05:21 +00:00
Lovell Fuller
336856dfc2 Tests: add PNG palette decode/encode roundtrip 2021-11-25 10:29:28 +00:00
Lovell Fuller
e1ba2a7fd8 Standardise HEIF effort option name, deprecate speed 2021-11-24 19:54:04 +00:00
Lovell Fuller
2b1f5cbe07 Standardise WebP effort option name, deprecate reductionEffort 2021-11-24 18:54:30 +00:00
Lovell Fuller
72025051c5 Expose control over CPU effort for palette PNG #2541 2021-11-24 17:12:53 +00:00
Lovell Fuller
140eeebb3d Docs refresh 2021-11-24 12:35:40 +00:00
Lovell Fuller
407bfcb42a Expose unlimited option for SVG and PNG input #2984 2021-11-24 12:35:20 +00:00
Lovell Fuller
549219f32a Tests: only need to assert 'mean' of 16-bit PNG roundtrip 2021-11-23 12:35:47 +00:00
Lovell Fuller
afab0d34dd Docs: changelog and credit for #2958 2021-11-23 12:21:36 +00:00
Max Gordon
2deced0fb9 Ensure 16-bit PNG output uses correct bitdepth #2958 2021-11-23 12:19:41 +00:00
Lovell Fuller
2a0077c481 Upgrade to libvips v8.12.0 2021-11-21 12:03:12 +00:00
Lovell Fuller
f7f3e43490 Add support for GIF output using cgif in prebuilt binaries 2021-11-21 10:22:34 +00:00
Lovell Fuller
b876abaf88 Tests: ensure median default window is covered 2021-11-17 13:58:56 +00:00
Lovell Fuller
dcd9a3c558 Docs: changelog and credit for #2976 2021-11-17 11:42:30 +00:00
Drian Naude
a06b8c296a
Properly emit close events for duplex streams (#2976) 2021-11-17 11:19:58 +00:00
DSRKafuU
602f988aba
Docs: Update Chinese mirror hostname (#2979) 2021-11-17 11:17:37 +00:00
Lovell Fuller
079bd7b9f5 Upgrade to libvips v8.12.0-rc1 2021-11-16 10:28:38 +00:00
Lovell Fuller
1ff84b20b7 Release v0.29.3 2021-11-14 11:40:19 +00:00
Lovell Fuller
97655d2dfd Bump deps 2021-11-14 09:17:44 +00:00
Michael B. Klein
d10d7b02d4
Docs: remove duplicate entry for mbklein (#2971) 2021-11-11 19:10:44 +00:00
Lovell Fuller
2ffdae2914 Docs: changelog and credit for #2952 2021-11-08 19:43:49 +00:00
Michael B. Klein
342de36973 Impute TIFF xres/yres from withMetadata({density}) 2021-11-08 19:43:42 +00:00
Lovell Fuller
b33231d4bd Ensure correct dimensions when contain 1px image #2951 2021-11-07 16:35:30 +00:00
Lovell Fuller
319db21f29 Release v0.29.2 2021-10-21 09:15:21 +01:00
Lovell Fuller
d359331426 Remove animation props from single page images #2890 2021-10-18 20:27:10 +01:00
Lovell Fuller
7ae151362b Bump devDeps 2021-10-17 15:17:50 +01:00
Lovell Fuller
648a1e05da Throw error rather than exit for invalid binaries #2931 2021-10-17 15:14:40 +01:00
Lovell Fuller
b9f211fe34 Docs: changelog for #2918 2021-10-17 15:11:38 +01:00
Dmitri Pyatkov
e475d9e47f
Improve error message on Windows for version conflict (#2918) 2021-10-17 14:10:28 +01:00
Lovell Fuller
f37ca8249a Bump deps 2021-09-22 11:41:22 +01:00
Lovell Fuller
1dd4be670d Add timeout function to limit processing time 2021-09-22 10:33:59 +01:00
Lovell Fuller
197d4cf835 Docs: changelog and credit for #2893 2021-09-22 10:31:12 +01:00
Lovell Fuller
83eed86b53 Docs: clarify prebuilt libc support on ARMv6/v7 2021-09-22 10:08:52 +01:00
Lovell Fuller
bbf612cb9e Replace use of deprecated util.inherits 2021-09-22 10:08:44 +01:00
Erlend
2679bb567b
Allow use of 'tif' to select TIFF output (#2893) 2021-09-16 18:49:14 +01:00
Lovell Fuller
481e350f39 Ensure 'versions' is populated from vendored libvips 2021-09-07 11:21:00 +01:00
Lovell Fuller
50c7a08754 Release v0.29.1 2021-09-07 10:23:50 +01:00
Lovell Fuller
9a0bb60737 Bump deps 2021-09-07 10:21:51 +01:00
Lovell Fuller
deb5d81221 Docs: changelog entries for #2878 #2879 2021-09-06 16:30:31 +01:00
Espen Hovlandsdal
916b04dbac
Allow using speed 9 for AVIF/HEIC encoding (#2879) 2021-09-06 16:23:02 +01:00
Espen Hovlandsdal
52307fad5d
Resolve paths before comparing input/output destination (#2878)
This fixes an issue where if you try to write to the same destination as the
input file but you are not using absolute (or the same relative path) for both
the input and output, sharp/vips might produce errors such as:

someFile.jpg: unable to open for write
unix error: No such file or directory
2021-09-06 16:21:43 +01:00
Lovell Fuller
afb21135c2 Docs: add changelog entry for #2868 2021-09-05 09:35:46 +01:00
Zaruike
b7fbffb3f7 Add support for libvips compiled with OpenJPEG 2021-09-05 09:32:02 +01:00
Lovell Fuller
5d98bcd8d8 Remove unsupported animation props from AVIF #2870 2021-09-05 08:46:15 +01:00
Lovell Fuller
e044788f63 Docs: changelog and credit for #2846 2021-08-30 20:31:10 +01:00
Tenpi
4a9267ce12 Add lightness option to modulate operation 2021-08-30 20:22:41 +01:00
Lovell Fuller
104464c2e0 Ensure images with P3 profiles retain full gamut #2862 2021-08-30 17:15:17 +01:00
Lovell Fuller
60adc110f5 Ensure background is premultiplied when compositing #2858 2021-08-29 16:40:40 +01:00
Paul Straw
2031d7d112
Ensure compatibility with ImageMagick 7 (#2865) 2021-08-28 20:17:44 +01:00
Lovell Fuller
3402656ec5 Set PNG bitdepth based on number of colours #2855
Removes use of deprecated libvips API
2021-08-26 22:05:29 +01:00
Lovell Fuller
4e84f743e4 Docs: toFile expects directory structure to exist 2021-08-20 09:22:22 +01:00
Lovell Fuller
17e50de5f0 Docs: serve docute from same hostname
Cheapo corporate web proxies ignore CSP and rewrite HTML
2021-08-19 18:58:17 +01:00
Lovell Fuller
978a788f40 CI: ensure Linux ARM64 prebuild token is passed into container 2021-08-17 14:49:57 +01:00
Lovell Fuller
6e91d55971 CI: ensure Linux ARM64 prebuild token is passed into container 2021-08-17 14:33:29 +01:00
Lovell Fuller
d4ce0a1e36 Update prebuild include regex 2021-08-17 11:23:24 +01:00
Lovell Fuller
148608b377 Release v0.29.0 2021-08-17 11:16:04 +01:00
Lovell Fuller
f725f4acb7 Update performance test results 2021-08-17 10:23:45 +01:00
Lovell Fuller
d07a549438 Tests: add squoosh-cli and squoosh-lib to performance benchmarks 2021-08-16 20:33:33 +01:00
Lovell Fuller
551441cedd Bench: bump deps 2021-08-16 19:36:42 +01:00
Lovell Fuller
46c14e939b Tests: add a few new leak suppressions 2021-08-16 19:01:39 +01:00
Lovell Fuller
6084647795 Upgrade to libvips v8.11.3 2021-08-15 19:45:08 +01:00
Lovell Fuller
e0a598ae62 Bump deps 2021-08-15 19:28:49 +01:00
Lovell Fuller
28833eb04a Upgrade to libvips v8.11.3-alpha1 2021-08-15 08:35:27 +01:00
Lovell Fuller
b24c9c86d1 Docs: changelog and credit for #2762 2021-08-03 15:28:50 +01:00
Mart
b7add480c7
Add support for bit depth with raw input and output (#2762)
* Determine input raw pixel depth from the given typed array
* Allow pixel depth to be set on raw output
2021-08-03 14:52:54 +01:00
Lovell Fuller
eabb671b10 Docs: minimum Node.js version requirement of 12.13.0 2021-08-03 10:25:04 +01:00
Lovell Fuller
513ed02b76 Docs: changelog entry for #2808 2021-08-02 21:37:54 +01:00
Espen Hovlandsdal
b7ddbe71f7 Add support for negating only non-alpha channels
Fixes #1035
2021-08-02 21:19:56 +01:00
Lovell Fuller
21d1a7ca62 CI: Add darwin-arm64 via MacStadium-based runner 2021-07-23 10:58:00 +01:00
Lovell Fuller
4c2d28a7ad Bump dep: color 2021-07-19 15:30:12 +01:00
Lovell Fuller
2afec9e3ed Docs: rebuild to include commit 6979042 2021-07-19 15:30:01 +01:00
reiv
69790421b7
Docs: add stats usage note and example (#2803) (#2804)
Clarify that stats are derived from the original input image and that operations need to be buffered in order to obtain stats from the resulting image.
2021-07-19 15:25:36 +01:00
Lovell Fuller
3f08f6a359 Add default background metadata for PNG and GIF images 2021-07-19 14:55:22 +01:00
Lovell Fuller
719c2db8da Bump devDeps 2021-07-14 19:33:24 +01:00
Lovell Fuller
a9aa55c32d Ensure pipelineColourspace is applied to all inputs #2704 2021-07-14 19:22:31 +01:00
Lovell Fuller
3f6d9d6ee9 Upgrade to libvips v8.11.2-alpha1 2021-07-14 13:45:47 +01:00
Lovell Fuller
b32568159f Docs: changelog and credit for #2704 2021-07-14 13:45:47 +01:00
Daiz
bb48d0d857 Add pipelineColourspace operator 2021-07-14 13:45:47 +01:00
Lovell Fuller
536412515f Allow installation directory to contain spaces
This previously worked, but regressed in v0.26.0.
2021-07-14 13:45:47 +01:00
Lovell Fuller
fcc6eaadd3 Tests: reduce WebP CPU time, ~2s faster 2021-07-14 13:45:47 +01:00
Lovell Fuller
7dc78e8796 Bump deps 2021-07-14 13:45:47 +01:00
Lovell Fuller
c65de3fe6d Default to single-channel output from extractChannel #2658 2021-07-14 13:45:47 +01:00
Lovell Fuller
d000f57773 Add compression property to HEIF image metadata #2504 2021-07-14 13:45:47 +01:00
Lovell Fuller
75cddbdb6d Default AVIF encoding to 4:4:4 chroma subsampling #2562 2021-07-14 13:45:47 +01:00
Lovell Fuller
e418d91511 Test: correct coverage syntax 2021-07-14 13:45:47 +01:00
Lovell Fuller
6c2e6c5432 Install: multiple platform-arch binaries in same tree 2021-07-14 13:45:47 +01:00
Lovell Fuller
8c6d9fdc62 Install: always use Brotli-compressed tarballs 2021-07-14 13:45:47 +01:00
Lovell Fuller
468e95427e CI: migrate ARM64 builds from TravisCI to CircleCI #2665 2021-07-14 13:45:47 +01:00
Lovell Fuller
6d7a5ace6b Drop support for Node.js 10, upgrade to Node-API v5 2021-07-14 13:45:47 +01:00
Lovell Fuller
cbaec198a5 Upgrade to libvips v8.11.0-rc1 2021-07-14 13:45:47 +01:00
Lovell Fuller
7467fa8b50 Docs: serve markdown files via Firebase instead of jsdelivr
Might make a few corporate web proxies happier
2021-06-21 17:10:44 +01:00
Lovell Fuller
61640fb5c7 CI: use gcc 10 on Linux x64 2021-06-03 18:52:52 +01:00
Lovell Fuller
19cb4b62b0 Docs: add security-related response headers 2021-06-02 09:12:02 +01:00
Lovell Fuller
81ee8bc30f Docs: make keyword search case insensitive 2021-06-02 09:11:08 +01:00
Lovell Fuller
9f384e1c6c Release v0.28.3 2021-05-24 16:26:34 +01:00
Lovell Fuller
35e8c8b25e Docs: ensure ops without examples are indexed 2021-05-24 16:24:04 +01:00
Lovell Fuller
dc53f1baff Bump deps 2021-05-24 16:08:10 +01:00
Lovell Fuller
70139600b5 Docs: fix CLAHE link 2021-05-23 18:49:54 +01:00
Lovell Fuller
1b4d1521e0 Docs: cross-link removeAlpha and flatten 2021-05-23 18:46:23 +01:00
Lovell Fuller
ed3377cb2d Docs: add parameter names to search keywords 2021-05-23 18:02:18 +01:00
Lovell Fuller
d72852b3aa Docs: changelog entry for #2726 2021-05-23 17:45:43 +01:00
Brad Parham
4b6b6189bf
Add contrast limiting adaptive histogram equalization (CLAHE) operator (#2726) 2021-05-23 17:36:04 +01:00
Lovell Fuller
b69a54fc75 Ensure presence of libvips before invoking node-gyp 2021-05-16 19:40:43 +01:00
Lovell Fuller
81e388a4cc Docs: composite supports failOnError and limitInputPixels 2021-05-15 14:52:33 +01:00
Lovell Fuller
5bd5e5052a Skip shrink-on-load for multi-page WebP #2714 2021-05-15 14:13:16 +01:00
Lovell Fuller
a2d3fa729f Release v0.28.2 2021-05-10 17:59:50 +01:00
Lovell Fuller
cb6811bc47 CI: FreeBSD skip notifications 2021-05-10 17:44:15 +01:00
Lovell Fuller
53c6e80869 Docs: refresh index 2021-05-10 16:03:40 +01:00
Lovell Fuller
e71dca586c Bump devDeps 2021-05-10 16:03:08 +01:00
Lovell Fuller
b3cd48db5f Docs: add section about cross-platform installation 2021-05-10 14:41:28 +01:00
Sebastian
476448b9d4
Install: allow cross-libc via sharp-install-force flag (#2692) 2021-05-10 09:55:20 +01:00
Lovell Fuller
070534df5b Docs: changelog for #2685 2021-05-03 19:48:15 +01:00
Michael Nutt
9a1e8ed574
Add premultiplied boolean flag for raw pixel data input (#2685) 2021-05-03 19:30:37 +01:00
Lovell Fuller
309918a878 Move lint-related tasks to dedicated script entry 2021-05-03 10:04:19 +01:00
Lovell Fuller
cac83b94c1 Bump deps and docs refresh 2021-05-03 10:01:43 +01:00
Lovell Fuller
9c06df08a1 Docs: changelog entry for #2687 2021-05-03 10:01:17 +01:00
Jacob
52e4543d31
Detect empty input and throw a helpful error (#2687) 2021-05-03 09:29:51 +01:00
Lovell Fuller
a688468378 CI: replace Node.js 15 with 16 2021-05-01 16:24:47 +01:00
Lovell Fuller
e1760d64fb Tests: updates so latest libvips master branch passes 2021-05-01 15:25:57 +01:00
Lovell Fuller
84d4e3cf8f Require specific semver functions, aids tree-shaking 2021-04-30 20:42:46 +01:00
Raj Rajhans
f8a76372ad
Docs: rewrite sentence to avoid grammatical ambiguity (#2668) 2021-04-21 14:10:24 +01:00
Lovell Fuller
4237f5520f Allow withMetadata to set density #967 2021-04-17 13:46:54 +01:00
Lovell Fuller
8c0c01c702 Docs: changelog entry for #2664 2021-04-17 09:11:48 +01:00
msalettes
9c100830e0
Allow escaped proxy credentials (#2664) 2021-04-17 08:49:07 +01:00
Lovell Fuller
ed5d753b89 Skip shrink-on-load where one dimension <4px #2653 2021-04-07 21:26:16 +01:00
Timo Hausmann
d1ca756bd8
Docs: correct flatten example to use object instead of string (#2654) 2021-04-06 17:21:14 +01:00
Lovell Fuller
16cf9f0ef2 Release v0.28.1 2021-04-05 12:28:16 +01:00
Lovell Fuller
133f69d66c Bump prebuild-install (for sharp_local_prebuilds) 2021-04-05 12:26:28 +01:00
Lovell Fuller
bc60daff9e Allow EXIF metadata to be set/update #650 2021-04-05 11:39:53 +01:00
Lovell Fuller
43a085d1ae Add support for OME-TIFF subIFDs #2557 2021-04-02 08:04:21 +01:00
Lovell Fuller
8c33d0aa56 Allow ensureAlpha to set alpha transparency level #2634 2021-04-01 21:14:06 +01:00
Lovell Fuller
fe0767df13 Install: log errors with more obvious prefix 2021-04-01 16:20:58 +01:00
Lovell Fuller
08a25a0c8f Docs: add animated WebP example #2648 2021-04-01 16:04:46 +01:00
Lovell Fuller
cd410080bd Docs: remove reference to specific Lambda runtime 2021-03-29 20:16:07 +01:00
Lovell Fuller
7555378e3b Release v0.28.0 2021-03-29 14:10:34 +01:00
Lovell Fuller
80c95ee66a Docs: libvips tarballs are a bit smaller now 2021-03-29 12:16:48 +01:00
Lovell Fuller
31563b210d Ensure GIF input will work with future libvips v8.11.0 2021-03-29 12:16:10 +01:00
Lovell Fuller
861cd93324 Pre-release v0.28.0-beta1 2021-03-27 07:11:34 +00:00
Lovell Fuller
abb344bb1a Upgrade to libvips v8.10.6 2021-03-26 21:57:12 +00:00
Lovell Fuller
6147491d9e Extend: default missing edge props to zero #2578 2021-03-25 16:34:02 +00:00
Lovell Fuller
f1f18fbb4a Docs: clarify that flatten removes alpha channel #2601 2021-03-25 14:38:55 +00:00
Lovell Fuller
9fc611f257 Docs: changelog entries for #2594 #2608 2021-03-22 20:30:46 +00:00
SHG42
34a2e14a14 Fix erroneous top/left clipping in composite #2571
Fixes bug where certain input values for top/left parameters
in composite can conflict with clipping logic, resulting in
inaccurate alignment in output.
2021-03-22 18:27:49 +00:00
Lovell Fuller
83fe65b9e9 Docs: include more relevant content in search index 2021-03-21 20:59:05 +00:00
Lovell Fuller
ec26c8aa49 Docs: ensure toBuffer pixel example works #2624 2021-03-21 20:54:09 +00:00
Lovell Fuller
da43a3055f Docs: correct typo in description of threshold operation 2021-03-21 20:51:30 +00:00
Lovell Fuller
a38126c82f Ensure composite replicates correct tiles with centre gravity #2626 2021-03-20 13:24:04 +00:00
Lovell Fuller
cb592ce588 Tests: add case for SVG with truncated embedded PNG 2021-03-18 19:34:56 +00:00
Lovell Fuller
d69c58a6da Docs: add section about Linux memory allocators 2021-03-18 19:34:07 +00:00
Lovell Fuller
bdb1986e08 Tests: run in parallel again 2021-03-17 23:25:34 +00:00
Lovell Fuller
55356c78a8 Docs: refresh markdown 2021-03-15 20:24:53 +00:00
Lovell Fuller
a0f55252b1 Tests: a few more speed improvements 2021-03-15 20:24:13 +00:00
Lovell Fuller
013f5cffa9 Tests: refactor modulate suite, ~20x faster 2021-03-15 18:20:06 +00:00
Lovell Fuller
d5d008f568 Docs: reorder readme sections 2021-03-15 13:07:16 +00:00
Lovell Fuller
3b02134cdc Tests: update latest benchmark test results 2021-03-14 21:10:26 +00:00
Lovell Fuller
a57d7b51b1 Tests: match concurrency with CPU count 2021-03-14 19:51:45 +00:00
Lovell Fuller
1a3c38d35f Pre-release v0.28.0-alpha1 2021-03-14 11:50:33 +00:00
Lovell Fuller
00aece0538 Ensure id attr can be set for IIIF tile output #2612 2021-03-14 11:19:53 +00:00
Lovell Fuller
5a9cc835b3 Reduce concurrency when using glibc-based Linux
to help prevent memory fragmentation
2021-03-14 11:19:53 +00:00
Lovell Fuller
58526cc849 Upgrade to libvips v8.10.6-alpha3 2021-03-14 11:19:53 +00:00
Lovell Fuller
955b5f43a5 Tests: small speed up to a couple of tile-related tests 2021-03-14 11:19:53 +00:00
Lovell Fuller
447aec3fde Tests: update leak suppressions 2021-03-14 11:19:53 +00:00
Lovell Fuller
473260a836 Docs: update with install-time improvements 2021-03-14 11:19:53 +00:00
Lovell Fuller
4d2784c10c Prebuilt libvips v8.10.6 binaries work with musl 1.1.x and 1.2.x 2021-03-14 11:19:53 +00:00
Lovell Fuller
d9af897595 Tests: ensure AVIF order is read, write, read+write 2021-03-14 11:19:53 +00:00
Lovell Fuller
23a48be315 Upgrade to libvips v8.10.6-alpha2
- Prebuilt Linux libvips binaries now use 'new' C++11 ABI
2021-03-14 11:19:53 +00:00
Lovell Fuller
ce8f48e5d1 CI: Add linuxmusl-arm64v8 environment 2021-03-14 11:19:53 +00:00
Kleis Auke Wolthuizen
6aaf839662 Use a single shared library 2021-03-14 11:19:53 +00:00
Lovell Fuller
984a9e653e Upgrade to libvips 8.10.6-alpha1
- Prebuilt binaries now include mozjpeg and libimagequant (BSD 2-Clause)
- Prebuilt binaries limit AVIF support to the most common 8-bit depth
- Add `mozjpeg` option to `jpeg` method, sets mozjpeg defaults
- Reduce the default PNG `compressionLevel` to the more commonly used 6
2021-03-14 11:19:53 +00:00
Lovell Fuller
8dffa28b4d Remove npmlog as a direct dependency
It remains a transitive dependency via prebuild-install
2021-03-14 11:19:53 +00:00
Lovell Fuller
b05a4bdadd Use same version of simple-get as prebuild-install
to prevent two different versions being installed
2021-03-14 11:19:53 +00:00
Lovell Fuller
36087fe518 Remove array-flatten dependency 2021-03-14 11:19:53 +00:00
Lovell Fuller
5eed87ec4d Install: skip header files when using prebuilds 2021-03-14 11:19:53 +00:00
Tobias Nießen
af66a73225
Tests: fix unit test description (#2619) 2021-03-13 16:18:40 +00:00
Alex Bradley
dcf913c17e
Install: fail on incomplete download and clean up tempfile (#2608)
- Fail when the connection closes before the response is complete
- Create tempfile only when needed, and clean it up on failure
2021-03-05 15:21:34 +00:00
Lovell Fuller
68ccba8f74 Docs: refresh search index 2021-02-22 21:17:31 +00:00
Lovell Fuller
956f7e29db Release v0.27.2 2021-02-22 20:30:42 +00:00
Lovell Fuller
4264c0577e Improve experience for those using Apple M1 devices #2460
- For Rosetta x64, prevent use of global ARM64 libvips
- For ARM64, improve error message when global libvips not found
2021-02-22 13:49:31 +00:00
Lovell Fuller
cc37b59309 Switch to libvips' recently-exposed has_alpha #2569 2021-02-22 12:32:20 +00:00
Lovell Fuller
9f2f92095d Skip prebuilt binaries for musl >=1.2.0 #2570 2021-02-20 19:40:40 +00:00
Lovell Fuller
0c1075c089 Docs: local compilation requires --build-from-source flag 2021-02-20 15:43:48 +00:00
allx
9c64710c8b
Allow code bundling of utility functions (#2586) 2021-02-20 15:39:25 +00:00
Lovell Fuller
f6f16b91db Allow use of recomb op with 1/2 channel input #2584 2021-02-19 16:37:29 +00:00
Lovell Fuller
1986b5cfe6 Bump deps 2021-02-19 15:49:21 +00:00
Lovell Fuller
6445b72d41 Docs: Changelog entry and credit for #2581 2021-02-19 15:48:59 +00:00
Florian Busch
df7b8ba738
Add support for non lower case extensions with toFormat 2021-02-17 20:46:13 +00:00
Pedro Poveda
202083999e Docs: add closing parenthesis so code example runs 2021-02-14 15:57:06 +00:00
aprat84
315f519e1d
Docs: correct type for AVIF speed output option (#2568) 2021-02-08 20:37:56 +00:00
Lovell Fuller
d7d580ae6f Tests: using parallel fails on latest Node.js 15.8.0 2021-02-08 13:12:35 +00:00
Lovell Fuller
7017af303d Improve error message when attempting toFile/GIF without magick 2021-02-08 11:46:13 +00:00
Lovell Fuller
0dc325daa4 Docs: add section about Webpack configuration 2021-01-29 11:29:24 +00:00
Lovell Fuller
6dffb47973 Docs: small search index improvements 2021-01-29 11:28:48 +00:00
Lovell Fuller
b19dad69d6 Release v0.27.1 2021-01-27 19:44:39 +00:00
Lovell Fuller
94c5ac64e9 Bump devDeps 2021-01-27 19:44:01 +00:00
Lovell Fuller
c4bcd088fb Tests: run in parallel, ~20% faster on multicore machines 2021-01-26 20:27:52 +00:00
Lovell Fuller
aeecbe9396 Tests: ensure faster metadata tests pass on ARM64 2021-01-26 20:27:20 +00:00
Lovell Fuller
171aade9cd Tests: reduce time taken by metadata tests 2021-01-26 19:52:33 +00:00
Lovell Fuller
67213ae86c Tests: refactor output paths, might enable parallel runs 2021-01-26 18:43:48 +00:00
Lovell Fuller
24d9e53c3f Docs: add example of 16-bit RGB output #2528 2021-01-26 15:03:43 +00:00
Kleis Auke Wolthuizen
573ed5f4b5 Avoid calling g_type_from_name #2535 2021-01-26 14:42:08 +00:00
Bert Verhelst
ceff628add Docs: ensure correct types for output options 2021-01-26 14:23:56 +00:00
Randy Ridge
0bb8cb9203 Ensure TIFF is cast when using float predictor (#2502) 2021-01-26 14:00:25 +00:00
Lovell Fuller
98349bde28 Docs: add section on known conflicts 2021-01-24 17:15:28 +00:00
Lovell Fuller
f09be932eb Docs: add info about npm v7 directory ownership change 2021-01-24 16:52:10 +00:00
Lovell Fuller
4c57ac2bbe Docs: sharp logos are now in the public domain 2021-01-18 16:52:23 +00:00
Lovell Fuller
1dd93c1b6b Docs: changelog entry and example for #2527 2021-01-16 14:26:38 +00:00
alza54
c9f85fe27f
Expose libvips gaussnoise operation (#2527) 2021-01-16 14:03:25 +00:00
Lovell Fuller
419cbe50f6 Preserve transparancy in monochrome logo 2021-01-16 10:53:15 +00:00
Lovell Fuller
5031c8323f Add monochrome version of sharp logo 2021-01-15 22:03:00 +00:00
Lovell Fuller
762d5913ce Avoid nested macro, replace VIPS_AREA w/ reinterpret_cast 2021-01-13 18:32:37 +00:00
Lovell Fuller
290df1b1c7 Windows: fix preprocessor syntax 2021-01-13 18:09:42 +00:00
Lovell Fuller
79170afc51 Docs: add 2021 as a copyright year 2021-01-13 18:06:28 +00:00
Lovell Fuller
bba00c2bfe Revert: ensure all platforms use fontconfig #2399 #2515 2021-01-13 17:50:58 +00:00
Lovell Fuller
f7e2b3688f Bump devDependencies 2021-01-13 17:23:29 +00:00
Lovell Fuller
8d49b7dde1 Ensure tests pass with latest libvips master branch
Expose forthcoming HEIF features where available
2021-01-13 16:47:49 +00:00
Lovell Fuller
138e60adb3 Docs: add section for Apple M1 users #2460 2021-01-06 13:39:47 +00:00
Lovell Fuller
d6376c31e0 Test: ensure toBuffer tests return any errors 2021-01-06 13:12:24 +00:00
Lovell Fuller
a7003e93c8 Docs: changelog entry for #2511 2021-01-06 11:10:11 +00:00
Leon Radley
4821a11223
Add support for Uint8(Clamped)Array input (#2511) 2021-01-06 09:49:24 +00:00
Lovell Fuller
bf1b326988 Docs: allow docs to be built on Windows 2021-01-01 15:19:35 +00:00
Lovell Fuller
39ddb6a175 Docs: improve descripion of create/raw props 2021-01-01 14:47:26 +00:00
Lovell Fuller
b2a0b8c0f0 Release v0.27.0 2020-12-22 11:50:23 +00:00
Lovell Fuller
4debc46d0e Docs: add AVIF to supported formats 2020-12-22 11:47:54 +00:00
Lovell Fuller
f4e259d10f Pre-release v0.27.0-beta1 (prebuild test) 2020-12-21 21:14:15 +00:00
Lovell Fuller
774d78228e Docs: update performance test results 2020-12-21 21:00:44 +00:00
Lovell Fuller
0e62bde5c3 Update (and pin) benchmark module versions 2020-12-21 20:26:57 +00:00
Lovell Fuller
2bbd9b23e6 Add new leak test suppressions (fontconfig, gsf, rsvg) 2020-12-21 11:24:34 +00:00
Manan Jadhav
02676140e8 Allow for negative top/left offsets in composite overlays
A top or left offset value of -1 will no longer mean that the
value is not set, but will now be an actual offset of -1.

INT_MIN for left & top will mean that the values are not set.

Co-authored-by: Christian Flintrup <chr@gigahost.dk>
2020-12-20 17:36:39 +00:00
Lovell Fuller
182beaa4a1 Docs: add note about AVIF images smaller than 16x16 2020-12-20 17:17:49 +00:00
Lovell Fuller
7c08a09529 Add new leak test suppressions (rsvg, vips, heif, aom) 2020-12-20 17:05:37 +00:00
Lovell Fuller
ef964b5472 Ensure all platforms use fontconfig to render #2399 2020-12-20 10:23:26 +00:00
Lovell Fuller
ee54ce9913 Upgrade to stable libvips v8.10.5 prebuild 2020-12-20 09:51:33 +00:00
Lovell Fuller
e59e146887 CI: migrate x64 Linux, macOS and Windows to GitHub Actions 2020-12-18 17:39:11 +00:00
Lovell Fuller
103ec0d58f Upgrade to libvips 8.10.5, AVIF support in prebuilt binaries
Remove experimental status from HEIF, changing defaults
to prefer royalty-free AV1 over patent-encumbered HEVC
2020-12-18 17:32:16 +00:00
Lovell Fuller
a0d89ed514 Add link to documentation on new issue page 2020-12-09 15:01:14 +00:00
Lovell Fuller
c10888e6fe Release v0.26.3 2020-11-16 16:44:18 +00:00
Lovell Fuller
93455f8eb5 Docs: changelog entry for #2412 2020-11-16 15:26:27 +00:00
Matt Kane
65acd96c8d
Install: conditionally use Brotli or gzip prebuilt libvips (#2412) 2020-11-16 15:22:13 +00:00
Lovell Fuller
fabe720b9b Docs: keyword search improvements 2020-11-16 15:10:28 +00:00
Lovell Fuller
53dd313e97 CI: force build from source, req of prebuild-install v6+ 2020-11-16 13:55:55 +00:00
Lovell Fuller
2678d7a660 Bump dev dependencies 2020-11-16 12:52:03 +00:00
Lovell Fuller
46718102c6 Docs: changelog for #2336 2020-11-16 12:35:19 +00:00
Guillermo Varela
0f473fe3b1
Expose libvips affine operation (#2336) 2020-11-16 12:27:38 +00:00
Nick Jones
2872602c9e
Deps: upgrade to prebuild-install 6.0.0 (#2419) 2020-11-16 12:22:35 +00:00
Lovell Fuller
ab653cae33 Docs: use of N-API removes Electron-specific binaries
Clarify Lambda deployment for Windows/macOS users
2020-11-16 12:20:29 +00:00
Nicolas Stepien
e6a035e575
CI: add Node.js 15 (#2415) 2020-10-23 10:01:29 +01:00
Lovell Fuller
fbe48d75dd Release v0.26.2 2020-10-14 17:59:55 +01:00
Lovell Fuller
20ba0f49dd Changelog entry and doc refresh for #2397 2020-10-08 10:05:39 +01:00
beig
c213e9878d
Add centre/center option to tile-based output (#2397) 2020-10-08 09:51:54 +01:00
Lovell Fuller
9704ca4c18 Add support for libvips compiled with OpenEXR #698 2020-10-07 15:12:06 +01:00
Lovell Fuller
49dce6219e Docs: changelog entry for #2379 2020-10-07 14:43:13 +01:00
Adam Coster
260ff6c94f
Docs: clarify response object description for trim (#2400) 2020-10-06 17:08:32 +01:00
Adam Lovatt
3ec281d104
Ensure support for yarn v2 (#2379) 2020-09-23 21:41:14 +01:00
Lovell Fuller
c4c43d525b Release v0.26.1 2020-09-20 09:29:50 +01:00
Lovell Fuller
6c5cde363a Ensure animated GIF output is optimised #2376 2020-09-19 20:53:15 +01:00
Lovell Fuller
d46b4d950f Allow spaces in installation directory #2279
Uses new include_dir property of node-addon-api
2020-09-19 14:26:30 +01:00
Lovell Fuller
b369c4bb8a Ensure stats can be calculated for 1x1 input #2372 2020-09-17 11:08:52 +01:00
Lovell Fuller
c3898487c4 CI: name the FreeBSD task 2020-09-17 11:02:16 +01:00
Lovell Fuller
ca3c5b400f CI: install ARM64 nodejs package with dependency on python3-minimal
Node.js 14 will work but 10 and 12 will fail until
https://github.com/nodesource/distributions/issues/1100 is fixed
2020-09-15 19:21:32 +01:00
Lovell Fuller
97772b176c Docs: changelog entry for #2369 2020-09-15 18:05:22 +01:00
AcrylicShrimp
08a2965f1c
Ensure animation-related properties work with stream-based input 2020-09-15 15:12:26 +01:00
Lovell Fuller
76dcddfa3d Changelog, credit, doc update for #2348 2020-09-02 09:06:15 +01:00
stefanprobst
79f476ae4d
Allow input density range up to 100000 DPI (#2348) 2020-09-02 08:56:12 +01:00
Lovell Fuller
d406cb619c Improve error messaging for unsupported Node.js versions 2020-08-28 21:39:11 +01:00
Lovell Fuller
4f3890f1e4 Issue template: ask about installation architecture and platform 2020-08-28 13:59:44 +01:00
Lovell Fuller
7a9d58cc51 Docs: changelog entry for #2343 2020-08-28 13:56:35 +01:00
Lovell Fuller
eef87da0e1 Docs: CSP allow inline JS 2020-08-28 13:53:19 +01:00
Denis Soldatov
00e65f6f14
Ensure correct pageHeight when verifying image dimensions (#2343) 2020-08-28 13:39:19 +01:00
Lovell Fuller
866e9824d1 Release v0.26.0 2020-08-25 18:42:06 +01:00
Lovell Fuller
482e6078e2 Tests: Update leak suppressions for librsvg static data 2020-08-25 18:40:12 +01:00
Lovell Fuller
bc7ab296ef Tests: Update leak suppressions for static libs 2020-08-24 21:10:20 +01:00
Lovell Fuller
a5f4f53b56 Tests: remove no-longer-used conditional assertions 2020-08-23 20:11:23 +01:00
Lovell Fuller
b1227f526d Verify minimum libvips version at compile time 2020-08-23 20:10:27 +01:00
Lovell Fuller
78b42c8306 Docs: update performance test results 2020-08-23 16:48:46 +01:00
Lovell Fuller
4b6d45ab8e Prerelease v0.26.0-beta1 2020-08-23 15:56:25 +01:00
Lovell Fuller
7980341923 Upgrade libvips to v8.10.0 2020-08-23 15:36:03 +01:00
Lovell Fuller
3917efdebd Benchmarks: ensure PNG tests use consistent settings 2020-08-21 21:10:27 +01:00
Robert O'Rourke
eaecb7347b Add support to withMetadata for custom ICC profile #2271 2020-08-19 21:32:15 +01:00
Lovell Fuller
05ca7d3129 CI: further attempts to get Windows to play nicely 2020-08-18 20:53:18 +01:00
Lovell Fuller
4beae0de71 Add 'animated' constructor property as shortcut for 'pages'
Provides easier-to-understand API when handling animated images
2020-08-18 20:28:35 +01:00
Lovell Fuller
b711661784 CI: improve cross-platform (i.e. Windows) process spawning 2020-08-18 17:11:42 +01:00
Lovell Fuller
0c4a45b1f4 CI: workaround Appveyor ignoring v-prefixed tag names 2020-08-18 14:31:33 +01:00
Lovell Fuller
ec2beb0039 Prerelease v0.26.0-alpha2 2020-08-18 14:01:19 +01:00
Lovell Fuller
cafb3e8bac CI: ensure git tag is available inside prebuild containers 2020-08-18 14:00:14 +01:00
Lovell Fuller
e896d5e920 Prerelease v0.26.0-alpha1 2020-08-18 09:39:09 +01:00
Lovell Fuller
42d4228595 Replace prebuild-ci with simple wrapper around prebuild
Drop Node.js 13, generate prebuilds for NAPI v3 only
2020-08-18 09:37:57 +01:00
Lovell Fuller
341ea3e4ea Doc refresh and changelog entry for #2012 2020-08-17 16:20:10 +01:00
Tomáš Szabo
cb1baede87
Add support for animated WebP and GIF (via magick) (#2012) 2020-08-17 14:48:38 +01:00
diegodev3
45653ca2e7 Ensure prebuilt binaries for ARM default to v7 when using Electron 2020-08-14 17:27:14 +01:00
Lovell Fuller
77c861b74b Docs: ensure unreleased changes included in next release 2020-08-14 15:03:47 +01:00
Lovell Fuller
b586c2146f Ensure node-addon-api include path is array context
Need to revert to scalar context after node-addon-api v3.0.2
2020-08-14 12:39:58 +01:00
Lovell Fuller
4d42bed4f8 Upgrade to libvips v8.10.0-rc4 2020-08-14 10:33:37 +01:00
Lovell Fuller
ea54c119ab Bump deps 2020-08-14 08:20:35 +01:00
Lovell Fuller
d95b124771 CI: ensure ARM64 Node.js 10 is installed 2020-08-11 10:09:21 +01:00
Lovell Fuller
61ccf09e6f CI: ensure ARM64 Node.js 10 is installed from specific repo 2020-08-11 09:37:19 +01:00
Lovell Fuller
8da30f0b41 Map libvips file loader nicknames to sharp image types
Use stable API rather than internal class names, reduces complexity
2020-08-09 09:39:27 +01:00
Lovell Fuller
90a57e7664 Upgrade to libvips 8.10.0-rc1 2020-07-17 14:46:53 +01:00
Lovell Fuller
c42de19d2a Add most dominant colour to image stats #640 2020-07-15 21:57:37 +01:00
Lovell Fuller
dcc42f8514 Ensure electron-builder and electron-rebuild use N-API v3 prebuilds 2020-07-15 09:05:53 +01:00
Lovell Fuller
3150fad909 Upgrade to libvips 8.10.0-beta2 2020-07-14 19:45:25 +01:00
Lovell Fuller
ba17db3ab3 Switch to Brotli-compressed binaries, requires Node.js 10.16.0+ 2020-06-29 20:53:58 +01:00
Kleis Auke Wolthuizen
7c1c48327e
Add support for statically-linked dependencies (lovell/sharp-libvips#39) (#2223) 2020-06-28 21:17:15 +01:00
Lovell Fuller
85459e0ec6 macOS: remove linker flag ignored by clang 2020-06-27 11:55:10 +01:00
Lovell Fuller
13bdb68366 CI: pin Windows x86 Node.js 14 to 14.2.0
This is the least unstable version on the 14 release line.
Windows x86 users should probably delay upgrading to Node.js 14.
2020-06-27 11:42:00 +01:00
Lovell Fuller
c91373fba3 Docs: add section about worker threads 2020-06-18 13:42:04 +01:00
Lovell Fuller
e8149f5295 Docs: fix markdown in changelog 2020-06-16 19:01:36 +01:00
Lovell Fuller
ab015ef90f Avoid copy in metadata levels for loop 2020-06-16 18:59:20 +01:00
Lovell Fuller
fdfc89e577 Docs: add content security policy 2020-06-16 18:41:18 +01:00
Lovell Fuller
e647e1f7bd Add changelog entry and credit for #2258 #2259 2020-06-16 18:39:58 +01:00
Jerome Vouillon
a05d735e31
Allow multi-page input via ImageMagic (#2259) 2020-06-15 13:01:53 +01:00
Jerome Vouillon
4470048ba4
Add support for libvips ImageMagick v7 loaders (#2258) 2020-06-15 12:59:20 +01:00
Lovell Fuller
0f58f956a7 Docs: fix external CSS 2020-06-12 17:07:05 +01:00
Lovell Fuller
20284757a6 Docs: fix binary mirror example 2020-06-12 17:06:46 +01:00
Lovell Fuller
df6efa0285 Release v0.25.4 2020-06-12 14:17:23 +01:00
Lovell Fuller
3c10e118e3 Docs: ensure presence of constructor description 2020-06-12 13:52:19 +01:00
Lovell Fuller
19980190f7 Emit 'warning' event for non-critical problems #2032 2020-06-12 13:46:12 +01:00
Lovell Fuller
8f5495a446 Add experimental sharpness calc to stats #2251 2020-06-12 11:25:57 +01:00
Mikhail Bodrov
9431029917
Simplify type checking of plainObject, buffer (#2252) 2020-06-10 20:54:01 +01:00
Lovell Fuller
17ea70a102 Add named 'alpha' channel to extractChannel op #2138 2020-06-07 10:43:43 +01:00
Lovell Fuller
7f142bddb3 Add level constructor opt for multi-level input #2222 2020-06-06 16:10:56 +01:00
Lovell Fuller
98e0516ac1 Tests: latest libvips sets JPEG density 2020-06-06 16:09:52 +01:00
Mikhail Bodrov
7717516d1d
Simplify is helpers (#2244) 2020-06-05 09:48:26 +01:00
Lovell Fuller
760550ca0d Expose levels metadata for multi-level images #2222 2020-06-04 20:29:02 +01:00
Lovell Fuller
f8144dd89c Bump dependencies 2020-06-04 20:17:15 +01:00
Lovell Fuller
ac4070cb49 Tests: skip empty Buffer test when *magick supported 2020-06-04 20:07:30 +01:00
Lovell Fuller
25b964e3df Docs: changelog and credit update for #2226 2020-05-28 22:42:37 +01:00
Lovell Fuller
17ec6c72df Docs: inline small external docute CSS/JS 2020-05-28 22:41:24 +01:00
Roman Malieiev
a7b1185602
Enable PNG palette when at least one of quality, colours, colors or dither is set (#2226) 2020-05-28 22:21:33 +01:00
Lovell Fuller
c76ae06fd1 Attempt to reduce file size of binaries at link time 2020-05-22 19:47:19 +01:00
Lovell Fuller
b3dd54d550 Changelog and doc update for #2217 2020-05-22 16:48:27 +01:00
malice00
d248eadb06
Allow libvips binary location override with version appended (#2217) 2020-05-22 16:07:32 +01:00
Lovell Fuller
507eef3053 Docs: reorder/highlight optional output properties 2020-05-19 18:55:33 +01:00
Lovell Fuller
fc2f672337 Improve error messaging when platform mismatch detected 2020-05-19 18:53:39 +01:00
Lovell Fuller
6f49be8f26 Docs: small perf boost by prefetching image DNS 2020-05-19 18:50:18 +01:00
Lovell Fuller
dad7f1e1f6 Release v0.25.3 2020-05-17 14:21:39 +01:00
Lovell Fuller
c3a9384dcf Upgrade deps that have dropped Node.js 8 support 2020-05-17 13:29:55 +01:00
Lovell Fuller
0ee08bfe46 Docs: lint JSDoc annotations when building docs 2020-05-15 14:07:27 +01:00
Lovell Fuller
0872f495f9 Tests: temporarily skip known failure on FreeBSD 2020-05-15 12:17:45 +01:00
Lovell Fuller
33ac8b93a9 CI: allow FreeBSD to update to latest packages 2020-05-13 16:12:17 +01:00
Lovell Fuller
bbff1c222d Docs: clarify description of withMetadata
Default and non-default behaviour was mixed in the same paragraph,
leading to confusion about when an ICC profile might be expected.
2020-05-13 16:01:03 +01:00
Lovell Fuller
b534f99870 Docs: correct typo in composite 2020-05-13 15:56:44 +01:00
Lovell Fuller
86acf2460e Allow parsing of SVG attribute values >10MB #2195 2020-05-06 20:56:08 +01:00
NickNaso
40c00035ee Docs: add N-API badge 2020-05-01 11:53:10 +01:00
Lovell Fuller
4673abae7d Docs: serve logo via CDN 2020-05-01 11:41:38 +01:00
Lovell Fuller
ef8a705957 Docs: move npm install command to examples 2020-05-01 11:38:09 +01:00
Lovell Fuller
48255fa009 Docs: serve logo via CDN 2020-05-01 11:27:00 +01:00
Lovell Fuller
ed6269bc9c Bump dependencies 2020-05-01 11:26:05 +01:00
Lovell Fuller
16b8d9afe5 Docs: changelog entry and credit for #2188 2020-05-01 11:25:43 +01:00
Dumitru
f29fcb1f73
Ensure npm platform flag is respected when copying DLLs 2020-04-29 18:24:27 +01:00
Lovell Fuller
b36ad25030 CI: Upgrade FreeBSD to version 13
It currently provides only vips v8.8.3 so will (still) fail.
2020-04-23 21:39:45 +01:00
Lovell Fuller
edf3fe24c9 CI: add Node.js 14 2020-04-23 21:30:04 +01:00
Lovell Fuller
5a1bdf0eb1 Bump deps: semver, documentation, nyc 2020-04-23 20:51:12 +01:00
Lovell Fuller
d8e24d7e76 Docs: slightly reduce whitespace before headings, lists 2020-04-23 20:47:10 +01:00
Floris de Bijl
786c5330e9
docs: change 'colourspace' to 'toColourspace' (#2174) 2020-04-21 09:44:22 +01:00
Lovell Fuller
70e730bb67 Docs: add basic search feature for install and API 2020-04-14 21:26:41 +01:00
Lovell Fuller
1d6ef630a5 Docs: extract might also be referred to as 'crop' 2020-04-14 21:24:26 +01:00
Vincent Voyer
1eedb22ef5 docs(clone): add promise example 2020-04-08 09:45:04 +01:00
Lovell Fuller
6ed1f49ad3 Ensure libvips is initialised only once #2143 2020-03-29 19:44:21 +01:00
Lovell Fuller
ecd01afad3 Docs: clarify JPEG quality/chromaSubsampling interdependence 2020-03-26 20:22:47 +00:00
Lovell Fuller
8bd8709f2b Release v0.25.2 2020-03-20 19:20:34 +00:00
Lovell Fuller
e82a585cec Ensure AsyncWorker options are persisted #2130 2020-03-19 21:21:21 +00:00
Lovell Fuller
c1d4a68558 Add changelog entry, docs and credit for #2098 2020-03-18 13:54:41 +00:00
Edward Silverton
eff36dc09f
Add IIIF layout support to tile-based output (#2098) 2020-03-18 13:27:54 +00:00
Lovell Fuller
031a58f817 Docs: AWS Lambda cross-platform no longer requires target flag 2020-03-17 18:33:49 +00:00
Lovell Fuller
cf39fc4fb1 Simplify tiled layout JPEG file extension logic 2020-03-14 22:08:46 +00:00
Lovell Fuller
c9bff94e17 Docs: expand descriptions of resize cover/contain 2020-03-14 21:34:48 +00:00
Lovell Fuller
e78e919925 Clarify diff between install vs bug issue templates 2020-03-10 21:36:48 +00:00
Lovell Fuller
76bb25262e Docs: ARM64/RHEL7 prebuilt binaries changelog entry 2020-03-10 21:22:30 +00:00
Lovell Fuller
d8426b1ed5 CI: Switch Linux x64 to CentOS 7 for glibc 2.17, gcc 4.8.5
Expand Linux ARM64v8 to all supported versions of Node.js
2020-03-10 19:39:26 +00:00
Lovell Fuller
4894c10dd9 Ensure consistent, correct detection of input opts #2118 2020-03-08 14:32:17 +00:00
Lovell Fuller
24285bb0e0 Release v0.25.1 2020-03-07 21:21:44 +00:00
Lovell Fuller
bf75501262 Ensure prebuilt binary based on N-API version 2020-03-07 20:59:25 +00:00
Lovell Fuller
9e214a17f0 Release v0.25.1 2020-03-07 19:12:32 +00:00
Lovell Fuller
0aae1ecd9b Ensure prebuilt binaries use N-API v4 #2117 2020-03-07 18:52:44 +00:00
Lovell Fuller
062f990315 Release v0.25.0 2020-03-07 12:44:42 +00:00
Lovell Fuller
22685e44c0 Upgrade to libvips v8.9.1 2020-03-07 10:15:51 +00:00
Lovell Fuller
8d66433e7c Docs: 32-bit Windows is supported (again) 2020-03-06 21:33:15 +00:00
Lovell Fuller
82863f48f6 Update issue templates to ask common follow-up questions 2020-03-06 21:12:59 +00:00
Lovell Fuller
51b14329d6 Simplify and future-proof tile option parsing 2020-03-06 20:06:41 +00:00
Lovell Fuller
14dc7681ed Upgrade to libvips v8.9.0-alpha2 prebuild
Improve tests for 32-bit ARM
2020-03-04 23:17:23 +00:00
Lovell Fuller
258c9e86eb Improve docs relating to single-channel raw pixel output 2020-03-01 14:22:49 +00:00
Joe Flateau
03dad5f2b2
Docs: clarify stats.isOpaque (#2094) 2020-02-24 20:35:36 +00:00
Lovell Fuller
86264e7733 Docs: update Lambda section to use Node.js 12 2020-02-24 20:31:17 +00:00
Lovell Fuller
95eae905f0 Ensure limitInputPixels, sequentialRead for composite op #2099 2020-02-24 16:02:36 +00:00
Lovell Fuller
a90dbcc808 Docs: improve a11y and metadata 2020-02-24 09:24:27 +00:00
Lovell Fuller
e9b21f2211 Ensure correct ordering of rotate-then-trim ops #2087 2020-02-23 16:59:22 +00:00
Lovell Fuller
409e5174bb Add support for 32-bit Windows (win32-ia32) 2020-02-19 23:00:23 +00:00
Lovell Fuller
8b3c0daab2 Upgrade to libvips v8.9.1-alpha1 prebuild 2020-02-19 11:41:18 +00:00
Lovell Fuller
c17807c995 Remove previously deprecated limitInputPixels, sequentialRead 2020-02-15 20:01:46 +00:00
Lovell Fuller
4abb4edf64 Migrate internals to N-API #1282 2020-02-15 19:38:15 +00:00
Lovell Fuller
d5ecc537af Release v0.24.1 2020-02-15 13:48:46 +00:00
Lovell Fuller
c7a49054fd Docs: update libvips URLs for band format/interpretation 2020-02-15 13:43:47 +00:00
Lovell Fuller
a2314c4aa0 Ensure RGBA LZW TIFF info.channel count #2064 2020-02-15 11:46:13 +00:00
Lovell Fuller
1717173f17 Tests: tighten composite offset thresholds 2020-02-15 10:53:30 +00:00
Lovell Fuller
e44c12f029 Bump dependencies, tar is now node>=10 2020-02-15 10:53:00 +00:00
Lovell Fuller
1a98c390fc Prevent sequentialRead for EXIF-based rotate op #2042 2020-01-20 21:50:43 +00:00
Lovell Fuller
91902740e4 Attempt to detect out-of-date homebrew-managed vips 2020-01-19 19:58:24 +00:00
Lovell Fuller
6aa6a93b44 Docs: add details of ignore-scripts to installation guide 2020-01-19 19:27:50 +00:00
Lovell Fuller
b4135ac9b3 Docs: fix any remaining redirects 2020-01-16 20:57:02 +00:00
Lovell Fuller
78906e6551 Update any remaining documentation links 2020-01-16 20:52:19 +00:00
Lovell Fuller
ba29ba1ab7 Release v0.24.0 2020-01-16 19:11:34 +00:00
Lovell Fuller
e0fa15f5cb Update performance test results 2020-01-16 18:56:25 +00:00
Lovell Fuller
82a1ff359d Update dev and bench dependencies 2020-01-15 21:17:25 +00:00
Lovell Fuller
18e1f10a94 Add support for input with 16-bit RGB profile #2037 2020-01-15 21:16:11 +00:00
Lovell Fuller
4828a17643 Tests: add fontconfig static data leak suppression 2020-01-15 21:08:45 +00:00
Lovell Fuller
3b4f95597a Prevent use of sequentialRead for rotate ops #2016 2020-01-14 08:34:54 +00:00
Lovell Fuller
bd52e93fca Deprecate limitInputPixels and sequentialRead, move to input options 2020-01-12 19:59:39 +00:00
Lovell Fuller
6fdc79d569 Docs: ARM64 has prebuilt libvips, not sharp 2020-01-12 10:50:14 +00:00
Lovell Fuller
7dbad7206e Drop support for undef input where opts also provided #1768 2020-01-11 12:02:31 +00:00
Lovell Fuller
a8a0c1e935 Update doc links contained within code
Throw rather than exit if require fails
2020-01-10 16:29:40 +00:00
Lovell Fuller
00bcf60566 Docs: metadata delay/loop properties 2020-01-09 23:04:06 +00:00
Lovell Fuller
4a745f2d2e Expose delay/loop metadata for animated images #1905 2020-01-09 22:51:08 +00:00
Lovell Fuller
057074b238 Docs: improve header layout on narrow screen devices 2020-01-08 23:13:33 +00:00
Lovell Fuller
4b8cc13a05 Add 2020 to list of copyright years 2020-01-08 21:20:53 +00:00
Lovell Fuller
a4e8586b59 Docs: rewrite installation guide 2020-01-08 21:04:16 +00:00
Lovell Fuller
095b37db6a Rename OS X as macOS
Bump CI to latest xcode available on maxOS 10.13
2020-01-08 21:03:50 +00:00
Lovell Fuller
efff650314 Upgrade to libvips v8.9.0 2020-01-08 16:18:43 +00:00
Lovell Fuller
0764ca8fde Changelog entry and credit for #2024 2020-01-08 16:04:42 +00:00
Brychan
403160434b Correctly bind max width and height values when using withoutEnlargement (#2024) 2020-01-07 12:10:35 +00:00
Lovell Fuller
730ab14faa Docs: correct SVG logo URL 2020-01-06 17:51:11 +00:00
Lovell Fuller
51d70c4574 Docs: switch hosting from Readthedocs to Firebase 2020-01-06 14:48:35 +00:00
Lovell Fuller
765ccd2aaa Docs: add icons 2020-01-06 14:44:07 +00:00
Lovell Fuller
5399332f81 Docs: improve section nesting levels 2020-01-06 14:26:54 +00:00
Lovell Fuller
43b7f9fc0e Docs: inject API section name as title 2020-01-04 11:11:27 +00:00
Sebin Benjamin
3925689435 Docs: initial setup for docute documentation site generator 2020-01-04 10:59:08 +00:00
Lovell Fuller
96a994a4c0 Move functions to improve logical ordering of docs 2020-01-03 20:58:57 +00:00
Lovell Fuller
84c20373ec Update leak test suppressions 2020-01-03 20:47:01 +00:00
Lovell Fuller
a216d2945b Upgrade to libvips v8.9.0-rc4, drop support for Node.js 8 2020-01-03 20:26:55 +00:00
Lovell Fuller
755a0caf3d Fix 16-bit, 2-channel PNG w/ ICC profile support #2013 2019-12-20 17:19:33 +00:00
Lovell Fuller
703d90e663 Docs: add example of using metadata and resize to scale 2019-12-16 21:15:49 +00:00
Lovell Fuller
e230ce41d7 Docs: remove references to unmaintained Docker images 2019-12-16 21:07:31 +00:00
Lovell Fuller
596b38a3bb Release v0.23.4 2019-12-05 10:00:29 +00:00
Lovell Fuller
d31a91a599 Expose raw TIFFTAG_PHOTOSHOP metadata #1600 2019-11-29 13:05:07 +00:00
Lovell Fuller
400ef71b6f Handle zero-length Buffers in Node.js v13.2.0+
These now use nullptr internally - see
https://github.com/nodejs/node/pull/30339
2019-11-28 21:20:32 +00:00
Lovell Fuller
bb15cd9067 Improve thread safety with copy-on-write for metadata #1986 2019-11-27 23:15:56 +00:00
Lovell Fuller
6ee6a226e1 Docs: add FreeBSD build status 2019-11-19 11:16:48 +00:00
Lovell Fuller
94d51a94c8 Docs: recommend jemalloc buildpack for Heroku 2019-11-19 11:13:25 +00:00
Lovell Fuller
d0feb4156c Release v0.23.3 2019-11-17 15:42:07 +00:00
Lovell Fuller
0d1278dade Improve C++ linting, move exceptions inline 2019-11-14 22:06:38 +00:00
Lovell Fuller
1b401b1195 Add FreeBSD to CI via Cirrus #1953 2019-11-14 21:55:20 +00:00
Lovell Fuller
11daa3b4d1 Tests: flatten to mid-grey before generating fingerprint 2019-11-14 13:18:14 +00:00
Lovell Fuller
88a3919ce0 Docs refresh 2019-11-14 11:32:49 +00:00
Lovell Fuller
c41b87303d Ensure trim op supports image-in-alpha #1597 2019-11-14 11:29:45 +00:00
Lovell Fuller
833aaead56 Ensure modulate can co-exist with other colour ops #1958 2019-11-11 22:16:28 +00:00
Lovell Fuller
ff98d2e44a Docs: using custom binaries with prebuild-install 2019-11-07 20:00:03 +00:00
Lovell Fuller
fcf05f608a Changelog entry for #1952 2019-11-07 19:59:18 +00:00
Pouya Eghbali
9baf38db44 Allow compilation of v0.23.x on FreeBSD and variants (#1952) 2019-11-06 23:11:44 +00:00
Lovell Fuller
69050ef1c8 Add funding link to libvips' Open Collective 2019-11-05 21:51:14 +00:00
Lovell Fuller
b35b9f7850 Ensure Travis does not cache builds #1948 2019-11-01 16:17:36 +00:00
Lovell Fuller
500ae97cac Changelog entry for #1921 2019-11-01 16:15:02 +00:00
Brendan Kennedy
d5b7040557 Ensure tile overlap option works as expected (#1921) 2019-10-30 20:02:07 +00:00
Lovell Fuller
ca52894651 Release v0.23.2 2019-10-28 18:21:11 +00:00
Lovell Fuller
4009acdd30 Docs: support added for Node.js 13 2019-10-28 18:19:33 +00:00
Lovell Fuller
147c93ecd3 Tests: increase coverage for jpeg-related logic 2019-10-27 20:03:10 +00:00
Lovell Fuller
8e04e4b07f Tests: add coverage for tiff quality option 2019-10-27 19:54:23 +00:00
Lovell Fuller
e7413ea1e5 Tests: increase coverage for metadata-related logic 2019-10-27 19:32:48 +00:00
Lovell Fuller
220bb03a32 Switch from excl npmignore to incl package.json files 2019-10-27 18:22:10 +00:00
Lovell Fuller
20f512fe5f Bump dependency patch versions 2019-10-26 23:15:41 +01:00
Lovell Fuller
efb3523eaa Remove duplicate validation from resize background 2019-10-26 23:13:12 +01:00
Lovell Fuller
2f2276e091 Changelog entries for #1924 #1932 2019-10-26 22:53:39 +01:00
Paul Neave
08a6597626 Add background option to tile output operation (#1924) 2019-10-25 14:30:33 +01:00
Nicolas Stepien
d82a6ee4fc Add Node.js 13 to CI (#1932) 2019-10-23 19:28:19 +01:00
Lovell Fuller
e627f6d68d Docs: clarify that input 'path' refers to the filesystem 2019-10-05 08:43:40 +01:00
Lovell Fuller
e650f58bd8 Improve error messaging for root/sudo permission problems 2019-10-04 12:14:08 +01:00
Lovell Fuller
5a9b6c8afd Tighten validation of page/pages constructor options 2019-10-03 16:41:32 +01:00
Lovell Fuller
075771d1e9 Improve error messaging for 404 errors on non-standard platforms 2019-10-03 15:32:15 +01:00
Lovell Fuller
4fcf091fef Bump tar dep (appears to be non-breaking despite major increment) 2019-10-03 15:30:56 +01:00
Marc Bornträger
0e66454fe4 Docs: Simplify Alpine Linux info, uses 3.10 instead of edge 2019-10-01 12:00:38 +01:00
Lovell Fuller
aa3ce760bb Release v0.23.1 2019-09-26 10:19:06 +01:00
Lovell Fuller
ba46ad1fd9 Docs: mention removal of metadata in output methods 2019-09-25 16:56:52 +01:00
Lovell Fuller
11214bab5d Bump tar dependency to ensure minipass >=2.8.6 2019-09-25 14:31:54 +01:00
Lovell Fuller
d87c289b4a Update results from latest benchmark test run 2019-09-25 14:16:51 +01:00
Lovell Fuller
af45c03b6f Bump benchmark dependencies ahead of a perf test run 2019-09-25 12:03:16 +01:00
Lovell Fuller
7d6fadce6b Ensure promise-based benchmark test is fairer
Real-world code will register a catch handler
2019-09-25 12:01:43 +01:00
Lovell Fuller
6b560f7a85 Remove imagemagick-native module from benchmarks
Unmaintained, does not compile with newer ImageMagick and Node
2019-09-25 10:13:45 +01:00
Lovell Fuller
5d4221460d Docs: Add more prominent link to libvips 2019-09-24 10:53:33 +01:00
Lovell Fuller
d42c383992
Add link from GitHub to libvips OpenCollective 2019-09-24 10:49:52 +01:00
Lovell Fuller
9c7f6fcb2b Replace deprecated URL parser
Fix up various linter errors
2019-09-22 22:46:48 +01:00
Lovell Fuller
14af0bda61 Regenerate flatten-rgb16-orange test expectation, reduce threshold 2019-09-21 20:01:15 +01:00
Raboliot le gris
fb5c393fbd Allow instance reuse with differing toBuffer options (#1860) 2019-09-08 14:35:16 +01:00
Lovell Fuller
69fe21a7ec Ensure invalid resize width/height as options throw #1817 2019-08-16 21:21:12 +01:00
Lovell Fuller
da4e05c118 Better validation and test coverage for background colours 2019-08-16 20:37:17 +01:00
Lovell Fuller
e4333ff6b0 Changelog entry, credit and doc update for #1835 2019-08-14 20:17:31 +01:00
Andargor
4ae8999f62 Add premultiplied option to composite operation (#1835) 2019-08-14 19:01:23 +01:00
Lovell Fuller
3fa91bb4ce Ensure image >= 3x3 before attempting trim operation
See https://github.com/libvips/libvips/issues/1392
2019-08-13 21:34:49 +01:00
Lovell Fuller
23b2e541ab Changelog entry for #1834 2019-08-12 21:45:29 +01:00
Julian Aubourg
5bfcf61a6f Allow use of heic/heif identifiers with toFormat (#1834) 2019-08-12 21:36:56 +01:00
Lovell Fuller
0778c112a9 Ensure sharp.format.vips is present and correct #1813 2019-08-12 21:25:10 +01:00
Lovell Fuller
2c300754a7 Expand issue templates to direct towards installation 2019-07-31 16:48:32 +01:00
Lovell Fuller
c610e306df Release v0.23.0 2019-07-29 14:45:46 +01:00
Lovell Fuller
417cca6e0d Use libvips built-in ICC profiles when required #1619 2019-07-29 14:16:21 +01:00
Lovell Fuller
2ed4b5ae83 Provide guidance on (mis)use of sudo with npm install 2019-07-29 11:48:18 +01:00
Lovell Fuller
16e429cf2c Add a few new leak test suppressions 2019-07-29 11:34:20 +01:00
Lovell Fuller
6b7ce8a605 Force V8 GC after each test during leak checks 2019-07-29 11:33:45 +01:00
Lovell Fuller
ba4ce75377 Ensure all WebP tests wait until Promises resolve 2019-07-29 11:32:31 +01:00
Lovell Fuller
76ded7fd28 Changelog entry and credit for #1755 2019-07-28 17:39:30 +01:00
Lovell Fuller
a0d1a7be50 Upgrade to libvips v8.8.1 2019-07-28 10:51:09 +01:00
Ilya Ovdin
690bc43abe Fix rotate/extract ordering for non-90 angles (#1755) 2019-07-26 20:28:45 +01:00
Lovell Fuller
50b461024d Add test coverage for single value extend operation 2019-07-26 19:31:14 +01:00
Lovell Fuller
6cf0b3240d Simplify 'this' in IO pipeline using arrow functions 2019-07-26 19:19:21 +01:00
Lovell Fuller
233b015d77 Improve consistency of validation error handling
Utilises common path of existing invalidParameterError
2019-07-26 14:58:54 +01:00
Lovell Fuller
28de243c11 Bump dependencies 2019-07-14 23:01:34 +01:00
Lovell Fuller
36e8a3da88 Expose libwebp smartSubsample and reductionEffort #1545 2019-07-14 22:52:38 +01:00
Lovell Fuller
119d16cad3 Ignore test coverage on more esoteric code paths 2019-07-14 21:52:29 +01:00
Lovell Fuller
38402d3185 Changelog entry for #1687 2019-07-12 12:15:24 +01:00
RaboliotTheGrey
6c02949fc1 Add skipBlanks support for tile layout (#1687) 2019-07-12 12:02:51 +01:00
Lovell Fuller
b737d4601e Add experimental support for HEIF images #1105
Requires a custom, globally-installed libvips compiled with libheif
2019-07-04 13:21:32 +01:00
jwater7
3ff3353550 Docs: vips is now available via the Alpine community repo (#1769) 2019-07-01 12:08:11 +01:00
Lovell Fuller
946d3c81a5 Add experimental support for Worker Threads #1558 2019-06-26 21:15:04 +01:00
Lovell Fuller
628996846d Allow use of failOnError with Stream-based input #1691 2019-06-26 19:37:27 +01:00
Lovell Fuller
631a3597c7 Upgrade to libvips v8.8.0, remove deprecated overlayWith 2019-06-26 18:32:53 +01:00
Marc Bornträger
cfa4f7d45c Docs: Alpine now provides vips package via community repo (#1730) 2019-05-30 09:02:32 +01:00
Lovell Fuller
05d76eeadf Release v0.22.1 2019-04-25 12:14:45 +01:00
Lovell Fuller
28a6c53da0 Prevent issue templates being published to npm 2019-04-25 12:14:17 +01:00
Lovell Fuller
6fcd2153c5 Docs: add support for Node 12 #1668 2019-04-25 12:01:14 +01:00
Lovell Fuller
7ae0512b9b Docs: clarify some output features require custom libvips 2019-04-25 11:39:30 +01:00
Nicolas Stepien
0890b59c32 Add Node 12 to Windows CI (#1669) 2019-04-25 11:24:35 +01:00
Lovell Fuller
df3ce450d9 Bump all dependencies 2019-04-25 09:51:59 +01:00
Lovell Fuller
bb0257b318 Remove not-yet-available Node 12 from Windows CI 2019-04-25 09:51:03 +01:00
Lovell Fuller
9c3597670d Add Node 12 to CI 2019-04-25 08:42:13 +01:00
Lovell Fuller
aa9b328778 Remove use of deprecated V8 API, swap v8::Handle for v8::Local #1668 2019-04-23 20:16:31 +01:00
tyankatsu
159e8dace2 docs: Fix path to CONTRIBUTING.md (#1666) 2019-04-20 19:19:14 +01:00
Lovell Fuller
3be4d5bb45 Ensure limitInputPixels check uses 64-bit unsigned type 2019-04-20 17:51:19 +01:00
Lovell Fuller
af7caa7b25 Docs: modernise contributing guide 2019-04-02 22:33:24 +01:00
Lovell Fuller
b4ede75522
Add issue templates (#1639) 2019-04-02 22:32:06 +01:00
Lovell Fuller
9d98114074 Move contributing info to GitHub-specific subdirectory,
which then allows for future possible issue/PR templates etc.
2019-04-02 21:03:57 +01:00
Lovell Fuller
4ac51899c3 Docs: minimum supported version of Node.js is 6 2019-04-02 20:41:23 +01:00
Lovell Fuller
90a0382317 Tests: use a concurrency of 1 on musl-based Linux
Should reduce a bit of pressure on the stack
2019-04-02 20:40:36 +01:00
Lovell Fuller
687795c801 Enhancement to and changelog entry for #1638
Remove bindings dependency as this isn't really... required
2019-04-02 20:39:06 +01:00
Sidhartha Chatterjee
2e0fbbb942 Add warning if sharp bindings aren't built correctly (#1638) 2019-04-02 17:00:55 +01:00
Lovell Fuller
0a3512d066 Unpin prebuild as 8.2.x is no longer breaking 2019-04-01 20:51:45 +01:00
Lovell Fuller
6032171f91 Docs: clarify use of integral pixel values for extract 2019-04-01 20:06:46 +01:00
Lovell Fuller
fc178de309 Changelog entry for #1601 2019-03-25 08:32:20 +00:00
Jakub Michálek
3f4398457f Change docs for composite to reflect how create works (#1623) 2019-03-25 07:45:46 +00:00
Jakub Michálek
b494b2e872 Add brightness, saturation and hue modulation #609 (#1601) 2019-03-25 07:44:07 +00:00
Lovell Fuller
18afcf5f90 Release v0.22.0 2019-03-18 23:26:39 +00:00
Lovell Fuller
87a422942d Pin prebuild due to breaking change in 8.2.0 2019-03-18 23:10:33 +00:00
Lovell Fuller
ac515121e5 Release v0.22.0 2019-03-18 21:31:46 +00:00
Lovell Fuller
2bfea0ad76 Docs: refresh usage examples 2019-03-18 21:29:17 +00:00
Lovell Fuller
83cdb558f6 Allow Stream-based input of raw pixel data #1579 2019-03-18 20:15:18 +00:00
Lovell Fuller
9ee377963e Improve error message if libvips tarball is corrupt 2019-03-17 23:07:58 +00:00
Lovell Fuller
9cc06c887b Add support for pages option for multi-page input #1566 2019-03-17 16:37:27 +00:00
Lovell Fuller
7457b50373 Remove unused shared library 2019-03-15 15:58:25 +00:00
Lovell Fuller
6387fb79b1 Small improvements to input and install docs, bump deps 2019-03-15 15:48:55 +00:00
Lovell Fuller
54e5514b9a Bump dependencies to latest 2019-03-10 18:14:43 +00:00
Lovell Fuller
1e4597c284 Changelog entry for #1595 (plus add GIF) 2019-03-10 17:26:26 +00:00
Lovell Fuller
7cafd4386c Add composite op, supporting multiple images and blend modes #728 2019-03-09 22:46:23 +00:00
Lovell Fuller
e3549ba28c Remove functions previously deprecated in v0.21.0
background, crop, embed, ignoreAspectRatio, max, min, withoutEnlargement
2019-03-01 23:43:35 +00:00
Lovell Fuller
d1bbe62e52 Rename armv8 as arm64v8 to match Node's process.arch 2019-03-01 23:43:35 +00:00
Lovell Fuller
36af74a09b Upgrade to libvips v8.7.4 2019-03-01 23:43:35 +00:00
Fabrizio Ruggeri
5afe02be60 Allow page input option to be set for PDF (#1595) 2019-03-01 23:29:34 +00:00
Jack Cross
2262959673 Docs: add missing comma to extend example (#1588) 2019-02-27 11:03:02 +00:00
Lovell Fuller
ba3f914445 Document support for animated WebP in metadata pages 2019-01-27 21:01:49 +00:00
Lovell Fuller
770be35c44 Tests: add a couple of extra leak suppressions for Node 2019-01-27 20:48:17 +00:00
Lovell Fuller
cc9f2b90fd Docs: use absolute URL for logo 2019-01-19 15:15:22 +00:00
Lovell Fuller
4aff57b071 Release v0.21.3 2019-01-19 14:25:37 +00:00
Maxime BACONNAIS
1df8d82fe0 Docs: overlay parameter of overlayWith is optional (#1547) 2019-01-19 14:19:41 +00:00
Lovell Fuller
98e90784f4 Docs: overlay parameter of overlayWith is optional 2019-01-19 14:11:54 +00:00
Lovell Fuller
87ea54cc66 Bump devDependencies 2019-01-19 14:06:16 +00:00
Lovell Fuller
d5e98bc8ad Split file-based input errors into missing vs invalid #1542 2019-01-19 11:59:36 +00:00
Lovell Fuller
fa69ff773a Input image decoding fail fast by default 2019-01-18 19:25:55 +00:00
Lovell Fuller
a183bb1cac Add valgrind memory leak suppressions 2019-01-18 12:08:28 +00:00
Lovell Fuller
cf62372cab Install: log the fallback to build from source
https://github.com/lovell/sharp-libvips/issues/18
2019-01-14 19:33:01 +00:00
Lovell Fuller
56fa9c95a1 Release v0.21.2 2019-01-13 10:26:47 +00:00
Lovell Fuller
32a34a8841 Tests: separate IO suite into per-format unit files 2019-01-13 10:11:32 +00:00
Lovell Fuller
98797445de Expose PNG output options requiring libimagequant #1484 2019-01-13 09:06:05 +00:00
Lovell Fuller
bd377438b6 Ignore colour profiles in LAB images as they are already LAB 2019-01-12 18:13:43 +00:00
Lovell Fuller
9dd6510de6 Expose underlying error message for invalid input #1505 2019-01-12 16:10:25 +00:00
Lovell Fuller
93ad9d4a4a Ensure all metadata removed from PNG unless withMetadata used 2019-01-09 21:17:53 +00:00
Lovell Fuller
4c01a099ea Add ensureAlpha op, adds alpha channel if missing #1153 2019-01-05 21:12:33 +00:00
Lovell Fuller
8e70579e47 Docs: use HTTPS links where available 2019-01-04 21:25:21 +00:00
Lovell Fuller
ee8bfa3980 Add 2019 to list of years of copyright 2019-01-04 16:05:26 +00:00
Lovell Fuller
c5dfa49cae Docs: add sharp logo to readme 2019-01-04 15:56:22 +00:00
Lovell Fuller
0822404129 Docs: expand logo viewBox to prevent clipping 2019-01-04 15:54:33 +00:00
Lovell Fuller
144f39cd45 Docs: add sharp logo, CC BY-SA 4.0 2019-01-04 15:12:53 +00:00
Lovell Fuller
87f191fd05 Node 11 now supported by nodejs/nan 2019-01-03 14:01:18 +00:00
Lovell Fuller
37ed436202 Version bump of devDependencies 2019-01-03 13:26:56 +00:00
Lovell Fuller
88e490356d Test: remove stray console.log 2019-01-03 12:35:54 +00:00
Lovell Fuller
7c631c0787 Ensure shortest resized edge is >= 1px #1003 2019-01-03 12:01:55 +00:00
Lovell Fuller
f5d3721fe0 Doc refresh for #1205 2019-01-02 19:04:49 +00:00
Lovell Fuller
cc633589d9 Expose pages metadata for multi-page input images #1205 2019-01-01 22:10:27 +00:00
Lovell Fuller
cc1d4c1a6d Expose palette-bit-depth metadata, requires upcoming libvips v8.8.0 2019-01-01 21:02:00 +00:00
Lovell Fuller
30ca424942 Apply correct forced output when chaining #1528 2019-01-01 18:40:09 +00:00
Pascal Temel
813831acf0 Docs: Update deprecated overlayWith example (#1526) 2018-12-30 20:44:36 +00:00
Lovell Fuller
a54fe9f77c Prevent mutatation of jpeg options #1516 2018-12-21 19:54:33 +00:00
Amila Welihinda
8c6da5548a Docs: change repo badge to SVG (#1498) 2018-12-10 11:03:03 +01:00
Lovell Fuller
a2aa7d69e7 Add error handler to download stream lovell/sharp-libvips#14 2018-12-08 13:56:05 +00:00
Lovell Fuller
34d5252242 Release v0.21.1 2018-12-07 19:23:54 +00:00
Lovell Fuller
f31e4d2869 Changelog, credit and doc refresh for #1483 2018-12-06 21:58:14 +00:00
Michael B. Klein
c695c40abc Expose libvips pyramid/tile options for TIFF output (#1483) 2018-12-06 22:33:46 +01:00
Lovell Fuller
fd1ca1dbb2 Ensure the tests for #1477 pass on OS X 2018-12-04 23:58:02 +01:00
Lovell Fuller
f25dbd5f61 Ensure the tests for #1477 pass on OS X 2018-12-04 23:45:08 +01:00
Keith
541e7104fd Expose libvips recombination matrix operation #1477 2018-12-04 23:06:34 +01:00
Lovell Fuller
94945cf6ac Changelog and credit for #1475 2018-12-04 07:49:41 +00:00
Lovell Fuller
db76e655f8 Ensure licensing checker works on Windows 2018-11-29 10:15:13 +00:00
Lovell Fuller
d43c7b581d Add licensing checker for production dependencies 2018-11-29 09:53:00 +00:00
Julian Aubourg
383b933e26 Build prototype with Object.assign to allow minification (#1475) 2018-11-26 19:40:06 +01:00
Lovell Fuller
d26ccf6294 Docs: update Alpine repository URLs 2018-11-21 22:42:58 +00:00
Lovell Fuller
6f9699f605 Ensure correct channel info for raw, greyscale output #1425 2018-11-19 20:00:30 +00:00
Quinn Pan
1e9093d781 Docs: correct code example in extend operation 2018-11-19 20:35:16 +01:00
Lovell Fuller
9dc6492e52 Docs: correct code example in extend operation 2018-11-19 19:34:16 +00:00
Lovell Fuller
d22f7cae6a Silence cast-function-type warnings from GCC 8+ 2018-11-19 18:47:35 +00:00
Lovell Fuller
473afaab45 Install: detect missing libvips on OpenBSD and SunOS
See https://github.com/lovell/sharp-libvips/issues/12
2018-11-19 18:46:05 +00:00
Lovell Fuller
dcd68303a4 Docs: add installation details for Lambda without Docker 2018-11-16 10:28:34 +00:00
Lovell Fuller
03394556b5 Update semistandard linter to latest 2018-11-11 18:05:40 +00:00
Lovell Fuller
1c4f6f75f3 Add Node 11 to CI, experimental only, no prebuild
Hide deprecation warnings - see nodejs/nan#811
2018-11-11 17:55:35 +00:00
Lovell Fuller
f00928dedb Doc refresh for #1438 #1439 2018-11-11 17:40:19 +00:00
Daiz
a48f8fbb61 Allow separate parameters for gamma encoding and decoding (#1439) 2018-11-11 10:15:38 +01:00
Daiz
1fa388370e Add support for the "mitchell" kernel for image reductions (#1438) 2018-10-28 15:11:27 +00:00
Christoph Tavan
95ef6b3f71 Docs: update Alpine libvips installation instructions (#1429)
With version 8.7.0 of the vips-dev Alpine package the documented installation instructions no longer work and result in:

ERROR: unsatisfiable constraints:
  pc:fftw3 (missing):
    required by: vips-dev-8.7.0-r0[pc:fftw3] vips-dev-8.7.0-r0[pc:fftw3] vips-dev-8.7.0-r0[pc:fftw3]

The fix was proposed in https://bugs.alpinelinux.org/issues/9561#note-2
2018-10-24 14:31:32 +01:00
Lovell Fuller
de11d36d00 Minor version bumps 2018-10-22 19:38:06 +01:00
Lovell Fuller
d77c2adabe Changelog and docs for #1422 2018-10-22 19:17:42 +01:00
SethWen
c89c055ae0 Install: add support for npm_config_sharp_dist_base_url (#1422) 2018-10-22 18:54:47 +01:00
Lovell Fuller
dac8117f32 Docs: ensure options are included for flatten op 2018-10-08 19:56:30 +01:00
Waylon Walker
937b091bab Docs: clear _libvips cache on Windows (#1403) 2018-10-07 16:49:05 +01:00
Lovell Fuller
019e6a1bfe Release v0.21.0 2018-10-04 13:03:30 +01:00
Lovell Fuller
1565e58fcf Update benchmark results ahead of v0.21.0
Remove lwip and images as they lack Node 10 support
2018-10-04 12:41:01 +01:00
Lovell Fuller
c22e2a17ef Update benchmark dependencies 2018-10-04 11:01:09 +01:00
Lovell Fuller
fd2a10ccea Threshold trim tests for non-turbo libjpeg 2018-10-02 20:33:26 +01:00
Lovell Fuller
0725378257 Add trimOffsetLeft, trimOffsetTop to trim response #914 2018-10-02 20:16:00 +01:00
Lovell Fuller
c431909f35 Refresh resize docs to ensure options are present 2018-10-02 18:45:08 +01:00
Lovell Fuller
db4df6f0b2 Add size to metadata response (Stream/Buffer only) #695 2018-10-02 18:05:08 +01:00
Lovell Fuller
17f942c802 Add chromaSubsampling and isProgressive to metadata #1186 2018-10-02 17:11:25 +01:00
Lovell Fuller
60438ebfe5 Ensure precision of trim threshold, update docs #914 2018-10-02 12:45:37 +01:00
Lovell Fuller
21fbe546b8 Switch from custom trim op to vips_find_trim #914 2018-10-02 11:24:32 +01:00
Lovell Fuller
11900945eb Bump dependency versions to latest 2018-10-02 11:23:49 +01:00
Lovell Fuller
ea5270221b Add new leak suppression for nodejs/libuv 2018-10-02 11:23:15 +01:00
Lovell Fuller
a64844689e Deprecate background, add op-specific prop to resize/extend/flatten #1392 2018-10-01 20:58:55 +01:00
Lovell Fuller
6007e13a22 Improve/increase installation error handling 2018-10-01 11:06:12 +01:00
Lovell Fuller
c3274e480b Deprecate crop, embed, ignoreAspectRatio, max, min, withoutEnlargement.
These become options of the resize operation instead. #1135
2018-09-30 20:16:27 +01:00
Miguel Aragón
3c54eeda5b Use more universal English to improve global understanding 2018-09-28 16:04:56 +01:00
Lovell Fuller
6236e4b97d Changelog entry and credit for #1385 2018-09-27 21:01:41 +01:00
freezy
796738da65 Add support for arbitrary rotation angle via vips_rotate (#1385) 2018-09-27 18:00:36 +01:00
freezy
37d385fafa Move background extraction into separate method (#1383) 2018-09-24 10:00:00 +01:00
Lovell Fuller
db2af42ee7 File extend, extract and trim ops under 'resize' #1135
Should make them easier to find in the docs
2018-09-22 14:52:08 +01:00
Lovell Fuller
24b42ef192 Tests: Move all setup to named file 2018-09-22 13:54:20 +01:00
Lovell Fuller
2ce166ab0a Update links to libvips, now in its own GitHub org 2018-09-21 20:33:01 +01:00
Lovell Fuller
71755b69e4 Remove duplicate libvips version/platform check 2018-09-21 20:20:40 +01:00
Lovell Fuller
1106aac2d8 Tests: tweak colour thresholds for (non-turbo) libjpeg compat 2018-09-21 19:51:47 +01:00
Lovell Fuller
93aac660a3 Tests: avoid shrink-on-load for (non-turbo) libjpeg compat 2018-09-21 19:34:52 +01:00
Lovell Fuller
0ce8ad7130 Enable CI on OS X 2018-09-20 10:41:24 +01:00
Lovell Fuller
deacd553bf Enable SIMD convolution by default #1213 2018-09-19 21:42:40 +01:00
Lovell Fuller
c8ff7e11a9 Upgrade to libvips v8.7.0
Drop Node 4 support
Add experimental musl prebuild for Node 8 and 10
2018-09-19 21:38:09 +01:00
Lovell Fuller
4cff62258c Improve smartcrop saliency testing/reporting 2018-09-05 22:49:31 +01:00
Lovell Fuller
0144358afb Release v0.20.8 2018-09-05 08:44:01 +01:00
Lovell Fuller
136097efe7 Downgrade nyc for continued Node 4 support 2018-09-04 17:07:10 +01:00
Lovell Fuller
374c6959d7 Changelog and credit for #1358 #1362 2018-09-04 16:39:24 +01:00
Axel Eirola
7d48a5ccf4 Allow floating point density input (#1362)
Metadata output will still remain integer
2018-09-01 08:58:30 +01:00
ajhool
bf3254cb16 Install: avoid race conditions when creating directories (#1358) 2018-08-29 09:20:26 +01:00
Lovell Fuller
5bed3a7d52 Release v0.20.7 2018-08-21 11:50:14 +01:00
Lovell Fuller
ece111280b Use copy+unlink if rename fails during install #1345 2018-08-20 15:14:31 +01:00
Lovell Fuller
a15a9b956b Release v0.20.6 2018-08-20 11:40:10 +01:00
Lovell Fuller
42860c2f83 Changelog, credit and doc refresh for #1342 2018-08-19 10:43:25 +01:00
Alun Davies
b5b95e5ae1 Expose depth option for tile-based output (#1342) 2018-08-18 15:09:53 +01:00
Lovell Fuller
d705cffdd6 Ensure extractChannel works with 16-bit images #1330 2018-08-12 20:22:39 +01:00
Rodrigo Alviani
23a4bc103e Docs: correct quality option in overlayWith example (#1325) 2018-08-08 08:42:18 +01:00
Lovell Fuller
c14434f9e7 Add removeAlpha op, removes alpha channel if any #1248 2018-08-07 20:32:11 +01:00
Lovell Fuller
25bd2cea3e Add experimental entropy field to stats response 2018-08-06 15:41:27 +01:00
Lovell Fuller
532de4ecab Cache libvips binaries to reduce re-install time #1301 2018-08-05 10:31:41 +01:00
Lovell Fuller
bfdd27eeef Doc refresh and dependency bumps 2018-08-05 09:42:09 +01:00
Lovell Fuller
bd9f238ab4 Improve install time error messages for FreeBSD #1310 2018-08-04 22:27:32 +01:00
Lovell Fuller
75556bb57c Ensure vendor platform mismatch throws error #1303 2018-08-04 21:34:11 +01:00
thegareth
2de062a34a Docs: update the "make a transparent image" example (#1316)
Alpha for colour is between 0-1, not 0-255.
2018-08-02 09:42:25 +01:00
Lovell Fuller
4589b15dea Changelog and credit for #1285 #1290 2018-07-10 16:12:16 +01:00
Sylvain Dumont
8b75ce6786 Allow full WebP alphaQuality range of 0-100 (#1290) 2018-07-10 15:58:17 +01:00
Espen Hovlandsdal
7bbc5176a1 Expose mozjpeg quant_table flag (#1285) 2018-07-10 15:56:05 +01:00
Lovell Fuller
5cb35485f1 Release v0.20.5 2018-06-27 08:44:31 +01:00
Lovell Fuller
80189ed689 Add changelog and credit for #1265 2018-06-27 07:54:41 +01:00
Muhammad Faheem Akhtar
3d7e8ef432 Docs: update new Buffer() to Buffer.from() (#1273) 2018-06-26 08:19:27 +01:00
Lovell Fuller
1999c7103c Docs: add CSS to improve left-hand nav nesting 2018-06-25 19:58:50 +01:00
Thomas Vantuycom
9c20ae383e Remove top of file table of contents in documentation (#1270) 2018-06-24 21:45:51 +01:00
Tom Lokhorst
76c41eaf05 Expose libjpeg optimize_coding flag (#1265) 2018-06-21 18:12:10 +01:00
Lovell Fuller
873aa6700f Release v0.20.4 2018-06-20 08:26:28 +01:00
Lovell Fuller
0d9590a9a0 Documentation refresh 2018-06-20 08:14:03 +01:00
Lovell Fuller
94607b585a Ensure extractChannel sets bw colourspace interp #1257 2018-06-19 22:47:52 +01:00
Lovell Fuller
da0b0348a2 Prevent rounding err with shrink-on-load and 90/270 rot #1241 2018-06-19 21:19:34 +01:00
Lovell Fuller
09263455b5 Release v0.20.3 2018-05-29 08:38:42 +01:00
Lovell Fuller
ddc23493d4 Add warning about possible concurrent tile race #1151 2018-05-25 19:53:23 +01:00
Lovell Fuller
54a71fc142 Fix tint op by ensuring LAB and allowing negative values #1235
Add test cases for more tint colours and input interpretations
2018-05-23 20:51:47 +01:00
Lovell Fuller
b1a9bf10a2 Pre-built binaries provided for even-numbered major versions 2018-05-21 11:44:34 +01:00
Lovell Fuller
97cfbe1b63 Bump dependency versions 2018-05-19 15:19:23 +01:00
Lovell Fuller
0ee8c63551 Replace use of libvips API deprecated since v8.6.1
See jcupitt/libvips@b085908
2018-05-19 15:03:50 +01:00
Lovell Fuller
0ac5a9ad82 Promote nw.js details to main installation docs - see 6e51f2d 2018-05-19 14:53:22 +01:00
Michael
6e51f2d608 rebuild doc for NW.js (#1229)
refers to https://github.com/lovell/sharp/issues/1223
2018-05-15 07:28:09 +01:00
Lovell Fuller
f23a8dc9dc Release v0.20.2 2018-04-28 18:29:32 +01:00
Lovell Fuller
d09fe6178c Add support for Node 10, drop support for Node 9 2018-04-28 18:12:10 +01:00
Lovell Fuller
ae2cfcc4f3 Version bumps, hold simple-get at v2 for Node 4 support 2018-04-28 18:11:20 +01:00
Lovell Fuller
853cc65e32 Changelog entry for #1208 2018-04-28 14:06:45 +01:00
Nathan Graves
5d140d949f Add support for Group4 (CCITTFAX4) compression to TIFF output (#1208) 2018-04-26 19:49:08 +01:00
Lovell Fuller
6d2da2b3ba Switch unzip test dependency for Node 10 support 2018-04-25 20:37:10 +01:00
Lovell Fuller
165e337e44 Changelog entry and doc refresh for #1204 2018-04-25 10:19:33 +01:00
Nathan Graves
b154cd0418 Add support for page selection with multi-page TIFF input (#1204) 2018-04-24 22:57:27 +01:00
Lovell Fuller
8ef1532691 Dependency version bumps 2018-04-17 20:46:22 +01:00
Lovell Fuller
771e44f2a7 Add error highlighting lack of Windows x86 node.exe support 2018-04-17 20:37:19 +01:00
Lovell Fuller
8933f1128d Changelog entry and credit for #1165 2018-04-11 20:30:16 +01:00
Rik Heywood
dbac4b9a63 Add tint operation to set image chroma 2018-04-11 20:05:48 +01:00
Lovell Fuller
bdac5b5807 Add code usage examples for output-related functions 2018-04-06 19:52:00 +01:00
Lovell Fuller
b0961b5213 Bump dependencies 2018-04-06 19:49:17 +01:00
Thomas Parisot
0d7c3fc4d8 Ignore global libvips during install via SHARP_IGNORE_GLOBAL_LIBVIPS (#1165) 2018-03-22 18:48:30 +00:00
Lovell Fuller
8dac256096 Release v0.20.1 2018-03-17 14:04:35 +00:00
Lovell Fuller
8320da39c3 Changelog entry and doc refresh for #1161 2018-03-17 11:12:43 +00:00
Andrea Bianco
875937e3d8 Expose libvips' median filter operation (#1161) 2018-03-17 10:52:44 +00:00
Lovell Fuller
f880adbaac Bump dependencies ahead of v0.20.1 2018-03-16 20:46:08 +00:00
Lovell Fuller
48c5f86adb Improve install when global libvips below min version #1148 2018-03-13 20:37:42 +00:00
Lovell Fuller
f60f7dab12 Prevent error when cumulative rounding below target #1154 2018-03-13 19:42:10 +00:00
Lovell Fuller
8f690236ed Release v0.20.0 2018-03-04 21:54:28 +00:00
Lovell Fuller
430a4297aa Add support for prebuilt sharp binaries on common platforms 2018-03-04 14:33:44 +00:00
Oskar Thornblad
69e3ab02c4 Mention EXIF orientation in metadata's jsdocs (#1142) 2018-03-04 14:19:53 +00:00
Lovell Fuller
b87a20b881 Release v0.19.1 2018-02-24 10:02:12 +00:00
Lovell Fuller
0e6f2d16ab Bump dependencies 2018-02-23 19:27:34 +00:00
Lovell Fuller
498b061819 Upgrade nan dependency, enables async hooks 2018-02-23 19:18:31 +00:00
Lovell Fuller
5ab6f599fb Prevent crop when at or below target dimensions #1134 2018-02-23 10:31:11 +00:00
Lovell Fuller
8b80626035 Changelog, credit and doc refresh for #1121 2018-02-18 19:14:37 +00:00
Andrea Bianco
f86ae79fdb Expose angle option in tile feature (#1121) 2018-02-18 20:00:08 +01:00
Lovell Fuller
1a4e68096f Changelog and credit for #1024, bump dependencies 2018-02-04 13:30:47 +00:00
Marcel
d599d1f29e Expose linear transform feature of libvips (#1024) 2018-02-04 10:36:04 +00:00
Lovell Fuller
73edfb3d2c Update list of files that npm can ignore 2018-01-13 10:28:31 +00:00
Lovell Fuller
ebae68d579 Doc refresh for #1077 2018-01-13 10:27:43 +00:00
Tony Mobily
573836e2b8 Add mention of max() to preserve ratio in withoutEnlargement (#1077) 2018-01-13 09:59:59 +00:00
Lovell Fuller
da5deb8177 Release v0.19.0 2018-01-11 22:31:51 +00:00
Lovell Fuller
8fca89e876 Update documentation hostname 2018-01-10 23:35:50 +00:00
Lovell Fuller
d5295a2d0c Doc refresh for #1079 2018-01-10 22:24:46 +00:00
Oleg Aleynik
c4df115948 Expose IPTC and XMP metadata when available (#1079) 2018-01-10 22:12:11 +00:00
Lovell Fuller
8afcb16d8e Update performance benchmark results for v0.19.0 2018-01-07 14:30:25 +00:00
Lovell Fuller
3764d63244 Add valgrind suppressions for Node 8 2018-01-06 13:39:26 +00:00
Lovell Fuller
c82914df30 Doc refresh and devDependencies version bumps 2018-01-06 00:07:35 +00:00
Lovell Fuller
84ba921f5b Unpin tar dep as race condition is fixed - see 053e727 2018-01-05 10:51:24 +00:00
Lovell Fuller
8e74668e3c Update linter plus related spacing fixes 2018-01-05 10:18:08 +00:00
Lovell Fuller
707c05b5f5 Update libvips dependency minimum to v8.6.1 2018-01-05 09:57:33 +00:00
Lovell Fuller
9bd2cec199 Update benchmark test dependencies 2018-01-02 20:19:11 +00:00
Lovell Fuller
358b8fe8b6 Refresh Lambda install docs to recommend use of Docker 2017-12-22 19:31:03 +00:00
Lovell Fuller
7115ae5375 Prevent toFile ext taking precedence over toFormat #1037 2017-12-20 20:33:08 +00:00
Lovell Fuller
13997ca653 Run unit test files sequentially through valgrind 2017-12-18 19:57:26 +00:00
Lovell Fuller
9fa04a0b93 Attach event listener to clone only for Stream #995 2017-12-12 21:53:27 +00:00
Lovell Fuller
0894145284 Changelog and doc refresh for #1038 2017-12-12 19:42:07 +00:00
Kenric D'Souza
927b77700d Add gravity support to embed feature (#1038) 2017-12-12 19:29:16 +00:00
Lovell Fuller
1d7a0ea99e Changelog and doc refresh for #915 2017-12-09 13:14:23 +00:00
Rahul Nanwani
d6aee8e5ba Add pixel-derived image statistics via vips_stats (#915) 2017-12-09 11:17:48 +00:00
Lovell Fuller
dfaa39fa5d Enable OS X CI 2017-12-09 10:47:02 +00:00
Lovell Fuller
8fe3b59efe Update test fixtures for e9b7231ac0 2017-12-08 17:54:39 +00:00
Lovell Fuller
47237b1f15 Add expected min libvips version to error messages 2017-12-07 23:16:33 +00:00
Lovell Fuller
053e727bd5 Pin tar dependency as latest version has a race condition with Node 4 2017-12-01 19:00:28 +00:00
Lovell Fuller
2ce9e81d80 Wait for close event before decompressing tarball
Should reduce the chance of a race condition
2017-11-30 20:29:18 +00:00
Lovell Fuller
50848ee462 Add unit test coverage report for C++ 2017-11-30 20:16:30 +00:00
Lovell Fuller
ef06d560cd Windows CI: retry npm install to workaround race condition 2017-11-30 20:12:14 +00:00
Lovell Fuller
2abf9f96c7 Force TIFF predictor=none to match fixture in squash tests 2017-11-27 19:55:20 +00:00
Lovell Fuller
a91686b4cd Temporarily revert to previous npm for Node 9 support 2017-11-27 19:38:44 +00:00
Lovell Fuller
1be424cd47 Add missing file from commit fc233ed 2017-11-27 19:35:08 +00:00
Lovell Fuller
929ea10f76 Re-enable test for 1200 DPI SVG rasterisation to PNG 2017-11-27 19:31:31 +00:00
Lovell Fuller
11d1f39e3d Add Node 9 to CI test environments 2017-11-27 19:15:09 +00:00
Lovell Fuller
fc233ed4ff Update upstream libvips source to v8.6.0-beta1 2017-11-27 19:14:30 +00:00
Lovell Fuller
efd2e893cf Ensure expected fixtures match libvips v8.6.0 behaviour 2017-11-27 19:13:39 +00:00
Lovell Fuller
2a18b9a8f7 Remove centreSampling option, update some expected test fixtures
See https://github.com/jcupitt/libvips/issues/705
2017-11-26 13:49:56 +00:00
Lovell Fuller
6aa214181b Version bump dependencies 2017-11-25 11:25:27 +00:00
Lovell Fuller
7067beda99 Docs refresh for cropOffsetLeft/cropOffsetTop 2017-11-25 11:24:53 +00:00
Lovell Fuller
e0f0baf164 Silence a couple of MSVC type conversion warnings 2017-11-17 20:10:10 +00:00
Lovell Fuller
1fec132dee Add tilecache before smartcrop to avoid over-computation 2017-11-17 19:53:50 +00:00
Lovell Fuller
ba521fccb4 Replace caw with its tunnel-agent dependency 2017-11-07 19:38:10 +00:00
Lovell Fuller
965a97105e Default TIFF predictor to horizontal to match libvips' behaviour 2017-10-19 19:40:07 +01:00
Lovell Fuller
3c88c84998 Doc refresh, changelog and dead code removal for #977 2017-10-19 11:05:43 +01:00
Jarda Kotěšovec
d0f66c3734 Switch to libvips' resize, make fastShrinkOnLoad optional (#977) 2017-10-19 11:05:43 +01:00
Lovell Fuller
ebc2a741f6 Ensure accessMethod is applied during shrink-on-load 2017-10-19 11:05:43 +01:00
Lovell Fuller
d46512af1c Doc refresh and changelog entry for #976 2017-10-19 11:05:43 +01:00
Matthew McEachen
b4d72bd544 Add failOnError option to fail-fast on bad input image data (#976) 2017-10-19 11:05:43 +01:00
Lovell Fuller
382d476271 Temporarily allow CI failures on OS X 2017-10-19 11:05:43 +01:00
Lovell Fuller
80c240b54a Add compile time check for libvips 8.6.0+ 2017-10-19 11:05:43 +01:00
Lovell Fuller
21f99d88ab Docs: possible to install libvips via pkg on FreeBSD 2017-10-19 11:05:43 +01:00
Lovell Fuller
d5873a00d5 Docs refresh 2017-10-19 11:05:43 +01:00
Lovell Fuller
99076edc89 Default PNG output to adaptiveFiltering=false, compressionLevel=9
PNG is mostly used for logos and line art, so these defaults will
produce the smallest files for most output most of the time.
2017-10-19 11:05:43 +01:00
Lovell Fuller
7b6c80327e Verify platform of vendor binaries at install and run time 2017-10-19 11:05:43 +01:00
Lovell Fuller
57946ed672 Upgrade to libvips v8.6.0
Expose offset coordinates of strategy-based crop
Switch to Github releases for prebuilt libvips
Move packaging scripts to lovell/sharp-libvips repo
2017-10-19 11:05:43 +01:00
Aditya Bharti
aad16ac50d Improved jsdocs for withoutEnlargement and sequentialRead #972 (#992) 2017-10-15 09:28:08 +01:00
Brooks Becton
bbe897e607 Added Coding tools section and added types link (#975) 2017-10-04 13:02:11 +01:00
Mika Fischer
eca0e66e23 Remove use of dynamic require to facilitate bundling (#960) 2017-09-25 21:00:40 +01:00
Lovell Fuller
3511723914 Release v0.18.4 2017-09-18 18:26:12 +01:00
Lovell Fuller
6a1c7b7588 Ensure input Buffer really is marked as Persistent #950 2017-09-16 20:17:32 +01:00
Lovell Fuller
18fd6ef119 Release v0.18.3 2017-09-13 10:51:08 +01:00
Matt Parrish
0004f5d2ff Migrate from got to simple-get (#945)
The simple-get module provides support for basic auth and
is already used by the future prebuild dependency.
2017-09-12 07:38:17 +01:00
Mario Viens
5f29d1ba9c Clarifying cache documentation (#919) 2017-08-19 10:43:36 +01:00
Jasper Blues
791fd35c35 Update README.md (#913) 2017-08-16 12:09:02 +01:00
Kleis Auke Wolthuizen
e0d622d347 Skip shrink-on-load when trimming (#887) (#888) 2017-07-28 21:02:30 +01:00
Lovell Fuller
6b34e8a804 Docs: FreeBSD gcc v4/v5 needs _GLIBCXX_USE_C99 for C++11 #873 2017-07-25 14:54:44 +01:00
Lovell Fuller
eb8773fe3e Use detect-libc instead of ldd output parsing 2017-07-17 12:11:13 +01:00
Lovell Fuller
b40e3fa1f1 Docs: Alpine vips-dev package requires fftw-dev also 2017-07-15 14:47:25 +01:00
Lovell Fuller
d25d761b55 Update benchmark deps, allow node-images to fail 2017-07-14 13:18:13 +01:00
Lovell Fuller
d6051dd714 Release v0.18.2 2017-07-01 09:52:47 +01:00
Lovell Fuller
53ff061efa Document SHARP_DIST_BASE_URL #841 2017-07-01 09:44:02 +01:00
Lovell Fuller
72b0efd393 Remove possible switch case fall through
Luckily there were no side effects in this... case
2017-06-25 19:09:20 +01:00
Lovell Fuller
df97ef23d9 Document/changelog for Solus Linux support #857 2017-06-25 17:42:03 +01:00
Ekrem Karaca
f6373971bd Add support for Solus OS (#857) 2017-06-24 13:48:03 +01:00
Lovell Fuller
ec617f2489 Document minimum Node dependency of v4.5.0 #847 2017-06-20 22:05:05 +01:00
Lovell Fuller
502ae78579 Allow binary download URL override via SHARP_DIST_BASE_URL #841 2017-06-20 21:40:46 +01:00
Lovell Fuller
49297d6afb Ensure flip and flop operations work with auto-rotate #837 2017-06-19 23:42:26 +01:00
Lovell Fuller
29354badd8 Docs: add Alpine Linux install details 2017-06-19 08:13:49 +01:00
Lovell Fuller
3c4de796c8 Dependency bumps and next point release 2017-06-04 19:55:45 +01:00
Lovell Fuller
c7f4488e77 Docs and changelog entry for #828 2017-06-04 19:51:22 +01:00
Yves Bos
d8765f955d Allow xres and yres to be set for TIFF output (#828) 2017-06-03 10:52:09 +01:00
Lovell Fuller
9f20037dad Release v0.18.1 2017-05-30 21:02:35 +01:00
Lovell Fuller
2ebb090df2 Update Travis CI to Ubuntu 16.04
Rollback Appveyor CI from Node 8 to 7
2017-05-30 20:50:32 +01:00
Lovell Fuller
110fff3ab9 Replace Node 7 with Node 8 in CI environment 2017-05-30 20:32:15 +01:00
Lovell Fuller
f42a1ceab7 Recalculate residual after adjusting shrink #831 2017-05-30 20:22:15 +01:00
Lovell Fuller
9e39a7fa95 Correct shrink calc, regression introduced in e398b47 #831 2017-05-30 17:16:41 +01:00
Lovell Fuller
c879df3b31 Release v0.18.0 2017-05-30 08:09:59 +01:00
Lovell Fuller
361ed98353 Remove previously-deprecated output format 'option' functions 2017-05-23 21:57:05 +01:00
Lovell Fuller
d45f8ef2d3 Document the cache-free nature of metadata extraction #796 2017-05-23 21:24:29 +01:00
Lovell Fuller
d6a63d11d7 Docs refresh 2017-05-22 21:49:37 +01:00
jingsam
4c6804eadc Add toFormat 'jpg' alias for 'jpeg' (#814) 2017-05-22 12:59:43 +01:00
Nicolas Coden
99810c0311 Add support for any rotation angle (#791)
Allow to provide any positive or negative multiple of 90 to `.rotate(...)`.
Negative angles and angles above 360 are converted to valid 0/90/180/270
rotations (0 rotations are still ignored).

Changes:
- [Node] Add `useExifOrientation` internal variable to know if the Exif
  orientation must be used instead of the provided angle. This allows to save a
  negative angle in the `angle` option, because the `-1` special case is not
  needed.

- [Node] Change check for planed-rotation in extract, to prepare a
  rotation before extraction: check with both `angle` and `useExifOrientation`
  options.
  I think this check contains a bit too much logics on rotation options. Maybe
  we could move this condition to a dedicated function.

- [C++] Separate `CalculateRotationAndFlip` into two generic functions:
  - `CalculateExifRotationAndFlip`: Calculate the angle of rotation and
    need-to-flip for the given Exif orientation.
  - `CalculateAngleRotation`: Calculate the rotation for the given angle.

  One or the other function is used to calculate the rotation, depending on
  wether the Exif orientation tag or the provided angle must be used.

- Add unit tests for `-3690`, `-450`, `-90`, `90`, `450`, `3690` and `-3780`,
  `-540`, `0`, `180`, `540`, `3780` rotations
- Add `320x240` fixture image for tests.

Unrelated changes (squashed):
- Add ncoden to the list of contributors
2017-05-22 11:08:33 +01:00
gmaliar
d15fb1ab1b Docs: add link to TailorBrands-maintained libvips Dockerfiles (#813) 2017-05-21 20:37:57 +01:00
Lovell Fuller
0a6d8b37ad Ensure double to int cast introduced in 4d1a169 is static 2017-05-21 19:05:56 +01:00
Lovell Fuller
f78ffdb9ce Upgrade to libvips v8.5.5 2017-05-21 18:31:06 +01:00
Lovell Fuller
b7b6fdbdf5 Update perf test contenders, add node-images 2017-05-13 20:08:53 +01:00
Lovell Fuller
e398b471e1 Prevent aliasing by using dynamic values for shrink(-on-load) 2017-05-13 18:46:39 +01:00
Lovell Fuller
48f69f3d88 Upgrade libpng to v1.6.29 2017-05-13 18:20:54 +01:00
Lovell Fuller
95850d75f6 Include pixel format depth when reading metadata 2017-05-07 09:29:38 +01:00
Lovell Fuller
c41d755441 Ctor single arg: allow plain object, reject null/undefined
Thank you @kub1x
2017-05-06 19:03:14 +01:00
Lovell Fuller
39a21787b7 Remove 'require' test as bufferutil now ships prebuilt 2017-05-06 15:49:50 +01:00
Lovell Fuller
36078f9903 Switch to the libvips crop strategy implementations 2017-05-06 14:46:28 +01:00
Lovell Fuller
2f534dc01c Base maximum output dimensions on limitation of format 2017-05-04 23:20:37 +01:00
Lovell Fuller
c8e59f08ec Add support for Buffer and Stream-based TIFF output 2017-05-04 16:40:49 +01:00
Lovell Fuller
19dd6a997f Doc refresh, thank you @cspotcode 2017-05-01 09:34:10 +01:00
Lovell Fuller
4d1a1694cd Improve perf/accuracy of nearest neighbour integral upsample 2017-04-30 20:54:48 +01:00
Lovell Fuller
52bea15ad7 Upgrade libvips dependency to v8.5.4, plus other bumps 2017-04-26 23:04:08 +01:00
Lovell Fuller
6592361c5a Ensure ARM64 pre-built binaries use correct C++11 ABI 2017-04-26 21:41:03 +01:00
Lovell Fuller
f3f83494f5 Credit contributor YvesBos 2017-04-26 21:40:30 +01:00
Lovell Fuller
1169afbe90 Avoid (un)premultiplication for overlay image without alpha channel
Add 'premultiplied' boolean attribute to output info, helps test
2017-04-26 21:37:43 +01:00
Lovell Fuller
301bfbd271 Expose libvips warnings via NODE_DEBUG env var 2017-04-26 21:37:43 +01:00
Lovell Fuller
46aec7eabc Upgrade libvips dependency and packaging to v8.5.1 2017-04-26 21:37:43 +01:00
YvesBos
4cd3b66761 Add support for squashing TIFF output to 1-bit (#783) 2017-04-26 17:47:29 +01:00
Jakub Podlaha
567e3dd258 Add gentoo support to glibc detection (#760) 2017-04-06 15:17:30 +01:00
Lovell Fuller
fcf853712c Release v0.17.3 2017-04-01 10:20:44 +01:00
Lovell Fuller
088d36b47b Add support for TIFF float predictor 2017-04-01 10:08:47 +01:00
Lovell Fuller
27fb864ac4 Update dev deps, deconstify all the functions, API doc refresh 2017-03-31 21:42:23 +01:00
Lovell Fuller
4001c4a48a Add changelog and credit for #738 2017-03-31 21:17:19 +01:00
Sagiv Frankel
f64c18ef15 Docs: Add download info to Heroku section (#748) 2017-03-30 12:55:33 +01:00
Kristo Jorgenson
f8e72f443d Expose TIFF compression and predictor options (#738) 2017-03-29 12:12:04 +01:00
Lovell Fuller
5e015cc3ca Docs: use NODE_MODULES_CACHE=false for Heroku+yarn #722 2017-03-27 20:31:50 +01:00
Andreas Lind
9707f8c5d2 Add support for passing the crop strategy as a string (#735) 2017-03-16 14:27:09 +00:00
Lovell Fuller
6b1d698448 Add credit and changelog for #732 2017-03-16 07:37:05 +00:00
Alice Monday
72f69dda30 Add support for the "nearest" kernel for image reductions (#732) 2017-03-14 10:29:23 +00:00
Lovell Fuller
8b5d8a0577 Switch from seq to random access for normalise and 'smart' crop 2017-03-11 19:56:55 +00:00
Lovell Fuller
1aa053ce6f Create blank image (width, height, channels, background) #470 2017-03-11 11:46:01 +00:00
Lovell Fuller
701b1c4216 Document overlayWith image density parameter #729 2017-03-10 22:59:46 +00:00
Lovell Fuller
f1c4cef781 Version bump of dev dependencies 2017-03-04 22:28:01 +00:00
Lovell Fuller
6fe5b307b1 Allow toBuffer to resolve Promise with info+data #143 2017-03-04 22:15:31 +00:00
Lovell Fuller
679ce08998 Small doc updates 2017-03-04 18:37:23 +00:00
Lovell Fuller
eeb923eb5b Update docs domain name 2017-03-04 18:36:18 +00:00
Lovell Fuller
142c431745 Release v0.17.2 2017-02-11 10:35:34 +00:00
Lovell Fuller
81f5589411 Add use of 'cc' to improve C++ code style linting 2017-02-11 09:59:23 +00:00
Mark van Seventer
04f5c884a4 Add CLI tools section to installation guide (#691) 2017-01-25 21:34:23 +00:00
Lovell Fuller
d8df503404 Ensure Readable can start flowing after Writable finish #671 2017-01-22 14:03:06 +00:00
Lovell Fuller
d241efcdbe Add changelog entry and credit for #685 2017-01-22 13:58:11 +00:00
Rahul Nanwani
a1b8efe721 Expose WebP alpha quality, lossless and near-lossless output options (#685) 2017-01-19 13:45:32 +00:00
Lovell Fuller
815d076b35 Release v0.17.1 2017-01-15 15:23:49 +00:00
Lovell Fuller
86b4816b3f Allow HTTP-over-HTTPS proxy when d/l pre-compiled deps #679 2017-01-14 11:23:13 +00:00
Lovell Fuller
473055468a Docs: ensure alpha attribute is used for transparency 2017-01-13 21:24:57 +00:00
Brandon Aaron
c6a28db8b1 Packaging: bump zlib to 1.2.10 and png16 to 1.6.28 (#676) 2017-01-10 18:19:23 +00:00
子龙山人
971f567571 Docs: correct alpha attribute in extend background example (#675) 2017-01-09 10:47:02 +00:00
Lovell Fuller
7e2eca3d1e Credit recent new contributors, thank you! 2017-01-05 22:27:30 +00:00
Lovell Fuller
86b0053bf0 Removed preinstall.sh script 2017-01-05 22:21:41 +00:00
Lovell Fuller
cfc4b282f0 Doc refresh for d9b667e 2017-01-05 22:20:33 +00:00
Lovell Fuller
b85d2aa565 Merge branch 'master' of https://github.com/lovell/sharp 2017-01-05 22:17:16 +00:00
Lovell Fuller
70a3d4fb5e Improve error messages for invalid resize parameters
Dependency version bumps and doc refresh
2017-01-05 22:17:04 +00:00
Adam Coyne
d9b667e346 Docs: remove parentheses from sharp.format (#663) 2016-12-31 19:32:18 +00:00
Jérémy Lal
3a1db53d5a Simpler expression for finding vips-cpp libdir (#656)
Fixes: #655
2016-12-18 08:57:50 +00:00
Lovell Fuller
4858ebe051 Release v0.17.0 2016-12-11 19:22:14 +00:00
Lovell Fuller
d2455267a8 Allow non-RGB input to embed/extend onto bg with alpha #646 2016-12-11 16:01:21 +00:00
Lovell Fuller
61721bb086 Remove preinstall ref from docs ahead of script removal 2016-12-11 15:21:30 +00:00
Lovell Fuller
3e76ee25e3 Update semistandard dependency plus linting improvements 2016-12-05 21:22:40 +00:00
Lovell Fuller
a71e562ff7 Upgrade to latest v1.x.x major version of the color dependency.
Uses 'alpha' instead of 'a' to represent transparency values.
2016-12-04 21:04:18 +00:00
Lovell Fuller
850fc9adf9 Increase threshold for OS X gamma test 2016-12-04 19:38:05 +00:00
Lovell Fuller
d3c78f825c Ensure premultiply op occurs before box shrink #605 2016-12-04 18:25:44 +00:00
Lovell Fuller
7231d92d1f Autoconvert GIF+SVG input to PNG output if no format specified 2016-11-30 22:46:04 +00:00
Lovell Fuller
93e14484da Update dev dependencies, regenerate API docs 2016-11-27 22:29:57 +00:00
Lovell Fuller
d7d03b1ca2 Update benchmark target image height for fairer tests #624 2016-11-27 22:17:09 +00:00
Lovell Fuller
dfd6d95209 Remove slightly-too-experimental TypeScript definitions.
To be revisited, perhaps during 2017, when tooling has improved.
2016-11-21 22:29:30 +00:00
Lovell Fuller
e4e7384f99 Move lib/types.d.ts generation to separate script.
Fixes Promise<T>, ensures module prefix is declared.
2016-11-20 11:24:12 +00:00
Lovell Fuller
effa77afee Docs/types: add Promise<T> and Array<T> #472
Changelog updates and version bump of devDeps
2016-11-17 21:29:41 +00:00
Patrick Paskaris
6ccccf8c39 Allow use of extend with greyscale input (#623) 2016-11-14 22:09:43 +00:00
Lovell Fuller
dd9d66ef20 Update output docs to include tile image format.
Correct some of the JPEG output option type defs.
2016-11-13 21:03:18 +00:00
Patrick Paskaris
bc84d1e47a Allow PNG and WebP tile-based output in addition to JPEG (#622) 2016-11-13 20:36:43 +00:00
Lovell Fuller
6b426014ad Provide experimental, automated TypeScript declaration #472 2016-11-08 14:21:38 +00:00
Lovell Fuller
c6f12fe033 Small doc update and dep bumps ahead of v0.17.0 2016-11-08 12:03:55 +00:00
Lovell Fuller
bb096ac617 Final update to preinstall.sh before it goes away 2016-11-08 11:55:46 +00:00
Lovell Fuller
734df539dd Patch libtiff v4.0.6 with latest security fixes 2016-11-08 11:54:41 +00:00
Lovell Fuller
27b9481452 Update benchmarks ahead of sharp v0.17.0 with libvips v8.4.2.
Ubuntu provides newer *magick than Amazon, so this is fairer on it.
Add note about the serious security vulnerabilities in lwip.
2016-11-08 11:21:32 +00:00
Lovell Fuller
945706c2a4 Remove use of deprecated API from benchmark
Add mapnik as possible contender
2016-11-07 18:53:54 +00:00
Lovell Fuller
a7b024d4fa Tile-based output filename may not exist, check g_stat return value 2016-11-06 14:31:32 +00:00
Lovell Fuller
9911863441 Expose libvips centre option, mimics *magick +0.5px convention 2016-11-04 18:17:33 +00:00
Lovell Fuller
deb978bf57 Remove use of deprecated functions from test code 2016-11-04 10:18:29 +00:00
Lovell Fuller
55998707a5 Regenerate docs 2016-11-02 18:04:00 +00:00
Lovell Fuller
4af702ee11 Docs: change Deep Zoom file extension for libvips v8.4.2+ 2016-11-02 17:25:18 +00:00
Lovell Fuller
8717ecc429 Modularise JS source in 'lib' subdirectory.
Generate public API documention via jsdoc comments.
2016-11-02 09:25:20 +00:00
Lovell Fuller
552cfd6ff1 Store pre-compiled binary dependencies in 'vendor' directory.
This frees up 'lib' directory to allow for more modular JavaScript.
2016-11-02 09:25:20 +00:00
Lovell Fuller
928edfd1dd Ensure jsdoc comments/types exist for all public methods.
This is a precursor to fully-automated docs and typings.
2016-11-02 09:25:20 +00:00
Lovell Fuller
98fb2e73f9 Remove trailing space from pkg-config libs output
Workaround for bug in pkg-config prior to v0.29
2016-11-02 09:25:20 +00:00
Lovell Fuller
de09577342 Put back overzealous code removal from 2470e5c 2016-11-02 09:25:20 +00:00
Lovell Fuller
cbdbbe535a Update tests to meet semistandard code standards
Switch to const/let instead of var
2016-11-02 09:25:20 +00:00
Lovell Fuller
36e636dca1 Drop support for versions of Node prior to v4.
Reduce production (sub)depedency count from 93 to 50.
Modernise dev tooling, e.g. use nyc, replace jshint with semistandard.
Make 'npm test' command consistent across platforms.
2016-11-02 09:25:20 +00:00
Lovell Fuller
3f5e38bb62 Deprecate output format option functions.
Access is now via options of existing output format functions.

e.g. use .jpeg({quality: n}) instead of .jpeg().quality(n)
2016-11-02 09:25:20 +00:00
Lovell Fuller
eb30f6ceff Upgrade libvips to v8.4.2
Improved EXIF orientation and GIF alpha channel support
2016-11-02 09:25:20 +00:00
Lovell Fuller
1051fcd278 Release v0.16.2 2016-10-22 18:39:33 +01:00
Lovell Fuller
1a0030e086 Restrict readelf usage to Linux only #602 2016-10-14 16:07:17 +01:00
Lovell Fuller
114ce370ed Provide a default lib location when detecting C++11 ABI
Useful for pkgconfig without -L, e.g. Alpine Linux
See also commit 07d66da
2016-10-13 12:38:53 +01:00
Lovell Fuller
207dcbeaa4 Release v0.16.1 2016-10-13 10:53:38 +01:00
Lovell Fuller
d4a1722863 The long-awaited return of code examples to README 2016-10-12 19:41:49 +01:00
Lovell Fuller
18b9991fe7 Add experimental 'attention' crop strategy 2016-10-12 11:18:58 +01:00
Lovell Fuller
739178dd74 Include '.node' ext for Meteor's require() implementation #537 2016-10-05 10:50:13 +01:00
Taka Kojima
dcd1392a85 Allow platform, arch and arm_version to be overridden (#581)
Aids cross-compilation
2016-10-01 12:54:14 +01:00
Lovell Fuller
07d66da57b Auto-detect C++11 ABI version, remove --sharp-cxx11 flag 2016-09-28 21:40:30 +01:00
Lovell Fuller
28ce33feb3 Fix y-axis calc when overlaying at fixed point #566 2016-09-16 11:20:08 +01:00
Brandon Aaron
86039a3f2b Bumping png16 to 1.6.25 (#570) 2016-09-12 19:43:16 +01:00
Lovell Fuller
af9d09f8ae Ensure conv kernel scale is clamped to min val of 1 #561 2016-09-03 20:06:49 +01:00
Lovell Fuller
7c06a48ec0 Release v0.16.0 2016-08-18 09:00:04 +01:00
Lovell Fuller
7ada9dbd0d Changelog update, fix for small leak introduced in 5c5d74a 2016-08-17 20:56:53 +01:00
Matt Hirsch
5c5d74a903 Add joinChannel and toColourspace/toColorspace operations (#513) 2016-08-17 15:42:05 +01:00
Lovell Fuller
72354d55a8 Doc and changelog updates #519 #540 2016-08-13 17:24:06 +01:00
cmtt
fc2002fbd0 Add alpha channels, if missing, to overlayWith images (#540) 2016-08-13 17:19:15 +01:00
Matt Hirsch
82ec2715f1 Prevent bandbool creating a single channel sRGB image (#519) 2016-08-13 14:55:15 +01:00
Lovell Fuller
ef6e90fb3c Correct dist name logging in packaging test script 2016-08-13 11:43:13 +01:00
Lovell Fuller
475f0bf120 Refactor packaging scripts, add ARMv7/v8 binaries 2016-08-12 13:40:44 +01:00
Lovell Fuller
e68a14c94c Dependency version bumps 2016-08-01 20:23:45 +01:00
Lovell Fuller
da0dc28bc4 Remove unescaped module_root_dir as it can contain spaces 2016-08-01 13:44:46 +01:00
Lovell Fuller
e6bfa52b0b Add raw pixel data support to boolean and withOverlay ops
The previously-scattered image opening logic has been refactored to a
single ImageDescriptor struct/Object available to both JS and C++ code

This removed about 150 LOC but more importantly reduces the complexity
of adding/exposing new operations that require an input image.
2016-07-26 23:07:25 +01:00
Lovell Fuller
36bfbdee0d Add support for using pre-compiled binaries with OSX 2016-07-25 16:32:42 +01:00
Lovell Fuller
7a9a4127a0 Remove deprecated interpolateWith method
Version bump dependencies
2016-07-25 16:11:53 +01:00
Lovell Fuller
4f1472d4ff Upgrade to libvips v8.3.2 2016-07-25 15:30:14 +01:00
Lovell Fuller
032bb7e96b Ensure ICC profiles are removed from PNG output #521 2016-07-21 16:49:27 +01:00
Lovell Fuller
9ddc817a09 Add WebP availability check to test added in a5bd68e 2016-07-21 15:55:34 +01:00
Lovell Fuller
a5bd68ef8c Recalc after WebP shrink-on-load to avoid rounding errors #508 2016-07-21 15:18:14 +01:00
Lovell Fuller
a2ec3642bf Alpine now provides vips in its testing repo
Resize+sharpen+alpha seems to stack-smash, ignore for now
2016-07-20 20:05:43 +01:00
Lovell Fuller
9647fe1b9f Reduce size of pre-built binaries by ~5% 2016-07-20 20:03:41 +01:00
Lovell Fuller
762cda75a9 Update libxml2 dependency CVE-2016-4448 #515
Also updates:
* libpng as previous version is now unavailable (?)
* libjpeg as previous version was pre-release
2016-07-18 12:07:28 +01:00
Matt Hirsch
c39a9b8de9 Prevent boolean errors during extract operation (#509) (#511) 2016-07-16 10:56:15 +01:00
Matt Hirsch
15a577863a Ensure boolean, bandbool, extractChannel ops occur before sRGB conversion (#504) 2016-07-13 19:20:50 +01:00
Lovell Fuller
2d500554c1 Release v0.15.1 2016-07-12 16:06:38 +01:00
Lovell Fuller
c42fb97419 Refactor pipeline to use common 16-bit detection methods 2016-07-11 23:03:45 +01:00
Lovell Fuller
d1d6155fd1 Increase unit test coverage for recently added operations
Switch param validation to use internal functions
2016-07-11 22:23:15 +01:00
Lovell Fuller
ff8c42e894 Changelog/doc/test updates for various new operations
Dependency version bumps
2016-07-11 15:52:30 +01:00
Lovell Fuller
e10aeb29eb Add missing include introduced by fee3d88 2016-07-11 14:05:26 +01:00
Lovell Fuller
fee3d882c7 Prevent GC of Buffer object vector via accumulate/lambda.
Removes need for naming Buffers and separate container struct.
2016-07-11 13:07:32 +01:00
Matt Hirsch
d17e8d3450 Add boolean feature for bitwise image operations (#501) 2016-07-11 09:51:43 +01:00
Lovell Fuller
99f960bf56 Docs: Clarify trimming of existing cache entries #487 2016-07-11 09:42:19 +01:00
Matt Hirsch
83d8847f57 Add extractChannel operation to extract a channel from an image (#497) 2016-07-09 16:48:30 +01:00
Matt Hirsch
f672f86b53 Add ability to read and write native vips .v files (#500) 2016-07-09 16:21:16 +01:00
Kleis Auke Wolthuizen
b69627891d Add trim operation to remove "boring" edges (#491 #492) 2016-07-08 22:19:10 +01:00
Matt Hirsch
673d8278b5 Add a unit test for extract area out of bounds (#498) 2016-07-08 20:52:33 +01:00
Lovell Fuller
8dd554b935 Use "previous" AppVeyor env as temp workaround for nodejs/node-gyp#952 2016-07-08 13:15:24 +01:00
Matt Hirsch
65b7f7d7d5 Add bandbool feature for channel-wise boolean operations (#496) 2016-07-07 21:03:49 +01:00
Matt Hirsch
a982cfdb20 Update docs to better reflect output of RAW data (#499) 2016-07-07 20:50:59 +01:00
Lovell Fuller
7689fbe54d Ensure --sharp-cxx11 flag is passed through #456 #494
node-gyp replaces dashes with underscores
2016-07-06 10:40:53 +01:00
Lovell Fuller
c9d32e22d3 Docs, changelog for top/left overlayWith offset #473 2016-07-05 11:17:41 +01:00
Rahul Nanwani
278273b5c3 Add top/left offset support to overlayWith operation (#473) 2016-07-05 10:12:02 +01:00
Lovell Fuller
a5d85b8a54 Changelog plus tidy of code/docs for convolve operation 2016-07-04 22:13:47 +01:00
Lovell Fuller
4c172d25f6 Allow images with alpha channel to use LAB sharpen #490 2016-07-04 21:33:44 +01:00
Matt Hirsch
b70a7d9a3b Add convolve operation for kernel-based convolution (#479) 2016-07-04 20:48:00 +01:00
Lovell Fuller
ba5a8b44ed Changelog, credit and doc tidy for improved threshold operation 2016-07-04 10:41:13 +01:00
Lovell Fuller
91e1ed1314 Ensure ICC profiles are licenced for distribution #486 2016-07-04 10:13:16 +01:00
Matt Hirsch
85f20c6e1b Add greyscale option to threshold operation (#480) 2016-07-03 19:32:07 +01:00
Lovell Fuller
4b98dbb454 Docs: reduce ambiguity of tile-based ZIP file output #474 2016-06-26 13:58:49 +01:00
Lovell Fuller
c3ad4fbdaa Document new cutout option of overlayWith feature #435 2016-06-26 13:53:20 +01:00
Kleis Auke Wolthuizen
2e9cd83ed2 Add support for clipping/cutting out (#435) (#448)
USAGE: overlayWith('overlayimage.png', { cutout: true } )
2016-06-25 16:48:01 +01:00
Lovell Fuller
f1ead06645 Update test expectations/thresholds previously failing on OS X.
Remove Node v5 from CI builds.
2016-06-14 22:25:27 +01:00
Teoh Han Hui
d486eaad03 Document breaking change in extract API in v0.14.0 (#465)
Deprecated style of calling extract was removed in 2034efc
2016-06-14 10:46:19 +01:00
Lovell Fuller
7d261a147d Ensure scaling factors are calculated independently #452
Fixes bug introduced in v0.15.0 where, if the shrink operation
rounded up along one dimension, it could then also round up the
reduce operation on the same axis, creating a small stretch effect.
2016-06-13 23:03:45 +01:00
Lovell Fuller
61038888c4 Document --sharp-cxx11 install flag #456 2016-06-11 08:28:27 +01:00
Jérémy Lal
39040fb9a0 Allow node-gyp configure --sharp-cxx11=1 (#456)
Can also be set in .npmrc.
Closes: #442
2016-06-08 17:42:46 +01:00
Lovell Fuller
4f3262c328 List licence details for all library dependencies 2016-05-27 23:17:06 +01:00
Lovell Fuller
69126a7c5f Add docs and credits for #439 and #443 2016-05-27 21:33:07 +01:00
lemnisk8
62554b766f Add support for repeated/tiled overlay image (#443)
USAGE: overlayWith('overlayimage.png', { tile: true, gravity: northwest} )
When using the tile option, the gravity option is applied to the extracted part of the tiled overlay image.
2016-05-26 16:42:17 +01:00
frulo
e699e36270 Add alpha channel, if required, before extend operation (#439) 2016-05-26 09:46:14 +01:00
Lovell Fuller
331926dc3c Concat Stream-based input in single operation for ~+3% perf and less GC #429 2016-05-24 21:04:18 +01:00
Lovell Fuller
8a3b660bbc Release v0.15.0 2016-05-21 15:33:56 +01:00
Lovell Fuller
933989c87d Update benchmark results ahead of v0.15.0, ~20% improvement 2016-05-21 10:21:42 +01:00
Lovell Fuller
e3cbcb98c0 Add hints about compiling with _GLIBCXX_USE_CXX11_ABI #432
Increase deprecatedness of preinstall script
Additional valgrind suppressions for libwebp
2016-05-21 09:03:09 +01:00
Lovell Fuller
32a2787254 Thank you to all the new contributors 2016-05-18 20:40:31 +01:00
Lovell Fuller
fccfc27de0 Update ARM packaging to libvips v8.3.1 2016-05-18 19:58:30 +01:00
Lovell Fuller
cdb2894bd9 Use libvips' new lanczos3 kernel as default for image reduce
Deprecate interpolateWith method, now provided as an option
2016-05-18 19:57:22 +01:00
Lovell Fuller
051d022fc2 Upgrade to libvips v8.3.1
Remove packaging tests and therefore support for Centos 6
2016-05-08 22:15:08 +01:00
Lovell Fuller
7388d97502 Allow keyword macros for glib support on MSVC 2016-05-08 13:30:42 +01:00
Lovell Fuller
1bece3a792 Add 2 channel (grey+alpha) GIF test case #375 2016-05-07 20:04:17 +01:00
Lovell Fuller
1de0038516 Upgrade to libvips 8.3.x
Add support for libvips' new native loaders, including GIF and SVG
Pre-built binaries now include giflib and librsvg, exclude *magick
2016-05-07 20:04:17 +01:00
Lovell Fuller
b7a098fb28 Break existing sharpen API to accept sigma and improve precision 2016-05-07 20:04:17 +01:00
Lovell Fuller
ee21d2991c Use shrink-on-load for WebP input 2016-05-07 20:04:17 +01:00
Lovell Fuller
f8eab49962 Add Node v6 to CI builds 2016-05-07 19:50:15 +01:00
Lovell Fuller
c9b3847a69 Docs: basic security considerations for installation #424 2016-05-07 19:48:06 +01:00
Felix Bünemann
dce3840537 Update Lambda instructions for Node.js 4.3 (#419)
Amazon introduced Node.js 4.3 support for Lambda, which is now the
recommended runtime instead of the old Node.js 0.10. This commit revises
the Lambda docs to build Node.js 4.3 compatible binaries using the
latest stable Node.js 4.x packages from Nodesource.
2016-04-27 19:39:30 +01:00
Lovell Fuller
b6030c161b Update expected test fixtures for libvips 8.3 2016-04-23 20:07:55 +01:00
Lovell Fuller
c920180cb3 Remove (un)premultiply ops when not resizing/compositing #413 2016-04-23 19:50:00 +01:00
Lovell Fuller
531a0402f7 Changelog updates ahead of v0.14.1
Note effect of C++11 ABI changes on upgrades
2016-04-16 21:16:37 +01:00
Lovell Fuller
cb10f9a9c8 Support gyp-based (re)build without npm env vars #412 2016-04-16 20:35:28 +01:00
Lovell Fuller
c808139b02 Changelog additions and version bumps ahead of v0.14.1 2016-04-14 21:57:44 +01:00
Lovell Fuller
e0d58266be Allow use of embed with 1 and 2 channel images #411 2016-04-14 21:39:17 +01:00
Felix Bünemann
1b7c5816fc Speed up slow pixel limit tests (#404)
This replaces the single color 20000x14000 PNG with a 20000x14000
Grayscale JPG. On a Broadwell Core i7 @ 3.1 GHz this speeds up the
"Disabling limit works" test from ~6.2s to ~0.15s because it can use
jpeg resize-on-load optimizations.

This should fix occasional timeouts on Travis CI.
2016-04-08 22:21:28 +01:00
Felix Bünemann
b224874332 Add support for writing dz format to zip container (#402)
To enable this you can either use the `.zip` or `.szi` file extensions
or use `.tile({container: 'zip'})` with the `.dzi` extension.
2016-04-08 19:58:13 +01:00
Samy Al Zahrani
ef61da3051 Ensure dimensions of final output image are provided (#399)
Add a failing test for vips::VError exception
* fix buffer size mismatch
* Loosen error message assertion
* Update image
2016-04-08 08:58:51 +01:00
Samy Al Zahrani
f214269aa1 Enable RTTI for clang-based builds
This allows for a more verbose error message on mac os x

```

libc++abi.dylib: terminating with uncaught exception of type vips::VError

```

becomes

```

libc++abi.dylib: terminating with uncaught exception of type vips::VError: VipsImage: memory area too small --- should be 1191960 bytes, you passed 1189440

```
2016-04-06 15:23:17 +01:00
Lovell Fuller
6bc2ea8dc7 No longer publish deprecated preinstall script to npm 2016-04-04 12:49:48 +01:00
Lovell Fuller
71fb839e2b Speed up limitInputPixels test case
Update changelog
2016-04-04 12:48:53 +01:00
kentongray
8c9c070caf Ability to disable limitInputPixels #250
Update docs
Added a giant image for testing
Adding myself to contributors
Added tests to verify giant image can be opened
Extend test-win time limit (because of large images)
2016-04-04 08:35:11 +01:00
Lovell Fuller
b2d7d4c4a9 Release v0.14.0 2016-04-02 13:21:44 +01:00
Lovell Fuller
0ac7fbfc07 Changelog entry for #382 #385 2016-04-02 12:19:58 +01:00
John Tobin
ebfc897bcf Fix for orientation values 1-8 2016-04-02 11:59:26 +01:00
Lovell Fuller
c66495b66c Tighten C++ linting rules
Bump benchmark dependencies
Update leak test suppressions
Update future branch details
2016-03-31 20:30:40 +01:00
Lovell Fuller
24fb0c33c2 Add further test case for #387, which builds on 25b63a2 2016-03-30 19:26:19 +01:00
Lovell Fuller
25b63a2fb4 Ensure ratios are not swapped when rotating 90/270 and ignoring aspect 2016-03-28 22:40:37 +01:00
Lovell Fuller
e576165cf1 Use Travis CI's multi-OS feature 2016-03-25 19:12:25 +00:00
Lovell Fuller
fe2eccef39 Merge branch 'needle' 2016-03-22 09:52:25 +00:00
Lovell Fuller
0e0e746a0d Update preinstall to libvips v8.2.3 for Centos 6 2016-03-22 09:44:08 +00:00
Lovell Fuller
5b4f4b0672 Upgrade to libvips v8.2.3 ahead of sharp v0.14.0 2016-03-22 09:37:52 +00:00
Lovell Fuller
185fcfe635 Improve entropy-based crop docs based on feedback.
Fix includes to keep MSVC compiler happy.
Additional memory leak suppressions for latest V8.
2016-03-05 18:30:38 +00:00
Lovell Fuller
2034efcf55 Add experimental, entropy-based auto-crop
Remove deprecated extract API
2016-03-05 12:29:16 +00:00
Lovell Fuller
38ddb3b866 Add support for Zoomify and Google tile layouts
Breaks existing tile API
2016-03-03 20:39:38 +00:00
Lovell Fuller
f950294f70 Add ability to extend (pad) the edges of an image 2016-03-03 09:18:11 +00:00
Lovell Fuller
86815bc9c4 Emit post-processing 'info' event for Stream-based output 2016-03-01 20:08:05 +00:00
Lovell Fuller
bb37dc1ea6 Expose density metadata; set density of images from vector input 2016-03-01 19:33:54 +00:00
Lovell Fuller
d92ea31858 overlayWith improvements: diff sizes/formats, gravity, buffer input 2016-02-29 15:15:27 +00:00
Lovell Fuller
55f204c6f9 Merge pull request #368 from felixbuenemann/improve-linux-lambda-docs
[ci skip] Improved Linux docs, Lambda instructions
2016-02-28 09:15:02 +00:00
Felix Bünemann
e97909f776 [ci skip] Improved Linux docs, Lambda instructions
* Add a more detailed explanation of how sharp discovers libvips
* Add a section on packaging sharp for running on AWS Lambda
2016-02-27 20:25:32 +01:00
Lovell Fuller
c210ac73cc Release v0.13.1 2016-02-27 16:17:58 +00:00
Lovell Fuller
962c91daf0 OpenSUSE package name for npm has changed 2016-02-25 22:19:08 +00:00
Lovell Fuller
df33c3024a Fix embedding onto transparent backgrounds #366
Fully automate embed tests to prevent regression
2016-02-25 18:36:00 +00:00
Lovell Fuller
62e04f7784 Merge pull request #361 from jardakotesovec/clone-clean-up
Remove left over, non-functional code from clone feature.
2016-02-17 11:38:34 +00:00
Jarda Kotesovec
32fcb771ca clone clean up 2016-02-17 10:25:00 +01:00
Lovell Fuller
a21760b374 Release v0.13.0 2016-02-15 19:12:23 +00:00
Lovell Fuller
cd05c7814a Merge pull request #359 from wjordan/alpine-packaging-test
Use libvips-dev apk for alpine-linux packaging test
2016-02-13 20:37:21 +00:00
Will Jordan
7b12f091e8 use alpine:edge image for packaging test
vips requires main/gettext-0.19.7r1 for aports commit 4ef70b432b05b720f7f144c2060550749d378205 to link correctly.
2016-02-13 13:48:46 -05:00
Will Jordan
e149e60c7a Use libvips-dev apk for alpine-linux packaging test 2016-02-13 16:07:56 +00:00
Lovell Fuller
bdac84059d Update perf results for forthcoming v0.13.0
Install runtime rather than dev pkgs on Alpine Linux
2016-02-12 19:33:21 +00:00
Lovell Fuller
2d05804fc3 Add cache recommendations for use with Alpine/musl #354
Prevent Windows EBUSY errors during tests
2016-02-11 20:33:33 +00:00
Lovell Fuller
2a56de69cc Add Alpine Linux packaging test #354
Requires libvips cache to be disabled for tests
Skip tiff/magick tests when format unavailable
2016-02-11 18:30:50 +00:00
Lovell Fuller
6ca2a4a9cd Ensure sharp.format lists support for raw input #220 2016-02-11 18:12:51 +00:00
Lovell Fuller
a9eb65c462 Most Linux systems no longer require the preinstall script 2016-02-09 20:18:00 +00:00
Lovell Fuller
afb30b3695 Ensure VipsArea is unreferenced after Buffer-based output
Prevents the leak of a ~1KB GMutex per output image
2016-02-09 19:28:17 +00:00
Lovell Fuller
09b019ed13 Expand glibc check to include 'gnu libc' identifier 2016-02-08 20:45:24 +00:00
Lovell Fuller
d46ac3a478 Check for glibc before downloading pre-compiled binaries #354 2016-02-08 20:06:01 +00:00
Lovell Fuller
677b2b9089 Selected output format > unknown file extension #344 2016-02-07 20:13:13 +00:00
Lovell Fuller
5c1067c63f Remove the no-longer-maintained gulp-sharp #353 2016-02-07 15:35:41 +00:00
Lovell Fuller
736c04a7a4 Only set density option when using magick loader
to reduce number of warnings from libvips #352
2016-02-04 19:16:54 +00:00
Lovell Fuller
0e29c55d13 Merge branch 'master' of https://github.com/lovell/sharp 2016-02-04 19:11:51 +00:00
Lovell Fuller
ca49e6079c Increase threshold for gamma=0 test, due to either
the version of libjpeg or a cumulative rounding error.
2016-02-04 19:10:58 +00:00
Lovell Fuller
320a7464c7 Merge pull request #351 from joelmukuthu/master
Fix: default crop gravity to sharp.gravity.center
2016-02-04 10:11:48 +00:00
Joel Mukuthu
da74cd078f Fix: default crop gravity to sharp.gravity.center
Closes https://github.com/lovell/sharp/issues/350
2016-02-04 10:38:58 +01:00
Lovell Fuller
322aa60891 Ensure 16-bit input images can be normalised 2016-02-03 19:33:34 +00:00
Lovell Fuller
e380576da2 Add support for raw, uncompressed pixel Buffer/Stream input 2016-02-03 19:21:37 +00:00
Lovell Fuller
cf7664a854 Improve SVG support by allowing control of density/DPI
Switch pre-built libs from Imagemagick to Graphicsmagick
2016-02-03 17:48:22 +00:00
Lovell Fuller
56508e8d79 Add support for libvips' PPM and FITS loaders #347 2016-02-03 17:48:22 +00:00
Lovell Fuller
2656c69d99 Upgrade to libvips v8.2.2 2016-02-03 17:48:22 +00:00
Lovell Fuller
57c1e3ae26 Slightly simplify marshalling of data from V8 Objects 2016-02-03 17:48:22 +00:00
Lovell Fuller
2675b2265b Ensure 16-bit input images embed onto alpha background
Support gamma correction of images with alpha channel
Favour shrink over affine when reducing by integral factor
2016-02-03 17:48:22 +00:00
Lovell Fuller
41e50770d1 Update benchmark test dependencies 2016-02-03 17:48:22 +00:00
Lovell Fuller
b3d6e94984 Optimisation for integral factors: favour shrink over affine 2016-02-03 17:48:22 +00:00
Lovell Fuller
5c9c17f1f6 Switch from libvips' C to C++ binding
Requires upgrade to libvips 8.2.1
2016-02-03 17:48:22 +00:00
Lovell Fuller
11329d5e09 Expose control of the number of open files in libvips' cache.
Breaks API of existing cache method.
Disable libvips cache for I/O tests.
2016-02-03 17:48:22 +00:00
Lovell Fuller
8843211e12 Upgrade libvips to v8.2.2 2016-01-31 11:54:19 +00:00
Lovell Fuller
20e75dc50b v0.12.2 2016-01-16 11:29:23 +00:00
Lovell Fuller
d2e5441d6e Dependency version bumps 2016-01-14 18:39:29 +00:00
Lovell Fuller
0ffa1e72d0 Attempt to remove temp file after install #331 2016-01-06 16:31:01 +00:00
Lovell Fuller
a0e034a9e9 Add support for pre-compiled libvips on ARM CPUs
Uses a HypriotOS-managed docker container for this
2016-01-06 15:50:36 +00:00
Lovell Fuller
3c7cbf8685 Update libvips to v8.2.0
Plus version bumps of other dependencies
2016-01-02 14:19:46 +00:00
Lovell Fuller
7541dfcab2 Document support for FreeBSD/gmake #326 2016-01-01 16:34:18 +00:00
Lovell Fuller
dc2b79ac9a Use array context for include/library paths in gyp config
Remove -I prefix from include paths
Should allow for compilation on FreeBSD #326
2016-01-01 14:04:52 +00:00
Lovell Fuller
6d62051877 Bump minimum version of libvips to 8.1.1 #324
Debian-based systems must compile from source
2015-12-23 20:54:37 +00:00
Lovell Fuller
61b86744d7 Ensure 16-bit input images work with embed option #325 2015-12-23 20:46:49 +00:00
Lovell Fuller
fd5b4a131f v0.12.1 2015-12-12 10:21:36 +00:00
Lovell Fuller
32c4b9eff1 Allow SIMD vector unit to be toggled on/off #172
Currently defaults to off but future versions may default to on
2015-12-12 09:11:50 +00:00
Lovell Fuller
95cf35efc5 Add changelog for v0.12.1 2015-12-06 20:40:05 +00:00
Lovell Fuller
58e6368525 Ensure embedded ICC profiles output with perceptual intent #321 2015-12-06 20:24:17 +00:00
Lovell Fuller
16e0d54b15 Use the NPM-configured HTTPS proxy, if present 2015-12-03 21:30:47 +00:00
Lovell Fuller
be381e4440 Add release date for v0.12.0 2015-11-23 14:06:49 +00:00
Lovell Fuller
9982182926 Update perf test results ahead of v0.12.0 2015-11-23 13:09:06 +00:00
Lovell Fuller
607d157b76 Benchmark test updates ahead of v0.12.0 2015-11-23 10:53:52 +00:00
Lovell Fuller
e21277ceba Version bump of libpng Windows dependency 2015-11-22 21:11:29 +00:00
Lovell Fuller
8012733a52 Expose libvips+deps versions attribute
Add versions.json for Linux packaging

Bump vips-dev Windows version for latest libpng
2015-11-22 20:58:38 +00:00
Lovell Fuller
01a1377972 Include cmath header for clang #301 2015-11-22 09:39:42 +00:00
Lovell Fuller
37e4b9b5ba Update changelog ahead of v0.12.0
Highlight features in readme+docs

Add link to Docker-based Linux CI build status
2015-11-22 09:17:51 +00:00
Lovell Fuller
8a3098604c Remove experimental code that could prevent anti-alias filter 2015-11-21 23:37:44 +00:00
Lovell Fuller
5febce7a59 Remove executable bit from test/* file permissions 2015-11-21 23:05:48 +00:00
Lovell Fuller
3dbedf1fb6 Match g_malloc/g_free for make benefit glorious nation of Windows
Remove C++ standard lib from Windows packaging
2015-11-21 22:51:32 +00:00
Lovell Fuller
0ae619dfc5 Remove stray win32 library that was causing segfaults
Explicit int cast to prevent 'loss of precision' warnings

Remove unnecessary semver checking from I/O tests
2015-11-21 22:18:39 +00:00
Lovell Fuller
05dd191e17 Ensure 16-bit+alpha input images work with vips_premultiply #301
Improves SVG support as *magick serves these as 16-bit

Add automated tests for SVG and 16-bit+alpha PNG inputs
2015-11-21 20:21:34 +00:00
Lovell Fuller
c9ecc7a517 Document Debian 7 support
Add liborc to fix openSUSE support

Switch recommended *magick to ImageMagick for OS X

Increase test timeouts (for Circle CI)
2015-11-19 22:47:34 +00:00
Lovell Fuller
434a433a09 Make output of packaging tests easier to understand
Slight simplification of Linux packaging script
2015-11-19 21:36:16 +00:00
Lovell Fuller
3de54d897c Merge pull request #309 from papandreou/feature/extractWithOptionsObject
Add an options object to the extract operation, deprecate existing behaviour.
2015-11-18 11:48:11 +00:00
Andreas Lind
530c2a9fcf Stop using the legacy .extract(top,left,width,height) in the documentation. 2015-11-18 12:06:10 +01:00
Andreas Lind
60b8b92630 Add support for .extract({left:...,top:...,width:...,height:...}). 2015-11-18 12:06:10 +01:00
Lovell Fuller
5842da22d8 Merge pull request #306 from dacarley/negate
Add negate operation to invert all pixel values.
2015-11-17 20:45:09 +00:00
Lovell Fuller
9850e3dae0 Merge pull request #303 from dacarley/threshold
Add threshold operation.
Converts to greyscale then splits into black/white based on given value.
2015-11-17 20:34:40 +00:00
David Carley
3af62446fc Implements greyscale thresholding 2015-11-17 12:15:34 -06:00
Lovell Fuller
1f71dade67 Merge pull request #307 from papandreou/wheezy
Linux Dockerfile: Use Debian Wheezy as the base image
2015-11-17 17:29:35 +00:00
Lovell Fuller
8be664b66f Merge pull request #305 from papandreou/fix/imagemagickUrl
Dockerfile: Update ImageMagick tarball url (they took -5 down and up -6)
2015-11-17 17:24:30 +00:00
Andreas Lind
c0be4f1307 Dial back the required libc version to 2.13 2015-11-17 17:37:06 +01:00
Andreas Lind
d9c754f5c1 Linux Dockerfile: Use a Debian Wheezy image instead of Ubuntu Precise. 2015-11-17 17:37:06 +01:00
David Carley
33a175eafb Implements negation. 2015-11-17 10:18:59 -06:00
Andreas Lind
7c990b3ab3 Dockerfile: Update ImageMagick tarball url (they took -5 down and up put -6). 2015-11-17 17:16:19 +01:00
Lovell Fuller
5dfeaa9fd1 Ensure gaussian blur is applied before lbb interpolator #289 2015-11-16 08:26:35 +00:00
Lovell Fuller
84fd1caa46 Switch default interpolator to bicubic #289
Only use gaussian blur for non-linear interpolators

Improves performance of bilinear by ~15%

Add liborc to the packaged build to improve bicubic perf

Add examples of the various interpolation methods

Add bilinear vs bicubic to perf tests
2015-11-15 22:04:31 +00:00
Lovell Fuller
2678d761ba Use FreeCallback to support mixed Windows runtime libs #152 2015-11-14 13:58:05 +00:00
Lovell Fuller
ede2ee9ce3 Use Persistent wrapper to prevent GC of input Buffer #152
Avoids memcpy of input and output Buffer objects

Improves Buffer and Stream performance by ~3%
2015-11-14 11:24:15 +00:00
Lovell Fuller
20f468991f Start to use libvips 8.1.0+ features #152
Use native (un)premultiply

Support normalise on Windows
2015-11-12 22:14:53 +00:00
Lovell Fuller
58d9e0fef7 Pre-extract rotate should not swap width/height #296 2015-11-11 22:34:30 +00:00
Lovell Fuller
d7278f022b Ensure latest npm on openSUSE test 2015-11-11 22:25:17 +00:00
Lovell Fuller
7383596f8c Allow tty-less docker-inside-docker usage 2015-11-11 21:37:04 +00:00
Lovell Fuller
f6831ab46b Increase packaging test logging 2015-11-10 23:30:08 +00:00
Lovell Fuller
7cf0f95ed1 Fix Circle CI config
CI providers should really provide config linters :)
2015-11-10 21:53:26 +00:00
Lovell Fuller
bf6b894480 Improve dependency-less documentation
Start to comment ever-growing GYP config

Add Circle CI config to run packaging tests
2015-11-10 21:49:45 +00:00
Lovell Fuller
ee8fcb6109 Update docs to reflect ease-of-installation 2015-11-10 00:04:06 +00:00
Lovell Fuller
05cec013fe Ensure support for more Linux flavours
Add docker-based packaging tests
2015-11-09 08:37:30 +00:00
Lovell Fuller
f4cbbd7b79 Ensure Windows CI uses x64 2015-11-07 20:22:17 +00:00
Lovell Fuller
2129adfcc3 Initial commit of local libvips binding/packaging
Copy Windows DLLs into release dir as no rpath equivalent
Use local libvips on Windows CI
2015-11-07 19:58:26 +00:00
Lovell Fuller
9f59a2aebf Version bumps and changelog for v0.11.4 2015-11-05 21:36:44 +00:00
Lovell Fuller
26fb75bf3f Merge pull request #291 from brandonaaron/corner-gravity
Add corner gravity support
2015-10-27 21:17:53 +00:00
Brandon Aaron
25e5f27785 add corner gavity support 2015-10-27 15:10:10 -04:00
Lovell Fuller
ef62daccf9 Upgrade CI and preinstall script to libvips 8.1.1 2015-10-16 23:43:55 +01:00
Lovell Fuller
9067c0a000 Merge pull request #288 from brandonaaron/exif_flop_2_and_4
EXIF Orientation tags 2 and 4 were flipping instead of flopping
2015-10-16 21:45:16 +01:00
Brandon Aaron
79470d2e07 EXIF Orientation tags 2 and 4 were flipping instead of flopping 2015-10-16 15:41:40 -04:00
Lovell Fuller
3cefa6f2bf Merge pull request #287 from vlapo/master
Add --runtime_link=static option to GYP binding for use with AWS Lambda
2015-10-14 19:22:09 +01:00
vlapo
75d954a6bc Add --runtime_link=static 2015-10-14 11:29:29 +02:00
Lovell Fuller
1b7e3746cc Merge pull request #286 from rayshan/patch-1
Replace `filename` with `path` to make consistent with Node's `fs` module
2015-10-13 21:03:32 +01:00
Ray Shan
29252d9dbb Clarify fileName argument by changing to path
I noticed we can do something like `.toFile("tmp/temp.jpg")`
2015-10-13 12:21:41 -07:00
Lovell Fuller
23e14861be Update perf test results to include jimp
Remove imagemagick-native until Node v4 support
2015-10-10 18:41:01 +01:00
Lovell Fuller
97960b5f91 Merge branch 'master' of https://github.com/lovell/sharp 2015-10-10 13:44:42 +01:00
Lovell Fuller
18c4ad9adf Version bumps of perf test candidates 2015-10-10 13:44:02 +01:00
Lovell Fuller
b240c53633 Merge pull request #282 from jabbrass/patch-1
Fix typo (docs/api)
2015-10-08 07:27:35 +01:00
J. Andrew Brassington
660f3d58be Fix typo (docs/api)
Line 330: "betweem" => "between"
2015-10-07 19:01:35 -07:00
Lovell Fuller
b6d75cda8e Revert Windows/Appveyor CI to libvips 8.0.2 2015-10-07 21:28:58 +01:00
Lovell Fuller
e07356c11c Update list of preinstall OS support
Upgrade to libvips 8.1.0
2015-10-07 20:49:47 +01:00
Lovell Fuller
82e215a42e Merge pull request #280 from roryrjb/master
(preinstall) add wily to 'supported' distros
2015-10-03 10:20:51 +01:00
Rory Bradford
cc1c36d891 (preinstall) add wily to 'supported' distros 2015-10-03 09:45:46 +01:00
Lovell Fuller
a1a2d7de5c Centos 7 provides LittleCMS via lcms2-devel #278 2015-09-30 17:35:35 +01:00
Lovell Fuller
6dce2deb82 Add jimp to perf tests #275 2015-09-27 09:38:47 +01:00
Lovell Fuller
cdad84edc6 Merge pull request #266 from roryrjb/master
(preinstall) add freya to 'supported' distros
2015-09-11 17:32:03 +01:00
Rory Bradford
de842a67d8 (preinstall) add freya to 'supported' distros 2015-09-11 17:10:25 +01:00
Lovell Fuller
918bbe88c6 Switch Travis to Ubuntu 14.04/GCE
Remove v0.10 and custom msvs flag from Appveyor
2015-09-09 22:18:22 +01:00
Lovell Fuller
7d3891989c Add Node.js v4 to CI builds 2015-09-08 20:50:33 +01:00
Lovell Fuller
168fe7c8d9 v0.11.3 2015-09-08 19:16:07 +01:00
Lovell Fuller
29ab8408fb Version bumps and changelog for v0.11.3 2015-09-08 15:13:28 +01:00
Lovell Fuller
692e2d4df4 Automate expected vs actual for blur/sharpen tests 2015-09-07 14:17:35 +01:00
Lovell Fuller
85d86dbede Merge pull request #263 from chrisriley/nan2-doubles
Convert blur and sharpen parameters to double instead of int.
This was broken during the nan v2 upgrade by commit b7e0a6f.
2015-09-06 19:29:06 +01:00
Chris Riley
ce2d7b8efc Update pipeline.cc
In the upgrade to nan v2 that was part of v0.11.2 the baton values for blurSigma, sharpenFlat, and sharpenJagged were being cast to int32_t causing blur(sigma) and sharpen(radius, flat, jagged) to fail with "parameters out of range". This patch casts these baton values to doubles.
2015-09-06 12:29:07 -04:00
Lovell Fuller
be00d72d82 Upgrade nan to fix clang linking problem #259 2015-08-28 10:48:20 +01:00
Lovell Fuller
5b376364f5 Add test case for require-time libc++ segfault 2015-08-27 23:59:48 +01:00
Lovell Fuller
409d15c624 Support EXIF Orientation removal in libvips v8.1.0
See #189 and jcupitt/libvips@fbe321e
2015-08-24 21:48:38 +01:00
Lovell Fuller
ce22388c3b Add io.js v3 to Appveyor CI test matrix 2015-08-24 19:31:11 +01:00
Lovell Fuller
30143cf509 Version bumps and changelog updates for v0.11.2 2015-08-24 19:03:05 +01:00
Lovell Fuller
78f31d2b0d Auto-exclude benchmark contenders that fail compilation 2015-08-24 18:55:59 +01:00
Lovell Fuller
4e67a5025a Use malloc for Nan::NewBuffer owned data
GC results in free() rather than delete[]

Add plenty of new valgrind suppressions
2015-08-24 16:14:49 +01:00
Lovell Fuller
b7e0a6f277 Upgrade to nan v2 #246
Provides support for io.js v3 and Node v4
2015-08-23 21:36:48 +01:00
Lovell Fuller
045680fba5 Document use of crop gravity as a String 2015-08-19 16:28:28 +01:00
Lovell Fuller
692347cc6b Merge pull request #255 from papandreou/feature/cropString
crop: Permit specifying the gravity as a string
2015-08-19 15:13:29 +01:00
Andreas Lind
faa515d969 crop: Permit specifying the gravity as a string.
Will be looked up in require('sharp').gravity.
2015-08-19 14:49:02 +02:00
Lovell Fuller
c4a278ec9c Update changelog for v0.11.1
Version bumps for benchmark test
2015-08-12 09:49:50 +01:00
Lovell Fuller
658a541f49 Add test case for enlarge+embed combo #243 2015-08-12 09:26:38 +01:00
Lovell Fuller
01435977de Blur and sharpen ops always convolve
Partial revert of 36ac882
2015-08-12 07:25:14 +01:00
Lovell Fuller
36ac8828f2 Gamma correction and premultiply do not mix
Skip premultiply for fast blur/sharpen

Automate gamma correction tests
2015-08-11 21:51:22 +01:00
Lovell Fuller
9c83d98bbb Update Appveyor CI to MSVC 2015 2015-07-31 12:11:18 +01:00
Lovell Fuller
dee9ca3ec2 Merge pull request #244 from TheThing/patch-1
Silence MSVC warning:
"C4530: C++ exception handler used,
but unwind semantics are not enabled."
2015-07-26 15:58:54 +01:00
Jonatan Nilsson
d375327d20 binding.gyp: Fix warnings during compiling
Fixes the following warnings while compiling:

```
D:\Forritun\Microsoft Visual Studio 14.0\VC\include\xlocale(341): warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc (compiling source file ..\src\common.cc) [D:\sharp\build\sharp.vcxproj]
D:\Forritun\Microsoft Visual Studio 14.0\VC\include\xlocale(341): warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc (compiling source file ..\src\operations.cc) [D:\sharp\build\sharp.vcxproj]
...etc...
```

Solution taken from here: https://github.com/TooTallNate/node-gyp/issues/26#issuecomment-7296389
2015-07-25 07:44:06 +00:00
Lovell Fuller
09244192e9 Add permalinks back to mkdocs
Erroneously removed in de333eb
2015-07-16 09:34:42 +01:00
Lovell Fuller
de333eb02d Add PPA details for Ubuntu LTS
Remove Mac OS from preinstall script - please use homebrew
2015-07-16 09:28:54 +01:00
Lovell Fuller
8b50f15a44 Version bumps ahead of v0.11.0 2015-07-15 10:55:06 +01:00
Lovell Fuller
f853fa3e23 Suppress known magick and glib leaks 2015-07-15 10:47:09 +01:00
Lovell Fuller
d26f6b3b89 Big documentation clean-up
Add structure via mkdocs (replaces ever-growing README)

Inline usage examples with the method they demonstrate

Add changelog
2015-07-15 10:17:55 +01:00
Lovell Fuller
022a2b1ade Ensure test coverage of overlayWith error paths 2015-07-15 09:37:25 +01:00
Lovell Fuller
4f1ac5717e Clarify removal of EXIF Orientation tag #189 2015-07-13 22:28:59 +01:00
Lovell Fuller
d303703dc5 Allow override of EXIF Orientation tag #189
Clear Orientation when rotate/flip/flop are used
2015-07-13 20:00:33 +01:00
Lovell Fuller
642e5687b6 Guard against unexpected overlay band format #97 2015-07-11 22:56:18 +01:00
Lovell Fuller
2ec845b083 Create normalize/blur/sharpen operations
Reduces pipeline by ~100 LOC
2015-07-11 21:44:39 +01:00
Lovell Fuller
c40cd1aa50 Switch Appveyor CI to x64 and iojs 2.x
Still install/build for 32-bit node/iojs exe
2015-07-11 19:56:23 +01:00
Lovell Fuller
804162c69a Increase AppVeyor CI timeout 2015-07-11 08:58:15 +01:00
Lovell Fuller
08b2a647d0 Update benchmark results for 0.11.0
Adds CImg-based 'lwip' module

Use AWS EC2 c4 instance type
2015-07-10 23:26:25 +01:00
Lovell Fuller
3a058c0c27 Add 'lwip' module to benchmark tests
Dependencies bump
2015-07-10 22:14:56 +01:00
Lovell Fuller
b8885c1faa Auto-width and height calcs now round instead of floor
I think this will better match people's expectations
2015-07-03 15:21:28 +01:00
Lovell Fuller
321e0f2bfe Add 'icc' raw profile data to metadata #129 2015-06-29 21:27:23 +01:00
Lovell Fuller
cff8b45420 Add OS X build status image
Almost-automated(TM)
2015-06-29 14:24:59 +01:00
Lovell Fuller
6ac47c1ef8 Add raw EXIF data to metadata response
Copy metadata input buffer to match pipeline

Prevents possible metadata segfault under load
2015-06-28 23:35:40 +01:00
Lovell Fuller
86490bedfb Add 'clone' method to snapshot an instance
Cloned instances share a common input
Allows multiple output Streams to use a single input Stream
2015-06-28 14:21:02 +01:00
Lovell Fuller
1091be374e Alpha compositing: support grey+alpha src and non-alpha dst 2015-06-02 14:51:08 +01:00
Lovell Fuller
36be0453dd Refactor internal 'resize' to more apt 'pipeline'
Refactor 'composite' C to C++ 'operations'
2015-06-01 16:33:26 +01:00
Lovell Fuller
e2c53b59ce Tighten constructor and quality param checks #221 2015-06-01 14:48:57 +01:00
Lovell Fuller
f19b6c48ca Skip normalise operation for images with one colour
It didn't play nicely with premultiplication
2015-06-01 14:21:02 +01:00
Lovell Fuller
d2a2654ace Replace use of 'finally' in failing tests 2015-06-01 14:21:02 +01:00
Lovell Fuller
8832ae0bf9 Add private maxColourDistance for functional tests
Switch MSE-based tests to use it

Remove experimental MSE-based compare API
2015-06-01 14:21:02 +01:00
Daniel Gasienica
ef8db1eebf Premultiply alpha channel to avoid dark artifacts during tranformation
Add `Sharp.compare(file1, file2, callback)` function for comparing images
using mean squared error (MSE). This is useful for unit tests.

See:
- https://github.com/jcupitt/libvips/issues/291
- http://entropymine.com/imageworsener/resizealpha/
2015-06-01 14:21:02 +01:00
Lovell Fuller
c792a047b1 Ensure libvips version requirement
Should improve debugging, e.g. #222
2015-06-01 14:21:01 +01:00
Daniel Gasienica
64f7f1d662 Add experimental overlayWith API
Composites an overlay image with alpha channel into the input image (which
must have alpha channel) using ‘over’ alpha compositing blend mode. This API
requires both images to have the same dimensions.

References:
- http://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending
- https://github.com/jcupitt/ruby-vips/issues/28#issuecomment-9014826

See #97.
2015-06-01 14:21:01 +01:00
Lovell Fuller
c886eaa6b0 Version bumps for v0.11.0 WIP 2015-06-01 14:21:01 +01:00
Lovell Fuller
b50fb53f27 Use image fingerprints in functional tests #122 2015-06-01 14:21:01 +01:00
Lovell Fuller
75d72cfded Version bumps ahead of v0.10.1 2015-06-01 09:50:49 +01:00
Lovell Fuller
21b0d8c7f7 Version bumps ahead of v0.10.1
Use SPDX format in licence field
2015-05-31 19:35:24 +01:00
Lovell Fuller
fa8f06f07d Include C standard library for 'atoi' #228
Xcode 6.3 appears to no longer do this
2015-05-31 19:05:18 +01:00
Lovell Fuller
e07a105b7c Test availability of __has_feature macro 2015-05-11 11:54:53 +01:00
Lovell Fuller
4f72dcbf54 Verify platform/compiler compatibility #178 #214 2015-05-11 10:46:47 +01:00
Lovell Fuller
b77877c83d Add Amazon Linux 2015.03
Update to libvips version 8.0.2
2015-05-07 15:50:14 +01:00
Lovell Fuller
8fd3520257 Correct use of Windows CI env variable 2015-05-05 11:15:32 +01:00
Lovell Fuller
f15e64039c Windows CI does not yet have io.js v2 2015-05-05 10:46:23 +01:00
Lovell Fuller
3ffe2ba17f Windows CI matrix and version bumps 2015-05-05 10:15:20 +01:00
Lovell Fuller
33782d3c83 Embed alpha image on non-transparent background #204 2015-04-29 20:14:45 +01:00
Lovell Fuller
783826aa26 Reverse Openslide if/else for Debian 8 #203 2015-04-27 18:44:53 +01:00
Lovell Fuller
c2ef16eac2 Don't publish AppVeyor config to npm 2015-04-27 18:44:11 +01:00
Lovell Fuller
e999fb6e30 Dependency version bumps ahead of v0.10.0 2015-04-23 14:29:14 +01:00
Lovell Fuller
d1fc0591a5 Silence Windows compiler warnings #19 2015-04-21 14:39:37 +01:00
Lovell Fuller
fb1c9cf3d3 Less strict assert for unordered events 2015-04-21 13:57:24 +01:00
Lovell Fuller
21ba1dfc26 Wrap flapping event test in nextTick 2015-04-21 13:22:29 +01:00
Lovell Fuller
dacd62428e Fix Windows CI binding config 2015-04-21 12:37:45 +01:00
Lovell Fuller
1e52c2dbe6 Windows compatibility #19
Hide WebP format and normalise option

Separate test runners for node and iojs
2015-04-21 12:13:19 +01:00
Lovell Fuller
8926ebc56c Add Appveyor config for Windows CI
Silence 'possible loss of data' warning
2015-04-20 19:00:22 +01:00
Lovell Fuller
9da87ce868 Fix typo in conditional introduced in 8ac33aa 2015-04-20 17:50:47 +01:00
Lovell Fuller
46cc45c186 Fail fast for unknown interpolator 2015-04-20 11:22:21 +01:00
Lovell Fuller
54f2243386 Merge pull request #198 from bkw/unknownInterpolator
Runtime guard against unknown interpolator class, avoids segfault.
2015-04-20 10:17:44 +01:00
Bernhard K. Weisshuhn
8ac33aad69 avoid segfault with unknown interpolator 2015-04-20 00:24:03 +02:00
Lovell Fuller
6fc62d39c9 Update thank you list
Add perf test for normalise
2015-04-19 21:09:19 +01:00
Lovell Fuller
a0655806de No need to remove dzi file extension
libvips handles this - ensures filenames containing . work
2015-04-19 21:08:15 +01:00
Lovell Fuller
3614d14f83 A few small fixes to the test scripts 2015-04-19 16:15:40 +01:00
Lovell Fuller
f6fd45cc90 Expose libjpeg extension param features
Trellis quantisation, overshoot deringing and scan optimisation
2015-04-19 16:15:40 +01:00
Lovell Fuller
be39297f3b Merge pull request #194 from bkw/normalize
Add normalize() to use full luminance range.
2015-04-19 16:05:20 +01:00
Bernhard K. Weisshuhn
dce36e0074 Add normalize() for simple histogram stretching
Available as normalize() or normalise().
Normalization takes place in LAB place and thus should not change any
colors.

Existing alpha channels are preserved untouched by normalization.
2015-04-18 12:55:04 +02:00
Lovell Fuller
ba034a8164 Add docs for new ignoreAspectRatio option 2015-04-16 18:28:30 +01:00
Lovell Fuller
3dfc7bea3a Merge pull request #192 from skedastik/judgement
Add support for ignoreAspectRatio option when resizing
2015-04-16 15:53:43 +01:00
Alaric Holloway
f72435c750 Support resize without preserving aspect ratio #118 2015-04-16 06:50:47 -07:00
Lovell Fuller
3810f642d3 Add small cache before convolution for seq access 2015-04-14 21:31:20 +01:00
Lovell Fuller
ae968142ee Soften limitInputPixels upper limit #146
Default limit of 14-bit dimensions remains
2015-04-12 14:23:36 +01:00
Lovell Fuller
ccb7887cb9 Use libjpeg-dev metapackage for Debian variants #190 2015-04-09 11:56:36 +01:00
Lovell Fuller
f1ad1216ca Add support for Windows #19
Requires VIPS_HOME environment variable
2015-04-05 22:42:14 +01:00
Lovell Fuller
ce6813329b Improve code portability ahead of Windows support 2015-04-05 21:57:53 +01:00
Lovell Fuller
7ad7193b1e Add test for progressive JPEG output 2015-03-30 11:36:14 +01:00
Lovell Fuller
bd96a49de6 Add usage example of Stream error handling #182 2015-03-24 10:35:05 +00:00
Lovell Fuller
81c710eaa3 Add EventEmitter for queue length changes
Remove unnecessary params from Error handler
2015-03-20 15:44:18 +00:00
Lovell Fuller
711f0fefb6 Disable unused static library and introspection components 2015-03-20 14:57:13 +00:00
Lovell Fuller
33ca86e4f2 Add example of Deep Zoom output
Clean up preinstall and prereqs docs
2015-03-12 17:33:06 +00:00
Lovell Fuller
9b5229f2dd Support old and new Magick loader class names
See jcupitt/libvips@99b4bcb
2015-03-12 17:12:06 +00:00
Lovell Fuller
5781a23a4d Combine new tile* API methods
Use v7.40.0+ libvips loader methods

Separate Openslide as input vs Deep Zoom as output

Split tile-based tests into new file

Added assertions for generated tile size
2015-03-12 15:39:27 +00:00
Victor Mateevitsi
2d1e6f2644 Added Deep Zoom support.
Added OpenSuse 13.1 and 13.2 support in preinstall.sh script.
Added OpenSlide support in preinstall script.
Added unit tests for Deep Zoom and OpenSlide.
2015-03-10 14:00:27 +00:00
Lovell Fuller
5240eeb518 Merge pull request #166 from mcuelenaere/no-custom-image-header-checking
Let libvips check whether we received a valid image or not
2015-03-01 15:41:37 +00:00
Maurus Cuelenaere
125ee836fe Let libvips check whether we received a valid image or not
This removes the custom image fingerprinting code and uses the libvips
is_a_buffer() infrastructure instead.
2015-03-01 11:53:17 +01:00
Lovell Fuller
3ca2f009f4 Remove confusing CSS equivs introduced in 77bbbb9 2015-02-27 15:04:11 +00:00
Lovell Fuller
a900c28f7c Version bumps 2015-02-27 14:46:03 +00:00
Lovell Fuller
77bbbb9715 Improve min/max docs, thanks @LinusU
Add requirement for C++11 compiler

Init scaling factor to silence compiler warning
2015-02-27 13:49:16 +00:00
Lovell Fuller
88753a6333 Merge pull request #175 from LinusU/feature-min
feature: min
2015-02-27 13:25:13 +00:00
Linus Unnebäck
bcd82f4893 feature: min 2015-02-27 13:50:52 +01:00
Lovell Fuller
749dc61f85 JSON and the agro-noughts 2015-02-26 19:49:54 +00:00
Lovell Fuller
c7ccf6801d Expose runtime format availability
Aids addition of new format/method combos

Dogfood this in the test code
2015-02-26 19:41:33 +00:00
Lovell Fuller
1565522ecc Add libgsf dependency ahead of Deep Zoom support 2015-02-26 19:36:42 +00:00
Lovell Fuller
a44df2f533 Merge pull request #173 from LinusU/patch-1
Install libgsf-1-dev on Debian 8
2015-02-26 14:00:51 +00:00
Linus Unnebäck
317510746f Install libgsf-1-dev on Debian 8
This was needed on my docker container running Debian Jessie. This is the error without it:

```text
Package libgsf-1 was not found in the pkg-config search path.
Perhaps you should add the directory containing `libgsf-1.pc'
to the PKG_CONFIG_PATH environment variable
Package 'libgsf-1', required by 'vips', not found
gyp: Call to 'PKG_CONFIG_PATH=":$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig:/usr/lib/pkgconfig" pkg-config --libs vips' returned exit status 1. while trying to load binding.gyp
```
2015-02-26 13:44:00 +01:00
Lovell Fuller
ef54e327b7 Document GIF input via Buffer and Stream
Ensure @mcuelenaere is credited
2015-02-16 13:51:47 +00:00
Lovell Fuller
d8d0158774 Version bump of libvips to 7.42.3
Rename version vars to major, minor and patch
2015-02-16 13:49:22 +00:00
Lovell Fuller
4d75f27a25 Merge branch 'mcuelenaere-imagemagick-buffer' 2015-02-16 13:27:51 +00:00
Lovell Fuller
f89e9d726d Add support for libvips v8.0.0 2015-02-16 13:27:22 +00:00
Lovell Fuller
5194b37460 Merge branch 'imagemagick-buffer' of https://github.com/mcuelenaere/sharp into mcuelenaere-imagemagick-buffer 2015-02-16 12:02:27 +00:00
Lovell Fuller
55ea432711 Add assumeyes flag for Fedora #167 2015-02-16 11:18:42 +00:00
Maurus Cuelenaere
ab7408c96f Add support for loading images through ImageMagick as a buffer 2015-02-16 10:12:59 +01:00
Lovell Fuller
1f7e80e581 Add chroma subsampling options for JPEG output 2015-02-13 09:41:42 +00:00
Lovell Fuller
0e91ca90d6 Remove lingering NanAdjustExternalMemory
Should have been removed in fe34548b
2015-02-12 12:15:56 +00:00
Lovell Fuller
8f41fed9c2 Add toFormat convenience method #137 2015-02-12 11:37:56 +00:00
Lovell Fuller
96dd40cee1 Add Node.js 0.12 stable to CI build
Replaces 0.11 unstable
2015-02-09 17:09:37 +00:00
Lovell Fuller
62767d072b Version bumps 2015-02-09 09:52:27 +00:00
Lovell Fuller
33880ce19e Merge pull request #161 from ide/nan
Change nan dependency back to ^1.6.2
2015-02-06 21:32:27 +00:00
James Ide
988176846d Change nan dependency back to ^1.6.2
The issue with nan on io.js was fixed in https://github.com/rvagg/nan/pull/273. `npm install` on io.js 1.1.0 works now.
2015-02-06 12:30:15 -08:00
Lovell Fuller
657d436a0f Merge pull request #160 from jo/patch-1
Adjust comment in interpolation example
2015-02-06 14:28:59 +00:00
Johannes Jörg Schmidt
e5549e3063 Adjust comment in interpolation example 2015-02-06 15:17:10 +01:00
Lovell Fuller
0b2fb967b8 Add iojs to CI test matrix
Specific version of nan required
2015-02-06 09:36:45 +00:00
Lovell Fuller
f57478c1aa Update bench to latest imagemagick-native
Use 'Triangle' filter as bilinear equiv.
2015-02-02 16:16:45 +00:00
Lovell Fuller
e5a5e2ca7e Tighten 'extract' parameter validation #158 2015-01-29 22:46:04 +00:00
Lovell Fuller
797d503a99 Merge pull request #156 from jonathanong/patch-1
⬇️ nan@^1.5.1
2015-01-28 22:04:52 +00:00
Jonathan Ong
512a281986 ⬇️ nan@^1.5.1
1.6 breaks iojs. this lowers the minimum nan version so that developers can still do `nan@~1.5.1`.
2015-01-27 15:11:40 -08:00
Lovell Fuller
37c5ca7166 Skip SVG test when format is unavailable
It's possible to compile *magick without SVG support
2015-01-25 11:34:16 +00:00
Lovell Fuller
cda700ef73 Update libmagick references to the C library 2015-01-23 11:00:39 +00:00
Lovell Fuller
d32901da8d Dependency version bumps 2015-01-23 10:50:50 +00:00
Lovell Fuller
83ebe12061 Remove atexit handler as libvips defines this
New grunt-sharp build tool

Version bump for latest libvips
2015-01-22 14:17:20 +00:00
Lovell Fuller
fe34548bad Remove optional AdjustAmountOfExternalAllocatedMemory #151
Isolate not available when deleting the buffer
2015-01-21 20:13:43 +00:00
Lovell Fuller
855945bef2 Delete input buffer on postclose #151
Notify V8 GC of memory (de)allocation
2015-01-21 10:34:03 +00:00
Lovell Fuller
8421e3aa5f Add limitInputPixels option to reject input #115 2015-01-20 14:18:05 +00:00
Lovell Fuller
c93f79daa7 Guard against InitImage failure #150
Protects against truncated image headers
2015-01-20 10:38:44 +00:00
Lovell Fuller
35c53f78c8 Ensure bench/random test uses int dimensions 2015-01-16 22:31:46 +00:00
Lovell Fuller
c158d51f8b Explicit cast to uint32 required for nan 1.5.x
See rvagg/nan#229
2015-01-16 22:31:46 +00:00
Lovell Fuller
8e9a8dfede Remove cpplint namespace-related warnings 2015-01-16 22:31:46 +00:00
Lovell Fuller
67dc694cfb Link to new contributor guide
Remove now-duplicate content
2015-01-16 22:31:46 +00:00
Lovell Fuller
74704a132c Add a contribution guide to help those who help 2015-01-16 22:31:46 +00:00
Lovell Fuller
b86674f91f Add cpplint to test suite 2015-01-16 22:31:46 +00:00
Lovell Fuller
5dab3c8482 Allow rotate before pre-resize extraction #145 2015-01-16 22:30:57 +00:00
Lovell Fuller
a190ae6b08 Add raw, uncompressed image data output #136 2015-01-16 22:28:24 +00:00
Lovell Fuller
464fb1726d Keep output dimensions within WebP 14-bit range 2015-01-16 22:28:24 +00:00
Lovell Fuller
065ce6454b Explicit cast of size_t to 32 bit integer
Ensures compilation with nan 1.5.0+
2015-01-15 15:16:01 +00:00
Lovell Fuller
850c2ecdd6 Version bumps 2014-12-15 14:02:30 +00:00
Lovell Fuller
926c5603aa Improve documentation on concurrency/parallelism 2014-12-15 14:00:23 +00:00
Lovell Fuller
d3225fa193 Add 'size' attribute to callback's info Object #138 2014-12-15 13:54:19 +00:00
Lovell Fuller
f026a835fd Move unref of input Buffer to C++ #138 2014-12-14 10:31:25 +00:00
Lovell Fuller
47241db789 Let V8 garbage collect the Buffer earlier #138 2014-12-13 08:48:24 +00:00
Lovell Fuller
34a9970bd9 Remove useless re-definition of image #139 2014-12-12 22:04:55 +00:00
Lovell Fuller
57203f841a Copy input Buffer to avoid V8 heap compaction #138 2014-12-12 22:02:42 +00:00
Lovell Fuller
bd20bd1881 Version bumps 2014-12-11 13:32:52 +00:00
Lovell Fuller
60f1fda7ee Change interpretation to sRGB before transformation #133 2014-12-11 13:32:36 +00:00
Lovell Fuller
ea1013f6ec Add support for latest Amazon Linux 2014-12-08 10:52:59 +00:00
Lovell Fuller
247b607afd Add SVG and PSD fixtures and tests 2014-12-05 21:35:18 +00:00
Lovell Fuller
a56102a209 Ensure ICC transform of withMetadata output #133 2014-12-04 11:28:09 +00:00
Lovell Fuller
940b6f505f Add test for Promise rejection path 2014-12-04 10:48:45 +00:00
Lovell Fuller
e1b5574c4a Handle broken, embedded ICC profile #131 2014-12-03 10:23:35 +00:00
Lovell Fuller
f4cc6a2db4 Correct location of Dockerfile 2014-11-26 10:50:47 +00:00
Lovell Fuller
0acf865654 Faster ICC profile transform via lcms #125 2014-11-25 22:52:24 +00:00
Lovell Fuller
8460e50ee0 Remove spurious keywords 2014-11-25 19:16:01 +00:00
Lovell Fuller
f57a0e3b00 Ensure embedded profile, if any, is always used
Perform sRGB conversion at end of pipe only

withMetadata exports profile, should not convert

Convert one fixture to sRGB to help test

Discovered while investigating #125
2014-11-25 18:54:49 +00:00
Lovell Fuller
02b6016390 Add link to Dockerfile for libvips
Thanks @marcbachmann
2014-11-25 10:33:43 +00:00
Lovell Fuller
4e01d63195 Add hasProfile attribute to metadata response
At the very least will be useful investigating #125
2014-11-24 17:24:29 +00:00
Lovell Fuller
94b47508c0 imagemagick-native now supports async and filter 2014-11-24 15:13:47 +00:00
Lovell Fuller
328cda82c5 Updates for 7.42 stable release of libvips 2014-11-24 12:19:44 +00:00
Lovell Fuller
118b17aa2f Apply less blur before affine reduction #121 2014-11-24 11:52:48 +00:00
Lovell Fuller
b7c7fc22f3 Ensure correct Gaussian blur before affine #121
Use double sigma instead of int radius for blur
2014-11-20 13:59:39 +00:00
Lovell Fuller
177a4f574c Minimum version of libvips now 7.40.0 #74 2014-11-17 12:08:05 +00:00
Lovell Fuller
e22d093002 Ubuntu 14 now compiles 7.40.x from source
as packaged version is the outdated 7.38.x

Added support for Ubuntu 15 and Mint 17.1
2014-11-12 20:30:13 +00:00
Lovell Fuller
e7f6d49bc1 Additional blur radii tests #108 2014-11-12 20:11:28 +00:00
Lovell Fuller
b886db4b0d Add bounds checks on blur/sharpen parameters #108 2014-11-12 20:06:28 +00:00
Lovell Fuller
ee513ac7a7 Less C, more C++ e.g. namespace, enum class
Improve image reference handling
2014-11-11 18:28:23 +00:00
Lovell Fuller
e465306d97 Disable libvips cache for unit tests
Aids memory leak detection
2014-11-11 18:09:48 +00:00
Lovell Fuller
32d9bc204a Add 'fast' blur and Gaussian blur feature #108 2014-11-10 22:38:13 +00:00
Lovell Fuller
df5cf402e3 Ensure leak check tests child processes 2014-11-10 22:35:22 +00:00
Lovell Fuller
86681100b7 Control level of sharpening via radius/flat/jagged #108 2014-11-10 16:20:04 +00:00
Lovell Fuller
47927ef47d Shrink less, affine more, maintain performance #75
Affects interpolators with 4x4+ window size

e.g. Bicubic, LBB, Nohalo

Introduces blur before large affine

to improve large PNG reductions
2014-11-08 12:08:27 +00:00
Lovell Fuller
7537adf399 Add features from libvips 7.40+
Load TIFF from Buffer/Stream

Interlaced PNG output no longer needs tilecache

Option to disable PNG adaptive row filtering
2014-11-08 12:08:27 +00:00
Lovell Fuller
740838b47c Prevent auto-rotate fail for libmagick formats #117 2014-11-08 12:07:47 +00:00
Lovell Fuller
f7c2a839ad Add support for profile-less CMYK images #99 2014-11-06 11:30:19 +00:00
Lovell Fuller
62fcfb3dba Add link to gulp-responsive module 2014-11-04 11:23:40 +00:00
Lovell Fuller
333e8789f4 Include cmath, erroneously removed in 3a9a137f 2014-10-29 13:32:19 +00:00
Lovell Fuller
3a9a137f40 Modify C++ 11 to be MS-friendly #19 2014-10-29 13:16:16 +00:00
Lovell Fuller
5c51612982 Version bumps ahead of v0.7.1 2014-10-28 11:12:40 +00:00
Lovell Fuller
a472adeb74 Fail fast for Buffer with unsupported format #105 2014-10-28 10:53:11 +00:00
Lovell Fuller
2e61839387 Prepare preinstall.sh for inclusion in master 2014-10-28 09:59:28 +00:00
Lovell Fuller
51805ef657 Add root check and support for Debian 7, Mint 13 2014-10-27 22:32:39 +00:00
Lovell Fuller
5856e41a62 Merge pull request #111 from papandreou/preinstallOnDebianWheezy
Build from source on Debian Wheezy
2014-10-27 15:47:29 +00:00
Andreas Lind
ffbe6b7d76 Build from source on Debian Wheezy. 2014-10-27 15:23:40 +01:00
Lovell Fuller
ed6a966534 Add shell script to install libvips 2014-10-24 10:57:45 +01:00
Lovell Fuller
97fc2a2a3a Ensure resize error from C++ is wrapped
Thanks to @papandreou
2014-10-23 09:39:37 +01:00
Lovell Fuller
3e1be7a33a Merge pull request #107 from papandreou/doNotUnrefUnparsableImages
Do not call g_object_unref when imageType comes out as UNKNOWN.
2014-10-23 09:23:37 +01:00
Lovell Fuller
4a4dd7f987 Merge pull request #106 from papandreou/errorInstances
Pass errors as Error instances rather than strings.
2014-10-23 09:22:15 +01:00
Andreas Lind
005c628352 Do not call g_object_unref when imageType comes out as UNKNOWN.
Avoids "(sharp:23220): GLib-GObject-CRITICAL **: g_object_unref: assertion 'G_IS_OBJECT (object)' failed" dumped to the console when an unsupported or invalid image is loaded.
2014-10-23 08:32:23 +02:00
Andreas Lind
1bd316de80 Pass errors as Error instances rather than strings. 2014-10-23 08:27:10 +02:00
Lovell Fuller
49b44d8238 Ensure compilation on RHEL/Centos 6 gcc 2014-10-21 22:01:43 +01:00
Lovell Fuller
8bc1981891 Refactor C++ code
Split features into their own file

Style is becoming less C, more C++
2014-10-21 21:38:19 +01:00
Lovell Fuller
db6dc6431b Add support for mirroring #62 2014-10-21 14:47:08 +01:00
Lovell Fuller
f214673c3c Add Coveralls badge 2014-10-21 12:57:24 +01:00
Lovell Fuller
ffe00ee398 Travis CI + Coveralls integration 2014-10-21 12:40:11 +01:00
Lovell Fuller
6cade5bd7f Increase unit test coverage to ~95% 2014-10-21 12:22:23 +01:00
Lovell Fuller
a531b5917e Add details about running leak and bench tests 2014-10-20 15:54:44 +01:00
Lovell Fuller
ca561daedf Test code refactor #63
Use mocha for feature-specific unit tests

Add test coverage report via istanbul
2014-10-20 15:32:56 +01:00
Lovell Fuller
f4cb577cb4 Code lint of new features 2014-10-17 12:26:53 +01:00
Lovell Fuller
91be57cbce Code lint of secondary tests 2014-10-17 12:26:38 +01:00
Lovell Fuller
78596545b0 Dependency version bumps ahead of 0.7.0 2014-10-17 12:15:31 +01:00
Lovell Fuller
9f6cc33858 Memory leak mop-up of new feature spillage 2014-10-13 22:53:43 +01:00
Lovell Fuller
d82de45b7e Thank you Brandon 2014-10-13 17:51:48 +01:00
Lovell Fuller
b7bbf58624 Document new extract method 2014-10-13 15:41:10 +01:00
Lovell Fuller
945d941c7b Convert image to sRGB sooner for embed 2014-10-13 15:39:52 +01:00
Lovell Fuller
2605bf966f Merge pull request #102 from brandonaaron/extract
Add support for stand-alone, pre-resize, and post-resize extraction
2014-10-07 15:19:41 +01:00
Brandon Aaron
83b72a1ede Add support for stand-alone, pre-resize, and post-resize extraction with a topOffset, leftOffset, width, and height. 2014-10-07 09:56:55 -04:00
Lovell Fuller
6190ca4307 Ensure conversion to sRGB occurs before background #99 2014-10-07 10:17:20 +01:00
Lovell Fuller
c2fcf7fc4a Add libvips install info for Debian Jessie #100 2014-10-06 11:27:29 +01:00
Lovell Fuller
37cb4339e2 Import embedded colour profile, if present #99 2014-10-06 10:45:58 +01:00
Lovell Fuller
46f229e308 Use own Angle enum to wrap jcupitt/libvips@154796a 2014-10-06 10:22:45 +01:00
Lovell Fuller
7f8f38f666 PNG compression level range is 0-9 #95 2014-10-03 14:50:15 +01:00
Lovell Fuller
fb0769a327 Improve image reference handling 2014-10-03 11:45:06 +01:00
Lovell Fuller
b84cc3d49e Unit test hardening 2014-10-03 11:42:10 +01:00
Lovell Fuller
0cba506bc4 Allow embed with rgba background #86 #89
Small memory leak mop-up related to #94
2014-10-02 20:02:14 +01:00
Lovell Fuller
5cdfbba55c Merge pull request #94 from gasi/background-flatten
Add `background` and `flatten` APIs
2014-10-01 20:51:52 +01:00
Daniel Gasienica
6145231936 Add background and flatten APIs 2014-09-30 17:58:57 -07:00
Lovell Fuller
513b07ddcf Add hasAlpha attribute to metadata API
Provides internal sharp_image_has_alpha method

Hopefully this helps with #91
2014-09-30 13:35:42 +01:00
Lovell Fuller
150971fa92 Add details of gulp.js plugin 2014-09-30 13:35:10 +01:00
Lovell Fuller
ac85d88c9c Update code style, jshint checks and EOLs 2014-09-19 11:55:52 +01:00
Lovell Fuller
1c79d6fb5d Add support for greyscale conversion #43 2014-09-16 11:22:26 +01:00
Lovell Fuller
d41321254a Update benchmarks using c3.xlarge AWS instance 2014-09-13 20:37:57 +01:00
Lovell Fuller
515b4656e6 Improve Stream error handling #88 2014-09-12 19:30:57 +01:00
Lovell Fuller
34c96ff925 Correct ...magick... test dependencies 2014-09-11 13:45:34 +01:00
Lovell Fuller
b8a04cc4ef Add link to Centos 6.5 CI via snap-ci 2014-09-08 23:58:13 +01:00
Lovell Fuller
ddc3f6e9c6 Add RHEL libvips installation - close #78 2014-09-08 23:53:01 +01:00
Lovell Fuller
3699e61c20 Improve support for extension-less output filenames 2014-09-07 08:59:11 +01:00
Lovell Fuller
2820218609 Add format property to output info
Output format may be derived from input format
2014-09-04 11:38:05 +01:00
Lovell Fuller
eb3e739f7b Expose libvips thread pool size 2014-09-03 19:52:03 +01:00
Lovell Fuller
87f6e83988 Add memory leak check #21
Runs unit tests via valgrind
2014-09-02 13:59:35 +01:00
Lovell Fuller
5728efd32b Add support for gamma correction #43 2014-08-30 14:12:42 +01:00
Lovell Fuller
bac367b005 Notify V8 GC of libvips cache size #21 2014-08-26 23:28:58 +01:00
Lovell Fuller
0d89131f66 Prevent small memory leak with non-empty argv0 #21 2014-08-26 15:25:36 +01:00
Lovell Fuller
8380be4be3 Add nearest neighbour interpolation
Suitable for image enlargement
2014-08-26 09:38:27 +01:00
Lovell Fuller
d0f51363bf Re-order output option methods
Add explicit list of and links to contributors
2014-08-26 09:09:01 +01:00
Lovell Fuller
15160d3b61 Merge pull request #83 from julianojulio/master
Add support for maintaining metadata in output image, thanks @julianojulio #83
2014-08-26 08:31:58 +01:00
Juliano Julio Costa
c5efb77bad New withMetadata([boolean]) to keep metadata in the generated images. 2014-08-25 15:59:21 -04:00
Lovell Fuller
b877751b2d Add support for C++11 on Mac 2014-08-24 21:41:09 +01:00
Lovell Fuller
40db482fd8 Version bumps 2014-08-24 21:40:23 +01:00
Lovell Fuller
98554e919c Small doc improvements ahead of v0.6.0 2014-08-22 16:57:05 +01:00
Lovell Fuller
017bf1e905 Expose libvips interpolators #69 2014-08-22 16:50:24 +01:00
Lovell Fuller
6498fc3a9e Ignore libmagick's inconsistent GIF colour spaces 2014-08-22 14:31:34 +01:00
Lovell Fuller
8ba71c94f4 Add usage example of metadata method 2014-08-22 14:27:46 +01:00
Lovell Fuller
f2f3eb76e1 Add method for fast access to image metadata #32 2014-08-22 14:17:43 +01:00
Lovell Fuller
5fe945fca8 Add gravity support to crop #45 2014-08-21 11:01:25 +01:00
Lovell Fuller
8ef0851a49 Expose libvips' op-cache max items #76 2014-08-19 20:30:21 +01:00
Lovell Fuller
e45956db6c Correct usage examples for new Stream-based API 2014-08-18 19:34:55 +01:00
Lovell Fuller
7cc9f7e2e0 Add Xcode Command Line Tools install info #80 2014-08-18 19:11:53 +01:00
Lovell Fuller
df3903532d Initial Duplex Stream support 2014-08-07 14:00:34 +01:00
Lovell Fuller
46456c9a2a Clear cached warnings after success 2014-08-06 11:34:16 +01:00
Lovell Fuller
e98f2fc013 Small documentation improvement plus version bump 2014-07-20 22:46:26 +01:00
Lovell Fuller
7df7a505ee Merge pull request #68 from chanon/master
Pass additional info (width, height) to output callback
2014-07-20 22:22:34 +01:00
Chanon
d40bdcc6ac Sends width and height as another parameter to the callback. Fixes issue #67 2014-07-20 23:52:28 +07:00
Lovell Fuller
1cce56b024 Use tile cache for interlace output
Doubles performance of Adam7 interlaced PNG output
2014-07-09 23:47:04 +01:00
Lovell Fuller
2126f9afc1 Ensure xcode/clang uses cflags
Silence pedantic warnings triggered by V8 in 0.11
2014-07-09 21:14:40 +01:00
Lovell Fuller
41420eedcf Add details of Heroku buildpack, thanks @alex88 #57 2014-07-06 13:20:41 +01:00
Lovell Fuller
1b6ab19b6d Remove fftw dependency when compiling libvips from src #57 2014-07-03 21:12:18 +01:00
Lovell Fuller
fbe5c18762 Expose depth of task queue 2014-06-25 23:21:39 +01:00
Lovell Fuller
8acb0ed5d0 Enable libvips C++ interpolators in Travis CI 2014-06-18 21:08:09 +01:00
Lovell Fuller
430e04d894 Update (and reduce) dependencies ahead of v0.5.1 2014-06-17 20:24:22 +01:00
Lovell Fuller
012edb4379 Support existing path to pkg-config lib for Heroku #57 2014-06-17 19:55:41 +01:00
Lovell Fuller
11ead360a9 Add Promises benchmark 2014-06-13 19:20:39 +01:00
Lovell Fuller
84a059d7e3 Rotate should throw Error, not String.
Minor JSLint and whitespace fixes.
2014-06-13 18:57:54 +01:00
Lovell Fuller
b1b070ae5c Revert "use native Promise if available"
This reverts commit 261a90c8a2db463c4fa0002b22f2c9ff10c0d8e0.
2014-06-13 18:46:36 +01:00
Lovell Fuller
4eb910fec9 Add support for bicubic and Nohalo interpolation #41 2014-06-08 20:46:03 +01:00
Lovell Fuller
f0a9d82bf7 Always convert to sRGB colourspace to prevent libwebp segfault #58 2014-06-07 22:49:15 +01:00
Lovell Fuller
6d20a1ca81 Simplify gyp to support non-standard brew installs #56 2014-06-05 22:19:02 +01:00
Lovell Fuller
eca2787213 Add @jonathanong to contributors - thank you!
Bump versions
2014-06-05 22:18:47 +01:00
Lovell Fuller
8d146accf3 Correct docs - callback is optional for png 2014-06-05 22:00:39 +01:00
Lovell Fuller
b635d015cd Merge pull request #55 from jonathanong/native-promises
use native Promise if available
2014-06-04 20:48:17 +01:00
Jonathan Ong
261a90c8a2 use native Promise if available 2014-06-04 09:03:37 -07:00
Lovell Fuller
4ae22b3425 Merge pull request #51 from jonathanong/deprecate-write
show deprecation warning for .write()
2014-06-04 10:43:59 +01:00
Lovell Fuller
c9aa9c7723 Merge pull request #49 from jonathanong/strings-are-not-errors
fix error types, support promises on convenience methods
2014-06-04 10:35:06 +01:00
Jonathan Ong
5e0b5969da show deprecation warning for .write() 2014-06-03 20:53:37 -07:00
Jonathan Ong
ae6d5e69b1 fix error types, support promises on convenience methods
closes #48
2014-06-03 20:41:15 -07:00
Lovell Fuller
5ccc2bca97 Warn about liborc 0.4.19 buffer overflows #21 2014-06-02 22:18:00 +01:00
Lovell Fuller
46b701c85c Fail fast when input Buffer is empty #37 2014-06-02 21:11:25 +01:00
Lovell Fuller
7319533969 Add support for Promises/A+ #33 2014-06-01 11:27:30 +01:00
Lovell Fuller
9a05684302 Add withoutEnlargement option #36 2014-05-29 20:01:43 +01:00
Lovell Fuller
906311d403 Replace write() with toFile() to allow streams in the future #30 2014-05-29 19:54:43 +01:00
Lovell Fuller
4de9a2435f Correct typo 2014-05-29 16:05:53 +01:00
Lovell Fuller
a94dd2b354 Add support for image rotation including EXIF auto-orient 2014-05-29 00:48:58 +01:00
Lovell Fuller
bc3311cbad Version bump 2014-05-26 09:23:41 +01:00
Lovell Fuller
7b03eb89d7 Merge pull request #39 from pierreinglebert/update-nan
update to nan 1.1.0
2014-05-26 09:15:35 +01:00
Pierre Inglebert
15a519ebd9 update to nan 1.1.0 2014-05-26 09:51:53 +02:00
Lovell Fuller
3f8e9f6487 Merge pull request #38 from pierreinglebert/fix-max-cropping-29
fix max factor #29
2014-05-24 11:54:59 +01:00
Pierre Inglebert
39688371a8 fix max factor #29 2014-05-24 10:29:33 +02:00
Lovell Fuller
e32faac17a Prevent writing output file over input file - closes #28 2014-05-22 22:27:02 +01:00
Lovell Fuller
6c96bd0d37 Version bumps 2014-05-22 00:18:43 +01:00
Lovell Fuller
6b5f2028b7 Add support for 32 bit Linux #27 2014-05-21 23:46:10 +01:00
Lovell Fuller
276ba5228b Add usage example and further unit test for new max option
Simplify max vs crop logic
2014-05-19 21:52:47 +01:00
Lovell Fuller
ad7735a0a6 Merge pull request #18 from pierreinglebert/master
Add 'max' canvas option to specify the maximum width and/or height.
Approximately equivalent to GraphicsMagick's geometry option.
2014-05-19 21:03:04 +01:00
Pierre Inglebert
88edad3fae add max option #18 2014-05-19 20:18:26 +02:00
Lovell Fuller
308d1971d8 Recalculate residual float value for affine after shrink #26
Switch to static casts for double values

Add unit tests that previously would have failed
2014-05-18 11:39:05 +01:00
Lovell Fuller
6622045172 Merge pull request #25 from pierreinglebert/fix-progressive-typo
Fix progressive typo
2014-05-14 11:17:41 +01:00
Pierre Inglebert
f68ba8ea57 fix progressive typo 2014-05-14 08:56:12 +02:00
Lovell Fuller
2e427bb28a Remove liborc from CI config (to match README) 2014-05-13 16:47:57 +01:00
Lovell Fuller
efc7504961 Merge branch 'pierreinglebert-0.11-wip' 2014-05-13 16:45:32 +01:00
Lovell Fuller
8118613fa0 Merge branch '0.11-wip' of https://github.com/pierreinglebert/sharp into pierreinglebert-0.11-wip
Conflicts:
	package.json
2014-05-13 16:45:12 +01:00
Pierre Inglebert
eb6a221cee use master branch of image-magick-native until the 0.11 compatible is out 2014-05-13 08:03:24 +02:00
Pierre Inglebert
acdfe02502 make travis test on node 0.11 2014-05-12 21:30:44 +02:00
Lovell Fuller
2e106f8e2e Version bumps 2014-05-12 21:15:23 +02:00
Lovell Fuller
10496881f1 Add quality and compressionLevel options for output image. #24 2014-05-12 21:15:23 +02:00
Lovell Fuller
e275f6f5dd Add warning about liborc memory leaks. #21 2014-05-12 21:15:23 +02:00
Lovell Fuller
d635c297a2 Replace use of deprecated libvips conv method.
Ensure unref of mask to fix minor memory leak of ~150 bytes/image.
2014-05-12 21:15:23 +02:00
Pierre Inglebert
817c0a2a5a do not publish tests files 2014-05-12 21:15:23 +02:00
Pierre Inglebert
92fd34c627 remove unnecessary gitignore file 2014-05-12 21:15:23 +02:00
Lovell Fuller
43086cf134 Merge branch 'master' into quality-option 2014-05-11 18:26:16 +01:00
Lovell Fuller
e607bac31c Version bumps 2014-05-10 20:23:08 +01:00
Lovell Fuller
f8338e7c4f Add quality and compressionLevel options for output image. #24 2014-05-10 19:45:12 +01:00
Lovell Fuller
8322b442e0 Add warning about liborc memory leaks. #21 2014-05-10 14:39:34 +01:00
Lovell Fuller
afc51df4d8 Replace use of deprecated libvips conv method.
Ensure unref of mask to fix minor memory leak of ~150 bytes/image.
2014-05-03 22:14:21 +01:00
Lovell Fuller
e3a70c1075 Merge pull request #22 from pierreinglebert/add-npmignore
Add npmignore to minimise published package size
2014-04-24 14:09:42 +01:00
Pierre Inglebert
e3ee2b2976 do not publish tests files 2014-04-24 11:28:02 +02:00
Pierre Inglebert
cb285a6fb3 remove unnecessary gitignore file 2014-04-24 11:27:34 +02:00
Pierre Inglebert
aed3ca63b3 use NanNull, NanNew & NanSymbol for 0.11.11+ compat 2014-04-23 10:03:11 +02:00
Lovell Fuller
cbcf5e0dcc Update instructions for libvips installation on Ubuntu 2014-04-18 13:09:45 +01:00
Lovell Fuller
59f5c2d31b Update async dependency 2014-04-18 09:11:01 +01:00
Lovell Fuller
d1b47ef419 Add details of performance test task - closes #12 2014-04-16 21:55:22 +01:00
Lovell Fuller
0954ca6adf Update performance test results 2014-04-15 22:57:27 +01:00
Lovell Fuller
c9d7f43bd9 Add gm buffer-input perf tests 2014-04-15 22:57:07 +01:00
Lovell Fuller
481741315d Correct README markdown format 2014-04-14 22:09:08 +01:00
Lovell Fuller
cae1dbdb89 Add imagemagick-native comparison to and disable vips caching in perf tests. 2014-04-14 22:03:48 +01:00
Lovell Fuller
200d5a9312 Major version increase ahead of incoming API additions. Add link to Travis CI status. 2014-04-08 23:11:01 +01:00
Lovell Fuller
e9ca25cb45 Correct markdown typo 2014-04-08 22:40:34 +01:00
Lovell Fuller
33f24d41e7 Add Travis CI config
Uses a PPA with back-ported libwebp to work around https://bugs.launchpad.net/ubuntu/+source/libwebp/+bug/1108731
2014-04-08 22:35:42 +01:00
Lovell Fuller
45d5f12a63 Add details of Ubuntu 12.04 oddities. Closes #16. 2014-04-08 22:35:20 +01:00
Lovell Fuller
8785ca4331 Merge pull request #15 from pierreinglebert/feature-movefixtures
Move test fixtures to their own directory.
2014-04-02 22:54:05 +01:00
Pierre Inglebert
1ecdf97bdb Move fixtures to a proper directory
Add test for gif (libmagick)
2014-04-02 23:42:05 +02:00
Lovell Fuller
3703ee41aa Merge pull request #14 from pierreinglebert/feature-magickloader
Add support for many other input files via the *magick libraries
2014-04-02 22:26:38 +01:00
Lovell Fuller
c8f023d8ba Support Node.js v0.10+ only. Add @pierreinglebert credit. 2014-04-02 22:19:53 +01:00
Lovell Fuller
fe773733cd Merge pull request #11 from pierreinglebert/master
Add support for Node.js v0.11+ via nan. Remove epeg test dependency as it fails to compile on v0.11+.
2014-04-02 22:08:21 +01:00
Pierre Inglebert
19bec9346e add libmagick load support 2014-04-02 22:17:41 +02:00
Pierre Inglebert
9bd335079f check input files with vips foreign lib 2014-04-02 21:04:01 +02:00
Pierre Inglebert
b6dc179551 remove all references to epeg 2014-04-02 18:51:19 +02:00
Pierre Inglebert
e96fd8b9de 0.11 compat using nan 2014-04-02 00:10:42 +02:00
Lovell Fuller
6a2816e917 Add help for compiling against the gettext dependency of libvips on Mac OS #9 2014-03-13 22:16:47 +00:00
Lovell Fuller
06d88de5a2 Version bump 2014-03-12 21:11:25 +00:00
Lovell Fuller
a292e1fe8e Add path to homebrew-installed pkgconfig for Mac OS 10.8 (10.9 is symlinked to 10.8) #9 2014-03-12 20:45:35 +00:00
Lovell Fuller
08bb35e7af Add test dependency installation details 2014-03-11 22:44:05 +00:00
Lovell Fuller
0e89a5bbf2 Add summary of JPEG and PNG optimisation features 2014-03-10 22:32:14 +00:00
Lovell Fuller
2a0d79a78b Minor markdown layout fix 2014-03-09 21:54:31 +00:00
Lovell Fuller
764b57022b Minor markdown layout fix 2014-03-09 21:53:09 +00:00
Lovell Fuller
5f61331d1a Breaking change to API to become more expressive (see #8). Add support for upscaling. 2014-03-09 21:44:03 +00:00
Lovell Fuller
d0e6a4c0f3 Support identity transform when both width and height are not specified 2014-03-04 22:44:53 +00:00
Lovell Fuller
f99e42d447 Add support for auto-scaling of width and height 2014-03-03 23:24:09 +00:00
Lovell Fuller
9b4387be97 Improve installation instructions for libvips 2014-02-28 23:11:05 +00:00
Lovell Fuller
9c3631ecb7 Add comparative performance tests using random dimensions 2014-02-28 22:39:02 +00:00
Lovell Fuller
31ca68fb14 Improve documentation of cache method 2014-02-28 22:37:59 +00:00
Lovell Fuller
d5d85a8697 Expose vips internal cache settings and status 2014-02-25 23:31:33 +00:00
Lovell Fuller
ae9a8b0f57 Remove unnecessary temporary copy of input buffer. 2014-02-23 10:52:40 +00:00
Lovell Fuller
0899252a72 Add support for WebP and TIFF image formats. Closes #7. 2014-02-22 21:48:00 +00:00
Lovell Fuller
16551bc058 Take a temporary copy of buffers provided as input. Soak testing suggests this prevents the problems seen in #6. 2014-02-12 22:36:13 +00:00
Lovell Fuller
e9d196f696 Fix (unrelated) memory leak discovered whilst investigating #6 2014-02-06 22:20:48 +00:00
Lovell Fuller
2f97d04dfa Keep shrink-on-load logic DRY. Ensure canvas option (crop vs embed) is always as requested. 2014-02-03 23:20:38 +00:00
Lovell Fuller
e4ca8f44ec Version bump 2014-02-01 23:00:37 +00:00
Lovell Fuller
6b3dc1e350 Ensure crop occurs on y-axis 2014-02-01 22:58:30 +00:00
Lovell Fuller
7ffcdb79e0 Add glib-2.0 path for Mac OS X 2014-01-30 18:28:24 +00:00
Lovell Fuller
10ce7c6693 Add parallel performance test to demonstrate effect of waiting for a worker thread 2014-01-26 20:16:42 +00:00
Lovell Fuller
ccd6012152 Version bump 2014-01-21 22:49:40 +00:00
Lovell Fuller
377662fffc Ensure gm perf tests actually resize. Prevent coredump when embeding pre-shrunk image within same dimensions. 2014-01-21 22:48:33 +00:00
Lovell Fuller
d509458ba1 Major rewrite and therefore API change. Despite the name, image sharpening is now optional, plus there are other new options. Can now handle buffers in and out. Doubled performance in certain cases. Closes #3. Closes #4. 2014-01-19 21:38:37 +00:00
Lovell Fuller
be8f35d830 Use shrink-on-load for JPEG images, partially implementing #4. Switch to new vip_ methods from legacy im_ methods. Large performance gains all round. 2014-01-16 22:51:44 +00:00
Lovell Fuller
7e8af63129 Improve thread/buffer shutdown using new vips_thread_shutdown method - closes #5 2014-01-15 21:38:23 +00:00
Lovell Fuller
f7b8ce1287 Add support for writing image data output to a buffer, boosting ops/sec by ~7%. Partially implements #3. 2014-01-11 21:50:17 +00:00
Lovell Fuller
dde9e94850 From here on in, this module will be using the bleeding edge version of libvips. Why? It just keeps getting faster. 2013-11-23 22:08:51 +00:00
Lovell Fuller
21f12e74ba Add support for PNG format. Close #2. 2013-10-26 16:32:18 +01:00
Lovell Fuller
daeebcc7dc Add epeg module to the perf tests 2013-10-19 13:39:57 +01:00
Lovell Fuller
5546a4f881 Added GraphicsMagick perf stats 2013-10-04 22:01:16 +01:00
Lovell Fuller
4aee725530 README layout clean-up 2013-10-02 23:40:32 +01:00
Lovell Fuller
f3da2284b1 Now requires livbips 7.28 or later 2013-10-02 23:37:29 +01:00
Lovell Fuller
f3cd263cb7 Replaced use of deprecated libvips im_* methods with new, shiny non-deprecated vips_* versions 2013-10-02 21:50:03 +01:00
Lovell Fuller
8443dd5122 Version bump 2013-10-02 19:35:49 +01:00
Lovell Fuller
0b7c8661fb The pkgconfig data file ends up in /usr/local when compiling libvips from source 2013-09-23 21:40:01 +01:00
Lovell Fuller
30f75bcc56 Additional performance test stats 2013-08-29 22:55:42 +01:00
Lovell Fuller
6f5125e889 Corrected order of width and height in usage docs 2013-08-26 16:21:38 +01:00
Lovell Fuller
6e3f9b04de Corrected order of width and height in usage docs 2013-08-26 16:20:43 +01:00
Lovell Fuller
b836704451 Improved performance benchmarks and usage docs 2013-08-26 16:10:48 +01:00
664 changed files with 40641 additions and 325 deletions

17
.cirrus.yml Normal file
View File

@ -0,0 +1,17 @@
freebsd_instance:
image_family: freebsd-15-0-snap
task:
name: FreeBSD
env:
IGNORE_OSVERSION: yes
skip_notifications: true
prerequisites_script:
- pkg update -f
- pkg upgrade -y
- pkg install -y devel/git devel/pkgconf graphics/vips www/node20 www/npm
- pkg-config --modversion vips-cpp
install_script:
- npm install --build-from-source
test_script:
- npx mocha --no-config --spec=test/unit/io.js --timeout=30000

12
.editorconfig Normal file
View File

@ -0,0 +1,12 @@
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false

98
.github/CONTRIBUTING.md vendored Normal file
View File

@ -0,0 +1,98 @@
# Contributing to sharp
Hello, thank you for your interest in helping!
## Submit a new bug report
Please create a [new issue](https://github.com/lovell/sharp/issues/new) containing the steps to reproduce the problem.
If you're having installation problems, please include the output of running `npm install --verbose sharp`.
New bugs are assigned a `triage` label whilst under investigation.
## Submit a new feature request
If a [similar request](https://github.com/lovell/sharp/labels/enhancement) exists,
it's probably fastest to add a comment to it about your requirement.
Implementation is usually straightforward if libvips
[already supports](https://www.libvips.org/API/current/func-list.html)
the feature you need.
## Submit a Pull Request to fix a bug
Thank you! To prevent the problem occurring again, please add unit tests that would have failed.
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/main`.
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
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.
Please also update the [TypeScript definitions](https://github.com/lovell/sharp/tree/main/lib/index.d.ts), along with the [type definition tests](https://github.com/lovell/sharp/tree/main/test/types/sharp.test-d.ts).
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)
to compare expected vs actual images.
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.
Please squash your changes into a single commit using a command like `git rebase -i upstream/<wip-branch>`.
### Add a new public method
The API tries to be as fluent as possible.
Image processing concepts follow the naming conventions from libvips and, to a lesser extent, ImageMagick.
Most methods have optional parameters and assume sensible defaults.
Please ensure backwards compatibility where possible.
Feel free to create a [new issue](https://github.com/lovell/sharp/issues/new) to gather feedback on a potential API change.
### Remove an existing public method
A method to be removed should be deprecated in the next major version then removed in the following major version.
By way of example, the `background()` method present in v0.20.0 was deprecated in v0.21.0 and removed in v0.22.0.
## Documentation
The public API is documented with [JSDoc](https://jsdoc.app/) annotated comments.
These can be converted to Markdown by running:
```sh
npm run docs-build
```
Please include documentation updates in any Pull Request that modifies the public API.
## Run the tests
### Functional tests and static code analysis
```sh
npm test
```
### Memory leak tests
Requires [Valgrind](http://valgrind.org/).
```sh
npm run test-leak
```
## Finally
Please feel free to ask any questions via a
[new issue](https://github.com/lovell/sharp/issues/new).
If you're unable to post details publicly, please
[e-mail](https://github.com/lovell/sharp/blob/main/package.json#L5)
for private, paid consulting.

1
.github/FUNDING.yml vendored Normal file
View File

@ -0,0 +1 @@
open_collective: libvips

5
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: Documentation
url: https://sharp.pixelplumbing.com/
about: Installation instructions, complete API documentation with examples, changelog

View File

@ -0,0 +1,28 @@
---
name: Feature request
about: Suggest an idea
labels: enhancement
---
## Feature request
### What are you trying to achieve?
<!-- Please provide context here. -->
### When you searched for similar feature requests, what did you find that might be related?
<!-- 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. -->

69
.github/ISSUE_TEMPLATE/installation.md vendored Normal file
View File

@ -0,0 +1,69 @@
---
name: Installation
about: Something went wrong during either 'npm install sharp' or 'require("sharp")'
labels: installation
---
<!-- Please try to answer as many of these questions as possible. -->
## Possible install-time or require-time problem
<!-- Please place an [x] in the box to confirm. -->
- [ ] I have read and understood all of the [documentation relating to installation](https://sharp.pixelplumbing.com/install).
- [ ] I have searched for known bugs relating to this problem in my choice of package manager.
You must confirm both of these before continuing.
### 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.
### Are you using a supported runtime?
<!-- Please place an [x] in the relevant box to confirm. -->
- [ ] I am using Node.js with a version that satisfies `^18.17.0 || ^20.3.0 || >=21.0.0`
- [ ] I am using Deno
- [ ] I am using Bun
If you cannot confirm any of these,
please upgrade to the latest version
and try again before opening an issue.
### Are you using a supported package manager and installing optional dependencies?
<!-- Please place an [x] in the relevant box to confirm. -->
- [ ] I am using npm >= 10.1.0 with `--include=optional`
- [ ] I am using yarn >= 3.2.0
- [ ] I am using pnpm >= 7.1.0 with `--no-optional=false`
- [ ] I am using Deno
- [ ] I am using Bun
If you cannot confirm any of these, please upgrade to the latest version of your chosen package manager
and ensure you are allowing the installation of optional or multi-platform dependencies before opening an issue.
### What is the complete error message, including the full stack trace?
<!-- Please provide the error message and stack trace here. -->
### What is the complete output of running `npm install --verbose --foreground-scripts sharp` in an empty directory?
<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. -->

65
.github/ISSUE_TEMPLATE/possible-bug.md vendored Normal file
View File

@ -0,0 +1,65 @@
---
name: Possible bug
about: Installation of sharp was successful but then something unexpected occurred using one of its features
labels: triage
---
<!-- If this issue relates to installation, please use https://github.com/lovell/sharp/issues/new?labels=installation&template=installation.md instead. -->
## Possible bug
### Is this a possible bug in a feature of sharp, unrelated to installation?
<!-- Please place an [x] in the box to confirm. -->
- [ ] Running `npm install sharp` completes without error.
- [ ] Running `node -e "require('sharp')"` completes without error.
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.
### 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. -->
### Does this problem relate to file caching?
The default behaviour of libvips is to cache input files, which can lead to `EBUSY` or `EPERM` errors on Windows.
Use [`sharp.cache(false)`](https://sharp.pixelplumbing.com/api-utility#cache) to switch this feature off.
- [ ] Adding `sharp.cache(false)` does not fix this problem.
### Does this problem relate to images appearing to have been rotated by 90 degrees?
Images that contain EXIF Orientation metadata are not auto-oriented. By default, EXIF metadata is removed.
- To auto-orient pixel values use the parameter-less [`rotate()`](https://sharp.pixelplumbing.com/api-operation#rotate) operation.
- To retain EXIF Orientation use [`keepExif()`](https://sharp.pixelplumbing.com/api-output#keepexif).
- [ ] Using `rotate()` or `keepExif()` does not fix this problem.
### 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. -->

26
.github/ISSUE_TEMPLATE/question.md vendored Normal file
View File

@ -0,0 +1,26 @@
---
name: Question
about: For help understanding an existing feature
labels: question
---
<!-- If this issue relates to installation, please use https://github.com/lovell/sharp/issues/new?labels=installation&template=installation.md instead. -->
## Question about an existing feature
### What are you trying to achieve?
<!-- Please provide context here. -->
### 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. -->

18
.github/SECURITY.md vendored Normal file
View File

@ -0,0 +1,18 @@
# Security Policy
## Supported Versions
The latest version of `sharp` as published to npm
and reported by `npm view sharp dist-tags.latest`
is supported with security updates.
## Reporting a Vulnerability
Please use
[e-mail](https://github.com/lovell/sharp/blob/main/package.json#L5)
to report a vulnerability.
You can expect a response within 48 hours
if you are a human reporting a genuine issue.
Thank you in advance.

324
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,324 @@
name: CI
on:
- push
- pull_request
permissions: {}
jobs:
build-native:
permissions:
contents: read
name: "build-${{ matrix.platform }} [Node.js ${{ matrix.nodejs_version_major }}] ${{ matrix.package && '[package]' }}"
runs-on: ${{ matrix.os }}
container: ${{ matrix.container }}
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-24.04
container: rockylinux:8
nodejs_arch: x64
nodejs_version: "^18.17.0"
nodejs_version_major: 18
platform: linux-x64
package: true
- os: ubuntu-24.04
container: rockylinux:8
nodejs_arch: x64
nodejs_version: "^20.3.0"
nodejs_version_major: 20
platform: linux-x64
- os: ubuntu-24.04
container: rockylinux:8
nodejs_arch: x64
nodejs_version: "^22.9.0"
nodejs_version_major: 22
platform: linux-x64
- os: ubuntu-24.04
container: node:18-alpine3.17
nodejs_version_major: 18
platform: linuxmusl-x64
package: true
- os: ubuntu-24.04
container: node:20-alpine3.18
nodejs_version_major: 20
platform: linuxmusl-x64
- os: ubuntu-24.04
container: node:22-alpine3.20
nodejs_version_major: 22
platform: linuxmusl-x64
- os: ubuntu-24.04-arm
container: arm64v8/rockylinux:8
nodejs_arch: arm64
nodejs_version: "^18.17.0"
nodejs_version_major: 18
platform: linux-arm64
package: true
- os: ubuntu-24.04-arm
container: arm64v8/rockylinux:8
nodejs_arch: arm64
nodejs_version: "^20.3.0"
nodejs_version_major: 20
platform: linux-arm64
- os: macos-13
nodejs_arch: x64
nodejs_version: "^18.17.0"
nodejs_version_major: 18
platform: darwin-x64
package: true
- os: macos-13
nodejs_arch: x64
nodejs_version: "^20.3.0"
nodejs_version_major: 20
platform: darwin-x64
- os: macos-13
nodejs_arch: x64
nodejs_version: "^22.9.0"
nodejs_version_major: 22
platform: darwin-x64
- os: macos-14
nodejs_arch: arm64
nodejs_version: "^18.17.0"
nodejs_version_major: 18
platform: darwin-arm64
package: true
- os: macos-14
nodejs_arch: arm64
nodejs_version: "^20.3.0"
nodejs_version_major: 20
platform: darwin-arm64
- os: macos-14
nodejs_arch: arm64
nodejs_version: "^22.9.0"
nodejs_version_major: 22
platform: darwin-arm64
- os: windows-2022
nodejs_arch: x86
nodejs_version: "18.18.2" # pinned to avoid 18.19.0 and npm 10
nodejs_version_major: 18
platform: win32-ia32
package: true
- os: windows-2022
nodejs_arch: x86
nodejs_version: "^20.3.0"
nodejs_version_major: 20
platform: win32-ia32
- os: windows-2022
nodejs_arch: x86
nodejs_version: "^22.9.0"
nodejs_version_major: 22
platform: win32-ia32
- os: windows-2022
nodejs_arch: x64
nodejs_version: "^18.17.0"
nodejs_version_major: 18
platform: win32-x64
package: true
- os: windows-2022
nodejs_arch: x64
nodejs_version: "^20.3.0"
nodejs_version_major: 20
platform: win32-x64
- os: windows-2022
nodejs_arch: x64
nodejs_version: "^22.9.0"
nodejs_version_major: 22
platform: win32-x64
- os: windows-11-arm
nodejs_arch: arm64
nodejs_version: "^20.3.0"
nodejs_version_major: 20
platform: win32-arm64
package: true
- os: windows-11-arm
nodejs_arch: arm64
nodejs_version: "^22.9.0"
nodejs_version_major: 22
platform: win32-arm64
steps:
- name: Dependencies (Rocky Linux glibc)
if: contains(matrix.container, 'rockylinux')
run: |
dnf install -y gcc-toolset-14-gcc-c++ make git python3.12 fontconfig google-noto-sans-fonts
echo "/opt/rh/gcc-toolset-14/root/usr/bin" >> $GITHUB_PATH
- name: Dependencies (Linux musl)
if: contains(matrix.container, 'alpine')
run: apk add build-base git python3 font-noto --update-cache
- name: Dependencies (Python 3.11 - macOS, Windows)
if: contains(matrix.os, 'macos') || contains(matrix.os, 'windows')
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Dependencies (Node.js)
if: "!contains(matrix.platform, 'linuxmusl')"
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.nodejs_version }}
architecture: ${{ matrix.nodejs_arch }}
- uses: actions/checkout@v4
- name: Install
run: npm install --build-from-source
- name: Test
run: npm test
- name: Populate npm package
if: matrix.package
run: npm run package-from-local-build
- uses: actions/upload-artifact@v4
if: matrix.package
with:
name: ${{ matrix.platform }}
path: npm/${{ matrix.platform }}
retention-days: 1
if-no-files-found: error
build-linuxmusl-arm-64:
permissions:
contents: read
name: "build-linuxmusl-arm64 [Node.js ${{ matrix.nodejs_version_major }}] ${{ matrix.package && '[package]' }}"
runs-on: ubuntu-24.04-arm
container:
image: ${{ matrix.container }}
volumes:
- /:/host
strategy:
fail-fast: false
matrix:
include:
- container: node:18-alpine3.17
nodejs_version_major: 18
package: true
- container: node:20-alpine3.18
nodejs_version_major: 20
steps:
- name: Allow Linux musl containers on ARM64 runners # https://github.com/actions/runner/issues/801#issuecomment-2394425757
shell: sh
run: |
apk add nodejs
sed -i "s:ID=alpine:ID=NotpineForGHA:" /etc/os-release
cd /host/home/runner/runners/*/externals/
rm -rf node20/*
mkdir node20/bin
ln -s /usr/bin/node node20/bin/node
- name: Dependencies
run: apk add build-base git python3 font-noto --update-cache
- uses: actions/checkout@v4
- name: Install
run: npm install --build-from-source
- name: Test
run: npm test
- name: Populate npm package
if: matrix.package
run: npm run package-from-local-build
- uses: actions/upload-artifact@v4
if: matrix.package
with:
name: linuxmusl-arm64
path: npm/linuxmusl-arm64
retention-days: 1
if-no-files-found: error
build-qemu:
permissions:
contents: read
name: "build-${{ matrix.platform }} [Node.js ${{ matrix.nodejs_version_major }}] [package]"
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
include:
- platform: linux-arm
distro: bullseye
run_on_arch: armv6
nodejs_arch: armv6l
nodejs_hostname: unofficial-builds.nodejs.org
nodejs_version: "18.17.0"
nodejs_version_major: 18
- platform: linux-s390x
distro: bullseye
run_on_arch: s390x
nodejs_arch: s390x
nodejs_hostname: nodejs.org
nodejs_version: "18.17.0"
nodejs_version_major: 18
- platform: linux-ppc64
distro: bullseye
run_on_arch: ppc64le
nodejs_arch: ppc64le
nodejs_hostname: nodejs.org
nodejs_version: "18.17.0"
nodejs_version_major: 18
steps:
- uses: actions/checkout@v4
- uses: uraimo/run-on-arch-action@v3
with:
arch: ${{ matrix.run_on_arch }}
distro: ${{ matrix.distro }}
run: |
apt-get update
apt-get install -y curl g++ git libatomic1 make python3 xz-utils
mkdir /opt/nodejs
curl --silent https://${{ matrix.nodejs_hostname }}/download/release/v${{ matrix.nodejs_version}}/node-v${{ matrix.nodejs_version}}-linux-${{ matrix.nodejs_arch }}.tar.xz | tar xJC /opt/nodejs --strip-components=1
export PATH=$PATH:/opt/nodejs/bin
npm install --build-from-source
npx mocha --no-config --spec=test/unit/io.js --timeout=30000
npm run package-from-local-build
- uses: actions/upload-artifact@v4
with:
name: ${{ matrix.platform }}
path: npm/${{ matrix.platform }}
retention-days: 1
if-no-files-found: error
build-emscripten:
permissions:
contents: read
name: "build-wasm32 [package]"
runs-on: ubuntu-24.04
container: "emscripten/emsdk:4.0.10"
steps:
- uses: actions/checkout@v4
- name: Dependencies
run: apt-get update && apt-get install -y pkg-config
- name: Dependencies (Node.js)
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install
run: emmake npm install --build-from-source
- name: Verify emscripten versions match
run: |
EMSCRIPTEN_VERSION_LIBVIPS=$(node -p "require('@img/sharp-libvips-dev-wasm32/versions').emscripten")
EMSCRIPTEN_VERSION_SHARP=$(emcc -dumpversion)
echo "libvips built with emscripten $EMSCRIPTEN_VERSION_LIBVIPS"
echo "sharp built with emscripten $EMSCRIPTEN_VERSION_SHARP"
test "$EMSCRIPTEN_VERSION_LIBVIPS" = "$EMSCRIPTEN_VERSION_SHARP"
- name: Test
run: emmake npm test
- name: Populate npm package
run: emmake npm run package-from-local-build
- uses: actions/upload-artifact@v4
with:
name: wasm32
path: npm/wasm32
retention-days: 1
if-no-files-found: error
release:
permissions:
contents: write
runs-on: ubuntu-24.04
needs:
- build-native
- build-linuxmusl-arm-64
- build-qemu
- build-emscripten
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
path: npm
- name: Create npm workspace tarball
run: tar -vcaf npm-workspace.tar.xz --directory npm --exclude=from-local-build.js .
- name: Create GitHub release for tag
if: startsWith(github.ref, 'refs/tags/v')
uses: ncipollo/release-action@v1
with:
artifacts: npm-workspace.tar.xz
artifactContentType: application/x-xz
prerelease: ${{ contains(github.ref, '-rc') }}
makeLatest: ${{ !contains(github.ref, '-rc') }}

194
.github/workflows/npm.yml vendored Normal file
View File

@ -0,0 +1,194 @@
name: "CI: npm smoke test"
on:
push:
tags:
- "v**"
permissions: {}
jobs:
release-smoke-test:
name: "${{ github.ref_name }} ${{ matrix.name }}"
runs-on: ${{ matrix.runs-on }}
strategy:
fail-fast: false
matrix:
include:
- name: linux-x64-node-npm
runs-on: ubuntu-24.04
runtime: node
package-manager: npm
- name: linux-x64-node-pnpm
runs-on: ubuntu-24.04
runtime: node
package-manager: pnpm
- name: linux-x64-node-yarn
runs-on: ubuntu-24.04
runtime: node
package-manager: yarn
- name: linux-x64-node-yarn-pnp
runs-on: ubuntu-24.04
runtime: node
package-manager: yarn-pnp
- name: linux-x64-node-yarn-v1
runs-on: ubuntu-24.04
runtime: node
package-manager: yarn-v1
- name: linux-x64-deno
runs-on: ubuntu-24.04
runtime: deno
- name: linux-x64-bun
runs-on: ubuntu-24.04
runtime: bun
- name: darwin-x64-node-npm
runs-on: macos-13
runtime: node
package-manager: npm
- name: darwin-x64-node-pnpm
runs-on: macos-13
runtime: node
package-manager: pnpm
- name: darwin-x64-node-yarn
runs-on: macos-13
runtime: node
package-manager: yarn
- name: darwin-x64-node-yarn-pnp
runs-on: macos-13
runtime: node
package-manager: yarn-pnp
- name: darwin-x64-node-yarn-v1
runs-on: macos-13
runtime: node
package-manager: yarn-v1
- name: darwin-x64-deno
runs-on: macos-13
runtime: deno
- name: darwin-x64-bun
runs-on: macos-13
runtime: bun
- name: win32-x64-node-npm
runs-on: windows-2022
runtime: node
package-manager: npm
- name: win32-x64-node-pnpm
runs-on: windows-2022
runtime: node
package-manager: pnpm
- name: win32-x64-node-yarn
runs-on: windows-2022
runtime: node
package-manager: yarn
- name: win32-x64-node-yarn-pnp
runs-on: windows-2022
runtime: node
package-manager: yarn-pnp
- name: win32-x64-node-yarn-v1
runs-on: windows-2022
runtime: node
package-manager: yarn-v1
- name: win32-x64-deno
runs-on: windows-2022
runtime: deno
steps:
- name: Install Node.js
if: ${{ matrix.runtime == 'node' }}
uses: actions/setup-node@v4
with:
node-version: 20
- name: Install pnpm
if: ${{ matrix.package-manager == 'pnpm' }}
uses: pnpm/action-setup@v4
with:
version: 8
- name: Install Deno
if: ${{ matrix.runtime == 'deno' }}
uses: denoland/setup-deno@v1
with:
deno-version: v1.x
- name: Install Bun
if: ${{ matrix.runtime == 'bun' }}
uses: oven-sh/setup-bun@v2
with:
bun-version: latest
- name: Version
id: version
uses: actions/github-script@v7
with:
script: |
core.setOutput('semver', context.ref.replace('refs/tags/v',''))
- name: Create package.json
uses: DamianReeves/write-file-action@v1.3
with:
path: package.json
contents: |
{
"dependencies": {
"sharp": "${{ steps.version.outputs.semver }}"
},
"type": "module"
}
- name: Create release.mjs
uses: DamianReeves/write-file-action@v1.3
with:
path: release.mjs
contents: |
import { deepStrictEqual } from 'node:assert';
import sharp from 'sharp';
deepStrictEqual(['.jpg', '.jpeg', '.jpe', '.jfif'], sharp.format.jpeg.input.fileSuffix);
- name: Run with Node.js + npm
if: ${{ matrix.package-manager == 'npm' }}
run: |
npm install --ignore-scripts
node release.mjs
- name: Run with Node.js + pnpm
if: ${{ matrix.package-manager == 'pnpm' }}
run: |
pnpm install --ignore-scripts
node release.mjs
- name: Run with Node.js + yarn
if: ${{ matrix.package-manager == 'yarn' }}
run: |
corepack enable
yarn set version stable
yarn config set enableImmutableInstalls false
yarn config set enableScripts false
yarn config set nodeLinker node-modules
yarn install
node release.mjs
- name: Run with Node.js + yarn pnp
if: ${{ matrix.package-manager == 'yarn-pnp' }}
run: |
corepack enable
yarn set version stable
yarn config set enableImmutableInstalls false
yarn config set enableScripts false
yarn config set nodeLinker pnp
yarn install
yarn node release.mjs
- name: Run with Node.js + yarn v1
if: ${{ matrix.package-manager == 'yarn-v1' }}
run: |
corepack enable
yarn set version classic
yarn install
node release.mjs
- name: Run with Deno
if: ${{ matrix.runtime == 'deno' }}
run: deno run --allow-read --allow-ffi release.mjs
- name: Run with Bun
if: ${{ matrix.runtime == 'bun' }}
run: |
bun install --ignore-scripts
bun release.mjs

33
.gitignore vendored
View File

@ -1,17 +1,18 @@
lib-cov src/build
*.seed src/node_modules
*.log
*.csv
*.dat
*.out
*.pid
*.gz
pids
logs
results
build
node_modules node_modules
tests/output.jpg /coverage
npm/*/*
npm-debug.log !npm/*/package.json
test/bench/node_modules
test/fixtures/output*
test/fixtures/vips-properties.xml
test/leak/libvips.supp
.DS_Store
.nyc_output
.vscode/
package-lock.json
.idea
.firebase
.astro
docs/dist

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,8 +0,0 @@
language: node_js
node_js:
- "0.11"
- "0.10"
before_install:
- sudo apt-get update -qq
- sudo apt-get install -qq libvips-dev imagemagick
- sudo ln -s /usr/lib/pkgconfig/vips-7.26.pc /usr/lib/pkgconfig/vips.pc

151
README.md Executable file → Normal file
View File

@ -1,63 +1,118 @@
# sharp # sharp
_adj_ <img src="https://sharp.pixelplumbing.com/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right">
1. clearly defined; distinct: a sharp photographic image. The typical use case for this high speed Node-API module
2. quick, brisk, or spirited. is to convert large images in common formats to
3. shrewd or astute: a sharp bargainer. smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions.
4. (Informal.) very stylish: a sharp dresser; a sharp jacket.
The typical use case for this high performance Node.js module is to convert a large JPEG image to smaller JPEG images of varying dimensions. It can be used with all JavaScript runtimes
that provide support for Node-API v9, including
Node.js (^18.17.0 or >= 20.3.0), Deno and Bun.
It is somewhat opinionated in that it only deals with JPEG images, always obeys the requested dimensions by either cropping or embedding and insists on a mild sharpen of the resulting image. Resizing an image is typically 4x-5x faster than using the
quickest ImageMagick and GraphicsMagick settings
due to its use of [libvips](https://github.com/libvips/libvips).
Under the hood you'll find the blazingly fast [libvips](https://github.com/jcupitt/libvips) image processing library, originally created in 1989 at Birkbeck College and currently maintained by the University of Southampton. Speed is typically 25-30% faster than the imagemagick equivalent. Colour spaces, embedded ICC profiles and alpha transparency channels are all handled correctly.
Lanczos resampling ensures quality is not sacrificed for speed.
## Prerequisites As well as image resizing, operations such as
rotation, extraction, compositing and gamma correction are available.
Requires node-gyp and libvips-dev to build. Most modern macOS, Windows and Linux systems
do not require any additional install or runtime dependencies.
sudo npm install -g node-gyp ## Documentation
sudo apt-get install libvips-dev
Requires vips-7.xx.pc (installed with libvips-dev) to be symlinked as /usr/lib/pkgconfig/vips.pc Visit [sharp.pixelplumbing.com](https://sharp.pixelplumbing.com/) for complete
[installation instructions](https://sharp.pixelplumbing.com/install),
[API documentation](https://sharp.pixelplumbing.com/api-constructor),
[benchmark tests](https://sharp.pixelplumbing.com/performance) and
[changelog](https://sharp.pixelplumbing.com/changelog).
Ubuntu 12.04 LTS: ## Examples
sudo ln -s /usr/lib/pkgconfig/vips-7.26.pc /usr/lib/pkgconfig/vips.pc ```sh
npm install sharp
Ubuntu 13.04:
sudo ln -s /usr/lib/x86_64-linux-gnu/pkgconfig/vips-7.28.pc /usr/lib/pkgconfig/vips.pc
## Install
npm install sharp
## Usage
```javascript
var sharp = require("sharp");
sharp.crop("input.jpg", "output.jpg", 300, 200, function(err) {
if (err) {
throw err;
}
// output.jpg is cropped input.jpg
});
sharp.embedWhite("input.jpg", "output.jpg", 200, 300, function(err) {
if (err) {
throw err;
}
// output.jpg contains input.jpg embedded with a white border
});
sharp.embedBlack("input.jpg", "output.jpg", 200, 300, function(err) {
if (err) {
throw err;
}
// output.jpg contains input.jpg embedded with a black border
});
``` ```
## Testing [![Build Status](https://travis-ci.org/lovell/sharp.png?branch=master)](https://travis-ci.org/lovell/sharp) ```javascript
const sharp = require('sharp');
```
npm test ### Callback
```javascript
sharp(inputBuffer)
.resize(320, 240)
.toFile('output.webp', (err, info) => { ... });
```
### Promise
```javascript
sharp('input.jpg')
.rotate()
.resize(200)
.jpeg({ mozjpeg: true })
.toBuffer()
.then( data => { ... })
.catch( err => { ... });
```
### Async/await
```javascript
const semiTransparentRedPng = await sharp({
create: {
width: 48,
height: 48,
channels: 4,
background: { r: 255, g: 0, b: 0, alpha: 0.5 }
}
})
.png()
.toBuffer();
```
### Stream
```javascript
const roundedCorners = Buffer.from(
'<svg><rect x="0" y="0" width="200" height="200" rx="50" ry="50"/></svg>'
);
const roundedCornerResizer =
sharp()
.resize(200, 200)
.composite([{
input: roundedCorners,
blend: 'dest-in'
}])
.png();
readableStream
.pipe(roundedCornerResizer)
.pipe(writableStream);
```
## Contributing
A [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md)
covers reporting bugs, requesting features and submitting code changes.
## Licensing
Copyright 2013 Lovell Fuller and others.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,14 +0,0 @@
{
'targets': [{
'target_name': 'sharp',
'sources': ['src/sharp.cc'],
'libraries': ['<!@(PKG_CONFIG_PATH="/usr/lib/pkgconfig" pkg-config --libs glib-2.0 vips)'],
'include_dirs': [
'/usr/include/glib-2.0',
'/usr/lib/glib-2.0/include',
'/usr/lib/x86_64-linux-gnu/glib-2.0/include'
],
'cflags': ['-fexceptions'],
'cflags_cc': ['-fexceptions']
}]
}

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

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

42
docs/build.mjs Normal file
View File

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

16
docs/firebase.json Normal file
View File

@ -0,0 +1,16 @@
{
"hosting": {
"site": "pixelplumbing-sharp",
"public": "dist",
"headers": [
{
"source": "**",
"headers": [
{ "key": "Cache-Control", "value": "max-age=86400" },
{ "key": "X-Content-Type-Options", "value": "nosniff" },
{ "key": "X-Frame-Options", "value": "SAMEORIGIN" }
]
}
]
}
}

17
docs/package.json Normal file
View File

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

View File

@ -0,0 +1,61 @@
<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="998" height="243" viewBox="0 0 998 243">
<defs>
<g id="placeholder">
<rect width="180" height="128" fill="#64bed8"/>
<circle cx="61.1" cy="36.8" r="19.3" fill="#ffefa9"/>
<circle cx="61.1" cy="36.8" r="18.1" fill="#fdda42"/>
<path d="m67.2 34.7 15.2 46L90 57.9l30.4 38 7.8-15.2 7.5 15.4H44z" fill="#6a696f"/>
<path d="m82.4 80.7-15.2-46-.3 69h22.9z" fill="#474749"/>
<path d="m90.1 58 12.2 15 18.2 23-13.9.1z" fill="#474749"/>
<path d="M135.8 96H131l-2.8-15.3z" fill="#474749"/>
<path d="M35.2 96h107.1c0 1.7-1.4 3.2-3.2 3.2H38.4a3.2 3.2 0 0 1-3.2-3.2z" fill="#b9c861"/>
<path d="m67.2 34.7-.1 31-6.2-3-5.3 2.7z" fill="#fff"/>
<path d="m67.2 34.7 7.6 23-7.7 8z" fill="#b3b1b4"/>
<rect width="30.8" height="7.7" x="71.1" y="27.2" rx="2.8" ry="4.1" fill="#fff"/>
<rect width="30.8" height="7.7" x="82.2" y="34.8" rx="2.8" ry="4.1" fill="#fff"/>
<rect width="30.8" height="7.7" x="36.2" y="19.6" rx="2.8" ry="4.1" fill="#fff"/>
<path d="m89.6 72.8-7.2 7.9L90 57.9l10 23z" fill="#fff"/>
<path d="m90.1 58 10 23 2.2-8z" fill="#b3b1b4"/>
<path d="M131.2 85.2 137 68l9 17.2-8 6z" fill="#8da128"/>
<rect width="109.4" height="6.8" x="33.9" y="99.1" rx="13.2" ry="11.4" fill="#22b0d6"/>
<path d="m137 68-5.8 17.2 6.8 6.1.3-13.7z" fill="#727d2e"/>
<rect width="83.3" height="6.8" x="50.8" y="103.6" rx="10" ry="11.4" fill="#22b0d6"/>
<rect width=".7" height="18.4" x="138" y="77.6" fill="#585657"/>
<rect width=".5" height="5.2" x="2" y="-161.3" fill="#585657" transform="rotate(120)"/>
<rect width=".5" height="5.3" x="5.5" y="-163.3" fill="#585657" transform="rotate(120)"/>
<rect width=".5" height="4.8" x="-142.4" y="77.7" fill="#585657" transform="rotate(240)"/>
<rect width=".5" height="5.1" x="-146" y="75.6" fill="#585657" transform="rotate(240)"/>
</g>
<pattern id="img" height="100%" width="100%" viewBox="0 0 180 128">
<use xlink:href="#placeholder"/>
</pattern>
<pattern id="img-fill" width="100%" height="100%" viewBox="0 0 180 128" preserveAspectRatio="none">
<use xlink:href="#placeholder"/>
</pattern>
</defs>
<rect x="0" y="0" width="998" height="243" fill="#ddd"/>
<g id="cover">
<rect x="22" y="28" width="180" height="132" fill="url(#img)"/>
<rect x="48" y="30" width="128" height="128" fill="none" stroke="#000" stroke-width="4"/>
<text x="112" y="85%" dominant-baseline="middle" text-anchor="middle" font-family="sans" font-size="32" font-weight="bold">cover</text>
</g>
<g id="contain">
<rect x="240" y="30" width="128" height="128" fill="url(#img)" stroke="#000" stroke-width="4"/>
<text x="304" y="85%" dominant-baseline="middle" text-anchor="middle" font-family="sans" font-size="32" font-weight="bold" fill="#555">contain</text>
</g>
<g id="fill">
<rect x="432" y="30" width="128" height="128" fill="url(#img-fill)" stroke="#000" stroke-width="4"/>
<text x="496" y="85%" dominant-baseline="middle" text-anchor="middle" font-family="sans" font-size="32" font-weight="bold">fill</text>
</g>
<g id="inside">
<rect x="624" y="48" width="128" height="92" fill="url(#img)" stroke="#000" stroke-width="4"/>
<rect x="624" y="30" width="128" height="128" fill="none" stroke="#000" stroke-width="4" stroke-dasharray="12 4" stroke-dashoffset="6"/>
<text x="688" y="85%" dominant-baseline="middle" text-anchor="middle" font-family="sans" font-size="32" font-weight="bold" fill="#555">inside</text>
</g>
<g id="outside">
<rect x="792" y="30" width="176" height="128" fill="url(#img)" stroke="#000" stroke-width="4"/>
<rect x="816" y="30" width="128" height="128" fill="none" stroke="#000" stroke-width="4" stroke-dasharray="12 4" stroke-dashoffset="-2"/>
<text x="880" y="85%" dominant-baseline="middle" text-anchor="middle" font-family="sans" font-size="32" font-weight="bold">outside</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

5
docs/public/favicon.svg Normal file
View File

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

After

Width:  |  Height:  |  Size: 508 B

325
docs/public/humans.txt Normal file
View File

@ -0,0 +1,325 @@
/* THANKS */
Name: John Cupitt
GitHub: https://github.com/jcupitt
Name: Pierre Inglebert
GitHub: https://github.com/pierreinglebert
Name: Jonathan Ong
GitHub: https://github.com/jonathanong
Name: Chanon Sajjamanochai
GitHub: https://github.com/chanon
Name: Juliano Julio
GitHub: https://github.com/julianojulio
Name: Daniel Gasienica
GitHub: https://github.com/gasi
Name: Julian Walker
GitHub: https://github.com/julianwa
Name: Amit Pitaru
GitHub: https://github.com/apitaru
Name: Brandon Aaron
GitHub: https://github.com/brandonaaron
Name: Andreas Lind
GitHub: https://github.com/papandreou
Name: Maurus Cuelenaere
GitHub: https://github.com/mcuelenaere
Name: Linus Unnebäck
GitHub: https://github.com/LinusU
Name: Victor Mateevitsi
GitHub: https://github.com/mvictoras
Name: Alaric Holloway
GitHub: https://github.com/skedastik
Name: Bernhard K. Weisshuhn
GitHub: https://github.com/bkw
Name: David A. Carley
GitHub: https://github.com/dacarley
Name: John Tobin
GitHub: https://github.com/jtobinisaniceguy
Name: Kenton Gray
GitHub: https://github.com/kentongray
Name: Felix Bünemann
GitHub: https://github.com/felixbuenemann
Name: Samy Al Zahrani
GitHub: https://github.com/salzhrani
Name: Chintan Thakkar
GitHub: https://github.com/lemnisk8
Name: F. Orlando Galashan
GitHub: https://github.com/frulo
Name: Kleis Auke Wolthuizen
GitHub: https://github.com/kleisauke
Name: Matt Hirsch
GitHub: https://github.com/mhirsch
Name: Rahul Nanwani
GitHub: https://github.com/rnanwani
Name: Matthias Thoemmes
GitHub: https://github.com/cmtt
Name: Patrick Paskaris
GitHub: https://github.com/ppaskaris
Name: Jérémy Lal
GitHub: https://github.com/kapouer
Name: Alice Monday
GitHub: https://github.com/alice0meta
Name: Kristo Jorgenson
GitHub: https://github.com/kristojorg
Name: Yves Bos
GitHub: https://github.com/YvesBos
Name: Nicolas Coden
GitHub: https://github.com/ncoden
Name: Matt Parrish
GitHub: https://github.com/pbomb
Name: Matthew McEachen
GitHub: https://github.com/mceachen
Name: Jarda Kotěšovec
GitHub: https://github.com/jardakotesovec
Name: Kenric D'Souza
GitHub: https://github.com/AzureByte
Name: Oleh Aleinyk
GitHub: https://github.com/oaleynik
Name: Marcel Bretschneider
GitHub: https://github.com/3epnm
Name: Andrea Bianco
GitHub: https://github.com/BiancoA
Name: Rik Heywood
GitHub: https://github.com/rikh42
Name: Thomas Parisot
GitHub: https://github.com/oncletom
Name: Nathan Graves
GitHub: https://github.com/woolite64
Name: Tom Lokhorst
GitHub: https://github.com/tomlokhorst
Name: Espen Hovlandsdal
GitHub: https://github.com/rexxars
Name: Sylvain Dumont
GitHub: https://github.com/sylvaindumont
Name: Alun Davies
GitHub: https://github.com/alundavies
Name: Aidan Hoolachan
GitHub: https://github.com/ajhool
Name: Axel Eirola
GitHub: https://github.com/aeirola
Name: Freezy
GitHub: https://github.com/freezy
Name: Julian Aubourg
GitHub: https://github.com/jaubourg
Name: Keith Belovay
GitHub: https://github.com/fromkeith
Name: Michael B. Klein
GitHub: https://github.com/mbklein
Name: Jakub Michálek
GitHub: https://github.com/Goues
Name: Ilya Ovdin
GitHub: https://github.com/iovdin
Name: Andargor
GitHub: https://github.com/Andargor
Name: Nicolas Stepien
GitHub: https://github.com/MayhemYDG
Name: Paul Neave
GitHub: https://github.com/neave
Name: Brendan Kennedy
GitHub: https://github.com/rustyguts
Name: Brychan Bennett-Odlum
GitHub: https://github.com/BrychanOdlum
Name: Edward Silverton
GitHub: https://github.com/edsilv
Name: Dumitru Deveatii
GitHub: https://github.com/dimadeveatii
Name: Roland Asmann
GitHub: https://github.com/malice00
Name: Roman Malieiev
GitHub: https://github.com/romaleev
Name: Jerome Vouillon
GitHub: https://github.com/vouillon
Name: Tomáš Szabo
GitHub: https://github.com/deftomat
Name: Robert O'Rourke
GitHub: https://github.com/roborourke
Name: Denis Soldatov
GitHub: https://github.com/derom
Name: Stefan Probst
GitHub: https://github.com/stefanprobst
Name: Thomas Beiganz
GitHub: https://github.com/beig
Name: Florian Busch
GitHub: https://github.com/florian-busch
Name: Matthieu Salettes
GitHub: https://github.com/msalettes
Name: Taneli Vatanen
GitHub: https://github.com/Daiz
Name: Mart Jansink
GitHub: https://github.com/mart-jansink
Name: Tenpi
GitHub: https://github.com/Tenpi
Name: Zaruike
GitHub: https://github.com/Zaruike
Name: Erlend F
GitHub: https://github.com/erf
Name: Drian Naude
GitHub: https://github.com/driannaude
Name: Max Gordon
GitHub: https://github.com/gforge
Name: Chris Banks
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
Name: Emanuel Jöbstl
GitHub: https://github.com/ejoebstl
Name: Tomasz Janowski
GitHub: https://github.com/janaz
Name: Lachlan Newman
GitHub: https://github.com/LachlanNewman
Name: BJJ
GitHub: https://github.com/bianjunjie1981
Name: Dennis Beatty
GitHub: https://github.com/dnsbty
Name: Ingvar Stepanyan
GitHub: https://github.com/RReverser
Name: Tamás András Horváth
GitHub: https://github.com/icetee
Name: Aaron Che
GitHub: https://github.com/yolopunk
Name: Mert Alev
GitHub: https://github.com/mertalev
Name: Adriaan Meuris
GitHub: https://github.com/adriaanmeuris
Name: Richard Hillmann
GitHub: https://github.com/project0
Name: Pongsatorn Manusopit
GitHub: https://github.com/ton11797
Name: Nathan Keynes
GitHub: https://github.com/nkeynes
Name: Sumit D
GitHub: https://github.com/sumitd2
Name: Caleb Meredith
GitHub: https://github.com/calebmer
Name: Don Denton
GitHub: https://github.com/happycollision
Name: Florent Zabera
GitHub: https://github.com/florentzabera
Name: Quentin Pinçon
GitHub: https://github.com/qpincon
Name: Hans Chen
GitHub: https://github.com/hans00
Name: Thibaut Patel
GitHub: https://github.com/tpatel

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

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

View File

@ -0,0 +1,11 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="86 86 550 550">
<!-- Creative Commons CC0 1.0 Universal Public Domain Dedication -->
<defs>
<mask id="c">
<path fill="none" stroke="#fff" stroke-width="80" d="M258.411 285.777l200.176-26.8M244.113 466.413L451.44 438.66m.001 0V238.484m0-150.121v171.572l178.725-23.917m-359.843 19.584V477.22m2.387 156.95V462.591L93.984 486.515"/>
<path fill="none" stroke="#000" stroke-width="112" d="M451.441 610.246V438.66l178.725-23.91M269.688 112.59v171.58L90.964 308.093"/>
</mask>
</defs>
<path mask="url(#c)" fill="none" stroke="#000" stroke-width="80" d="M258.411 285.777l200.176-26.8M244.113 466.413L451.44 438.66m.001 0V238.484m0-150.121v171.572l178.725-23.917m-359.843 19.584V477.22m2.387 156.95V462.591L93.984 486.515"/>
<path fill="none" stroke="#000" stroke-width="80" d="M451.441 610.246V438.66l178.725-23.91M269.688 112.59v171.58L90.964 308.093"/>
</svg>

After

Width:  |  Height:  |  Size: 929 B

View File

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

After

Width:  |  Height:  |  Size: 508 B

View File

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

After

Width:  |  Height:  |  Size: 508 B

View File

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

View File

@ -0,0 +1,141 @@
---
# This file was auto-generated from JSDoc in lib/channel.js
title: Channel manipulation
---
## removeAlpha
> removeAlpha() ⇒ <code>Sharp</code>
Remove alpha channels, if any. This is a no-op if the image does not have an alpha channel.
See also [flatten](/api-operation#flatten).
**Example**
```js
sharp('rgba.png')
.removeAlpha()
.toFile('rgb.png', function(err, info) {
// rgb.png is a 3 channel image without an alpha channel
});
```
## ensureAlpha
> ensureAlpha([alpha]) ⇒ <code>Sharp</code>
Ensure the output image has an alpha transparency channel.
If missing, the added alpha channel will have the specified
transparency level, defaulting to fully-opaque (1).
This is a no-op if the image already has an alpha channel.
**Throws**:
- <code>Error</code> Invalid alpha transparency level
**Since**: 0.21.2
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [alpha] | <code>number</code> | <code>1</code> | alpha transparency level (0=fully-transparent, 1=fully-opaque) |
**Example**
```js
// rgba.png will be a 4 channel image with a fully-opaque alpha channel
await sharp('rgb.jpg')
.ensureAlpha()
.toFile('rgba.png')
```
**Example**
```js
// rgba is a 4 channel image with a fully-transparent alpha channel
const rgba = await sharp(rgb)
.ensureAlpha(0)
.toBuffer();
```
## extractChannel
> extractChannel(channel) ⇒ <code>Sharp</code>
Extract a single channel from a multi-channel image.
**Throws**:
- <code>Error</code> Invalid channel
| Param | Type | Description |
| --- | --- | --- |
| channel | <code>number</code> \| <code>string</code> | zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`. |
**Example**
```js
// green.jpg is a greyscale image containing the green channel of the input
await sharp(input)
.extractChannel('green')
.toFile('green.jpg');
```
**Example**
```js
// red1 is the red value of the first pixel, red2 the second pixel etc.
const [red1, red2, ...] = await sharp(input)
.extractChannel(0)
.raw()
.toBuffer();
```
## joinChannel
> joinChannel(images, options) ⇒ <code>Sharp</code>
Join one or more channels to the image.
The meaning of the added channels depends on the output colourspace, set with `toColourspace()`.
By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.
Channel ordering follows vips convention:
- sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha.
- CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha.
Buffers may be any of the image formats supported by sharp.
For raw pixel input, the `options` object should contain a `raw` attribute, which follows the format of the attribute of the same name in the `sharp()` constructor.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Description |
| --- | --- | --- |
| images | <code>Array.&lt;(string\|Buffer)&gt;</code> \| <code>string</code> \| <code>Buffer</code> | one or more images (file paths, Buffers). |
| options | <code>Object</code> | image options, see `sharp()` constructor. |
## bandbool
> bandbool(boolOp) ⇒ <code>Sharp</code>
Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Description |
| --- | --- | --- |
| boolOp | <code>string</code> | one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. |
**Example**
```js
sharp('3-channel-rgb-input.png')
.bandbool(sharp.bool.and)
.toFile('1-channel-output.png', function (err, info) {
// The output will be a single channel image where each pixel `P = R & G & B`.
// If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]`
// then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`.
});
```

View File

@ -0,0 +1,150 @@
---
# This file was auto-generated from JSDoc in lib/colour.js
title: Colour manipulation
---
## tint
> tint(tint) ⇒ <code>Sharp</code>
Tint the image using the provided colour.
An alpha channel may be present and will be unchanged by the operation.
**Throws**:
- <code>Error</code> Invalid parameter
| Param | Type | Description |
| --- | --- | --- |
| tint | <code>string</code> \| <code>Object</code> | Parsed by the [color](https://www.npmjs.org/package/color) module. |
**Example**
```js
const output = await sharp(input)
.tint({ r: 255, g: 240, b: 16 })
.toBuffer();
```
## greyscale
> greyscale([greyscale]) ⇒ <code>Sharp</code>
Convert to 8-bit greyscale; 256 shades of grey.
This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results.
By default the output image will be web-friendly sRGB and contain three (identical) colour channels.
This may be overridden by other sharp operations such as `toColourspace('b-w')`,
which will produce an output image containing one colour channel.
An alpha channel may be present, and will be unchanged by the operation.
| Param | Type | Default |
| --- | --- | --- |
| [greyscale] | <code>Boolean</code> | <code>true</code> |
**Example**
```js
const output = await sharp(input).greyscale().toBuffer();
```
## grayscale
> grayscale([grayscale]) ⇒ <code>Sharp</code>
Alternative spelling of `greyscale`.
| Param | Type | Default |
| --- | --- | --- |
| [grayscale] | <code>Boolean</code> | <code>true</code> |
## pipelineColourspace
> pipelineColourspace([colourspace]) ⇒ <code>Sharp</code>
Set the pipeline colourspace.
The input image will be converted to the provided colourspace at the start of the pipeline.
All operations will use this colourspace before converting to the output colourspace,
as defined by [toColourspace](#tocolourspace).
**Throws**:
- <code>Error</code> Invalid parameters
**Since**: 0.29.0
| Param | Type | Description |
| --- | --- | --- |
| [colourspace] | <code>string</code> | pipeline colourspace e.g. `rgb16`, `scrgb`, `lab`, `grey16` [...](https://github.com/libvips/libvips/blob/41cff4e9d0838498487a00623462204eb10ee5b8/libvips/iofuncs/enumtypes.c#L774) |
**Example**
```js
// Run pipeline in 16 bits per channel RGB while converting final result to 8 bits per channel sRGB.
await sharp(input)
.pipelineColourspace('rgb16')
.toColourspace('srgb')
.toFile('16bpc-pipeline-to-8bpc-output.png')
```
## pipelineColorspace
> pipelineColorspace([colorspace]) ⇒ <code>Sharp</code>
Alternative spelling of `pipelineColourspace`.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Description |
| --- | --- | --- |
| [colorspace] | <code>string</code> | pipeline colorspace. |
## toColourspace
> toColourspace([colourspace]) ⇒ <code>Sharp</code>
Set the output colourspace.
By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Description |
| --- | --- | --- |
| [colourspace] | <code>string</code> | output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/libvips/libvips/blob/3c0bfdf74ce1dc37a6429bed47fa76f16e2cd70a/libvips/iofuncs/enumtypes.c#L777-L794) |
**Example**
```js
// Output 16 bits per pixel RGB
await sharp(input)
.toColourspace('rgb16')
.toFile('16-bpp.png')
```
## toColorspace
> toColorspace([colorspace]) ⇒ <code>Sharp</code>
Alternative spelling of `toColourspace`.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Description |
| --- | --- | --- |
| [colorspace] | <code>string</code> | output colorspace. |

View File

@ -0,0 +1,103 @@
---
# This file was auto-generated from JSDoc in lib/composite.js
title: Compositing images
---
## composite
> composite(images) ⇒ <code>Sharp</code>
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.
If both `top` and `left` options are provided, they take precedence over `gravity`.
Other operations in the same processing pipeline (e.g. resize, rotate, flip,
flop, extract) will always be applied to the input image before composition.
The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`,
`dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`,
`xor`, `add`, `saturate`, `multiply`, `screen`, `overlay`, `darken`, `lighten`,
`colour-dodge`, `color-dodge`, `colour-burn`,`color-burn`,
`hard-light`, `soft-light`, `difference`, `exclusion`.
More information about blend modes can be found at
https://www.libvips.org/API/current/libvips-conversion.html#VipsBlendMode
and https://www.cairographics.org/operators/
**Throws**:
- <code>Error</code> Invalid parameters
**Since**: 0.22.0
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| images | <code>Array.&lt;Object&gt;</code> | | Ordered list of images to composite |
| [images[].input] | <code>Buffer</code> \| <code>String</code> | | Buffer containing image data, String containing the path to an image file, or Create object (see below) |
| [images[].input.create] | <code>Object</code> | | describes a blank overlay to be created. |
| [images[].input.create.width] | <code>Number</code> | | |
| [images[].input.create.height] | <code>Number</code> | | |
| [images[].input.create.channels] | <code>Number</code> | | 3-4 |
| [images[].input.create.background] | <code>String</code> \| <code>Object</code> | | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |
| [images[].input.text] | <code>Object</code> | | describes a new text image to be created. |
| [images[].input.text.text] | <code>string</code> | | text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`. |
| [images[].input.text.font] | <code>string</code> | | font name to render with. |
| [images[].input.text.fontfile] | <code>string</code> | | absolute filesystem path to a font file that can be used by `font`. |
| [images[].input.text.width] | <code>number</code> | <code>0</code> | integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. |
| [images[].input.text.height] | <code>number</code> | <code>0</code> | 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. |
| [images[].input.text.align] | <code>string</code> | <code>&quot;&#x27;left&#x27;&quot;</code> | text alignment (`'left'`, `'centre'`, `'center'`, `'right'`). |
| [images[].input.text.justify] | <code>boolean</code> | <code>false</code> | set this to true to apply justification to the text. |
| [images[].input.text.dpi] | <code>number</code> | <code>72</code> | the resolution (size) at which to render the text. Does not take effect if `height` is specified. |
| [images[].input.text.rgba] | <code>boolean</code> | <code>false</code> | set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like `<span foreground="red">Red!</span>`. |
| [images[].input.text.spacing] | <code>number</code> | <code>0</code> | text line height in points. Will use the font line height if none is specified. |
| [images[].autoOrient] | <code>Boolean</code> | <code>false</code> | set to true to use EXIF orientation data, if present, to orient the image. |
| [images[].blend] | <code>String</code> | <code>&#x27;over&#x27;</code> | how to blend this image with the image below. |
| [images[].gravity] | <code>String</code> | <code>&#x27;centre&#x27;</code> | gravity at which to place the overlay. |
| [images[].top] | <code>Number</code> | | the pixel offset from the top edge. |
| [images[].left] | <code>Number</code> | | the pixel offset from the left edge. |
| [images[].tile] | <code>Boolean</code> | <code>false</code> | set to true to repeat the overlay image across the entire image with the given `gravity`. |
| [images[].premultiplied] | <code>Boolean</code> | <code>false</code> | set to true to avoid premultiplying the image below. Equivalent to the `--premultiplied` vips option. |
| [images[].density] | <code>Number</code> | <code>72</code> | number representing the DPI for vector overlay image. |
| [images[].raw] | <code>Object</code> | | describes overlay when using raw pixel data. |
| [images[].raw.width] | <code>Number</code> | | |
| [images[].raw.height] | <code>Number</code> | | |
| [images[].raw.channels] | <code>Number</code> | | |
| [images[].animated] | <code>boolean</code> | <code>false</code> | Set to `true` to read all frames/pages of an animated image. |
| [images[].failOn] | <code>string</code> | <code>&quot;&#x27;warning&#x27;&quot;</code> | @see [constructor parameters](/api-constructor#parameters) |
| [images[].limitInputPixels] | <code>number</code> \| <code>boolean</code> | <code>268402689</code> | @see [constructor parameters](/api-constructor#parameters) |
**Example**
```js
await sharp(background)
.composite([
{ input: layer1, gravity: 'northwest' },
{ input: layer2, gravity: 'southeast' },
])
.toFile('combined.png');
```
**Example**
```js
const output = await sharp('input.gif', { animated: true })
.composite([
{ input: 'overlay.png', tile: true, blend: 'saturate' }
])
.toBuffer();
```
**Example**
```js
sharp('input.png')
.rotate(180)
.resize(300)
.flatten( { background: '#ff6600' } )
.composite([{ input: 'overlay.png', gravity: 'southeast' }])
.sharpen()
.withMetadata()
.webp( { quality: 90 } )
.toBuffer()
.then(function(outputBuffer) {
// outputBuffer contains upside down, 300px wide, alpha channel flattened
// onto orange background, composited with overlay.png with SE gravity,
// sharpened, with metadata, 90% quality WebP image data. Phew!
});
```

View File

@ -0,0 +1,274 @@
---
# This file was auto-generated from JSDoc in lib/constructor.js
title: Constructor
---
## Sharp
> Sharp
**Emits**: <code>Sharp#event:info</code>, <code>Sharp#event:warning</code>
<a name="new_Sharp_new"></a>
### new
> new Sharp([input], [options])
Constructor factory to create an instance of `sharp`, to which further methods are chained.
JPEG, PNG, WebP, GIF, AVIF or TIFF format image data can be streamed out from this object.
When using Stream based output, derived attributes are available from the `info` event.
Non-critical problems encountered during processing are emitted as `warning` events.
Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.
When loading more than one page/frame of an animated image,
these are combined as a vertically-stacked "toilet roll" image
where the overall height is the `pageHeight` multiplied by the number of `pages`.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [input] | <code>Buffer</code> \| <code>ArrayBuffer</code> \| <code>Uint8Array</code> \| <code>Uint8ClampedArray</code> \| <code>Int8Array</code> \| <code>Uint16Array</code> \| <code>Int16Array</code> \| <code>Uint32Array</code> \| <code>Int32Array</code> \| <code>Float32Array</code> \| <code>Float64Array</code> \| <code>string</code> \| <code>Array</code> | | if present, can be a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or a TypedArray containing raw pixel image data, or a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. An array of inputs can be provided, and these will be joined together. JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. |
| [options] | <code>Object</code> | | if present, is an Object with optional attributes. |
| [options.failOn] | <code>string</code> | <code>&quot;&#x27;warning&#x27;&quot;</code> | When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort. |
| [options.limitInputPixels] | <code>number</code> \| <code>boolean</code> | <code>268402689</code> | Do not process input images where the number of pixels (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted. An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). |
| [options.unlimited] | <code>boolean</code> | <code>false</code> | Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). |
| [options.autoOrient] | <code>boolean</code> | <code>false</code> | Set this to `true` to rotate/flip the image to match EXIF `Orientation`, if any. |
| [options.sequentialRead] | <code>boolean</code> | <code>true</code> | Set this to `false` to use random access rather than sequential read. Some operations will do this automatically. |
| [options.density] | <code>number</code> | <code>72</code> | number representing the DPI for vector images in the range 1 to 100000. |
| [options.ignoreIcc] | <code>number</code> | <code>false</code> | should the embedded ICC profile, if any, be ignored. |
| [options.pages] | <code>number</code> | <code>1</code> | Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages. |
| [options.page] | <code>number</code> | <code>0</code> | Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based. |
| [options.animated] | <code>boolean</code> | <code>false</code> | Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`. |
| [options.raw] | <code>Object</code> | | describes raw pixel input image data. See `raw()` for pixel ordering. |
| [options.raw.width] | <code>number</code> | | integral number of pixels wide. |
| [options.raw.height] | <code>number</code> | | integral number of pixels high. |
| [options.raw.channels] | <code>number</code> | | integral number of channels, between 1 and 4. |
| [options.raw.premultiplied] | <code>boolean</code> | | specifies that the raw input has already been premultiplied, set to `true` to avoid sharp premultiplying the image. (optional, default `false`) |
| [options.raw.pageHeight] | <code>number</code> | | The pixel height of each page/frame for animated images, must be an integral factor of `raw.height`. |
| [options.create] | <code>Object</code> | | describes a new image to be created. |
| [options.create.width] | <code>number</code> | | integral number of pixels wide. |
| [options.create.height] | <code>number</code> | | integral number of pixels high. |
| [options.create.channels] | <code>number</code> | | integral number of channels, either 3 (RGB) or 4 (RGBA). |
| [options.create.background] | <code>string</code> \| <code>Object</code> | | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |
| [options.create.pageHeight] | <code>number</code> | | The pixel height of each page/frame for animated images, must be an integral factor of `create.height`. |
| [options.create.noise] | <code>Object</code> | | describes a noise to be created. |
| [options.create.noise.type] | <code>string</code> | | type of generated noise, currently only `gaussian` is supported. |
| [options.create.noise.mean] | <code>number</code> | <code>128</code> | Mean value of pixels in the generated noise. |
| [options.create.noise.sigma] | <code>number</code> | <code>30</code> | Standard deviation of pixel values in the generated noise. |
| [options.text] | <code>Object</code> | | describes a new text image to be created. |
| [options.text.text] | <code>string</code> | | text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`. |
| [options.text.font] | <code>string</code> | | font name to render with. |
| [options.text.fontfile] | <code>string</code> | | absolute filesystem path to a font file that can be used by `font`. |
| [options.text.width] | <code>number</code> | <code>0</code> | Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. |
| [options.text.height] | <code>number</code> | <code>0</code> | Maximum 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. |
| [options.text.align] | <code>string</code> | <code>&quot;&#x27;left&#x27;&quot;</code> | Alignment style for multi-line text (`'left'`, `'centre'`, `'center'`, `'right'`). |
| [options.text.justify] | <code>boolean</code> | <code>false</code> | set this to true to apply justification to the text. |
| [options.text.dpi] | <code>number</code> | <code>72</code> | the resolution (size) at which to render the text. Does not take effect if `height` is specified. |
| [options.text.rgba] | <code>boolean</code> | <code>false</code> | set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`. |
| [options.text.spacing] | <code>number</code> | <code>0</code> | text line height in points. Will use the font line height if none is specified. |
| [options.text.wrap] | <code>string</code> | <code>&quot;&#x27;word&#x27;&quot;</code> | word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'. |
| [options.join] | <code>Object</code> | | describes how an array of input images should be joined. |
| [options.join.across] | <code>number</code> | <code>1</code> | number of images to join horizontally. |
| [options.join.animated] | <code>boolean</code> | <code>false</code> | set this to `true` to join the images as an animated image. |
| [options.join.shim] | <code>number</code> | <code>0</code> | number of pixels to insert between joined images. |
| [options.join.background] | <code>string</code> \| <code>Object</code> | | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |
| [options.join.halign] | <code>string</code> | <code>&quot;&#x27;left&#x27;&quot;</code> | horizontal alignment style for images joined horizontally (`'left'`, `'centre'`, `'center'`, `'right'`). |
| [options.join.valign] | <code>string</code> | <code>&quot;&#x27;top&#x27;&quot;</code> | vertical alignment style for images joined vertically (`'top'`, `'centre'`, `'center'`, `'bottom'`). |
| [options.tiff] | <code>Object</code> | | Describes TIFF specific options. |
| [options.tiff.subifd] | <code>number</code> | <code>-1</code> | Sub Image File Directory to extract for OME-TIFF, defaults to main image. |
| [options.svg] | <code>Object</code> | | Describes SVG specific options. |
| [options.svg.stylesheet] | <code>string</code> | | Custom CSS for SVG input, applied with a User Origin during the CSS cascade. |
| [options.svg.highBitdepth] | <code>boolean</code> | <code>false</code> | Set to `true` to render SVG input at 32-bits per channel (128-bit) instead of 8-bits per channel (32-bit) RGBA. |
| [options.pdf] | <code>Object</code> | | Describes PDF specific options. Requires the use of a globally-installed libvips compiled with support for PDFium, Poppler, ImageMagick or GraphicsMagick. |
| [options.pdf.background] | <code>string</code> \| <code>Object</code> | | Background colour to use when PDF is partially transparent. Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |
| [options.openSlide] | <code>Object</code> | | Describes OpenSlide specific options. Requires the use of a globally-installed libvips compiled with support for OpenSlide. |
| [options.openSlide.level] | <code>number</code> | <code>0</code> | Level to extract from a multi-level input, zero based. |
| [options.jp2] | <code>Object</code> | | Describes JPEG 2000 specific options. Requires the use of a globally-installed libvips compiled with support for OpenJPEG. |
| [options.jp2.oneshot] | <code>boolean</code> | <code>false</code> | Set to `true` to decode tiled JPEG 2000 images in a single operation, improving compatibility. |
**Example**
```js
sharp('input.jpg')
.resize(300, 200)
.toFile('output.jpg', function(err) {
// output.jpg is a 300 pixels wide and 200 pixels high image
// containing a scaled and cropped version of input.jpg
});
```
**Example**
```js
// Read image data from remote URL,
// resize to 300 pixels wide,
// emit an 'info' event with calculated dimensions
// and finally write image data to writableStream
const { body } = fetch('https://...');
const readableStream = Readable.fromWeb(body);
const transformer = sharp()
.resize(300)
.on('info', ({ height }) => {
console.log(`Image height is ${height}`);
});
readableStream.pipe(transformer).pipe(writableStream);
```
**Example**
```js
// Create a blank 300x200 PNG image of semi-translucent red pixels
sharp({
create: {
width: 300,
height: 200,
channels: 4,
background: { r: 255, g: 0, b: 0, alpha: 0.5 }
}
})
.png()
.toBuffer()
.then( ... );
```
**Example**
```js
// Convert an animated GIF to an animated WebP
await sharp('in.gif', { animated: true }).toFile('out.webp');
```
**Example**
```js
// Read a raw array of pixels and save it to a png
const input = Uint8Array.from([255, 255, 255, 0, 0, 0]); // or Uint8ClampedArray
const image = sharp(input, {
// because the input does not contain its dimensions or how many channels it has
// we need to specify it in the constructor options
raw: {
width: 2,
height: 1,
channels: 3
}
});
await image.toFile('my-two-pixels.png');
```
**Example**
```js
// Generate RGB Gaussian noise
await sharp({
create: {
width: 300,
height: 200,
channels: 3,
noise: {
type: 'gaussian',
mean: 128,
sigma: 30
}
}
}).toFile('noise.png');
```
**Example**
```js
// Generate an image from text
await sharp({
text: {
text: 'Hello, world!',
width: 400, // max width
height: 300 // max height
}
}).toFile('text_bw.png');
```
**Example**
```js
// 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');
```
**Example**
```js
// Join four input images as a 2x2 grid with a 4 pixel gutter
const data = await sharp(
[image1, image2, image3, image4],
{ join: { across: 2, shim: 4 } }
).toBuffer();
```
**Example**
```js
// Generate a two-frame animated image from emoji
const images = ['😀', '😛'].map(text => ({
text: { text, width: 64, height: 64, channels: 4, rgba: true }
}));
await sharp(images, { join: { animated: true } }).toFile('out.gif');
```
## clone
> clone() ⇒ [<code>Sharp</code>](#Sharp)
Take a "snapshot" of the Sharp instance, returning a new instance.
Cloned instances inherit the input of their parent instance.
This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream.
**Example**
```js
const pipeline = sharp().rotate();
pipeline.clone().resize(800, 600).pipe(firstWritableStream);
pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 }).pipe(secondWritableStream);
readableStream.pipe(pipeline);
// firstWritableStream receives auto-rotated, resized readableStream
// secondWritableStream receives auto-rotated, extracted region of readableStream
```
**Example**
```js
// Create a pipeline that will download an image, resize it and format it to different files
// Using Promises to know when the pipeline is complete
const fs = require("fs");
const got = require("got");
const sharpStream = sharp({ failOn: 'none' });
const promises = [];
promises.push(
sharpStream
.clone()
.jpeg({ quality: 100 })
.toFile("originalFile.jpg")
);
promises.push(
sharpStream
.clone()
.resize({ width: 500 })
.jpeg({ quality: 80 })
.toFile("optimized-500.jpg")
);
promises.push(
sharpStream
.clone()
.resize({ width: 500 })
.webp({ quality: 80 })
.toFile("optimized-500.webp")
);
// https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md
got.stream("https://www.example.com/some-file.jpg").pipe(sharpStream);
Promise.all(promises)
.then(res => { console.log("Done!", res); })
.catch(err => {
console.error("Error processing files, let's clean it up", err);
try {
fs.unlinkSync("originalFile.jpg");
fs.unlinkSync("optimized-500.jpg");
fs.unlinkSync("optimized-500.webp");
} catch (e) {}
});
```

View File

@ -0,0 +1,138 @@
---
# This file was auto-generated from JSDoc in lib/input.js
title: Input metadata
---
## metadata
> metadata([callback]) ⇒ <code>Promise.&lt;Object&gt;</code> \| <code>Sharp</code>
Fast access to (uncached) image metadata without decoding any compressed pixel data.
This is read from the header of the input image.
It does not take into consideration any operations to be applied to the output image,
such as resize or rotate.
Dimensions in the response will respect the `page` and `pages` properties of the
[constructor parameters](/api-constructor#parameters).
A `Promise` is returned when `callback` is not provided.
- `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg`
- `size`: Total size of image in bytes, for Stream and Buffer input only
- `width`: Number of pixels wide (EXIF orientation is not taken into consideration, see example below)
- `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://www.libvips.org/API/current/VipsImage.html#VipsInterpretation)
- `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://www.libvips.org/API/current/VipsImage.html#VipsBandFormat)
- `density`: Number of pixels per inch (DPI), if present
- `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK
- `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan
- `isPalette`: Boolean indicating whether the image is palette-based (GIF, PNG).
- `bitsPerSample`: Number of bits per sample for each channel (GIF, PNG, HEIF).
- `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP
- `pageHeight`: Number of pixels high each page in a multi-page image will be.
- `loop`: Number of times to loop an animated image, zero refers to a continuous loop.
- `delay`: Delay in ms between each page in an animated image, provided as an array of integers.
- `pagePrimary`: Number of the primary page in a HEIF image
- `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide
- `subifds`: Number of Sub Image File Directories in an OME-TIFF image
- `background`: Default background colour, if present, for PNG (bKGD) and GIF images
- `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC)
- `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present
- `hasProfile`: Boolean indicating the presence of an embedded ICC profile
- `hasAlpha`: Boolean indicating the presence of an alpha transparency channel
- `orientation`: Number value of the EXIF Orientation header, if present
- `exif`: Buffer containing raw EXIF data, if present
- `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present
- `iptc`: Buffer containing raw IPTC data, if present
- `xmp`: Buffer containing raw XMP data, if present
- `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present
- `formatMagick`: String containing format for images loaded via *magick
- `comments`: Array of keyword/text pairs representing PNG text blocks, if present.
| Param | Type | Description |
| --- | --- | --- |
| [callback] | <code>function</code> | called with the arguments `(err, metadata)` |
**Example**
```js
const metadata = await sharp(input).metadata();
```
**Example**
```js
const image = sharp(inputJpg);
image
.metadata()
.then(function(metadata) {
return image
.resize(Math.round(metadata.width / 2))
.webp()
.toBuffer();
})
.then(function(data) {
// data contains a WebP image half the width and height of the original JPEG
});
```
**Example**
```js
// Get dimensions taking EXIF Orientation into account.
const { autoOrient } = await sharp(input).metadata();
const { width, height } = autoOrient;
```
## stats
> stats([callback]) ⇒ <code>Promise.&lt;Object&gt;</code>
Access to pixel-derived image statistics for every channel in the image.
A `Promise` is returned when `callback` is not provided.
- `channels`: Array of channel statistics for each channel in the image. Each channel statistic contains
- `min` (minimum value in the channel)
- `max` (maximum value in the channel)
- `sum` (sum of all values in a channel)
- `squaresSum` (sum of squared values in a channel)
- `mean` (mean of the values in a channel)
- `stdev` (standard deviation for the values in a channel)
- `minX` (x-coordinate of one of the pixel where the minimum lies)
- `minY` (y-coordinate of one of the pixel where the minimum lies)
- `maxX` (x-coordinate of one of the pixel where the maximum lies)
- `maxY` (y-coordinate of one of the pixel where the maximum lies)
- `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque.
- `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any.
- `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.
**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).
| Param | Type | Description |
| --- | --- | --- |
| [callback] | <code>function</code> | called with the arguments `(err, stats)` |
**Example**
```js
const image = sharp(inputJpg);
image
.stats()
.then(function(stats) {
// stats contains the channel-wise statistics array and the isOpaque value
});
```
**Example**
```js
const { entropy, sharpness, dominant } = await sharp(input).stats();
const { r, g, b } = dominant;
```
**Example**
```js
const image = sharp(input);
// store intermediate result
const part = await image.extract(region).toBuffer();
// create new instance to obtain statistics of extracted region
const stats = await sharp(part).stats();
```

View File

@ -0,0 +1,723 @@
---
# This file was auto-generated from JSDoc in lib/operation.js
title: Image operations
---
## rotate
> rotate([angle], [options]) ⇒ <code>Sharp</code>
Rotate the output image.
The provided angle is converted to a valid positive degree rotation.
For example, `-450` will produce a 270 degree rotation.
When rotating by an angle other than a multiple of 90,
the background colour can be provided with the `background` option.
For backwards compatibility, if no angle is provided, `.autoOrient()` will be called.
Only one rotation can occur per pipeline (aside from an initial call without
arguments to orient via EXIF data). Previous calls to `rotate` in the same
pipeline will be ignored.
Multi-page images can only be rotated by 180 degrees.
Method order is important when rotating, resizing and/or extracting regions,
for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [angle] | <code>number</code> | <code>auto</code> | angle of rotation. |
| [options] | <code>Object</code> | | if present, is an Object with optional attributes. |
| [options.background] | <code>string</code> \| <code>Object</code> | <code>&quot;\&quot;#000000\&quot;&quot;</code> | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |
**Example**
```js
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();
```
## autoOrient
> autoOrient() ⇒ <code>Sharp</code>
Auto-orient based on the EXIF `Orientation` tag, then remove the tag.
Mirroring is supported and may infer the use of a flip operation.
Previous or subsequent use of `rotate(angle)` and either `flip()` or `flop()`
will logically occur after auto-orientation, regardless of call order.
**Example**
```js
const output = await sharp(input).autoOrient().toBuffer();
```
**Example**
```js
const pipeline = sharp()
.autoOrient()
.resize(null, 200)
.toBuffer(function (err, outputBuffer, info) {
// outputBuffer contains 200px high JPEG image data,
// auto-oriented using EXIF Orientation tag
// info.width and info.height contain the dimensions of the resized image
});
readableStream.pipe(pipeline);
```
## flip
> flip([flip]) ⇒ <code>Sharp</code>
Mirror the image vertically (up-down) about the x-axis.
This always occurs before rotation, if any.
This operation does not work correctly with multi-page images.
| Param | Type | Default |
| --- | --- | --- |
| [flip] | <code>Boolean</code> | <code>true</code> |
**Example**
```js
const output = await sharp(input).flip().toBuffer();
```
## flop
> flop([flop]) ⇒ <code>Sharp</code>
Mirror the image horizontally (left-right) about the y-axis.
This always occurs before rotation, if any.
| Param | Type | Default |
| --- | --- | --- |
| [flop] | <code>Boolean</code> | <code>true</code> |
**Example**
```js
const output = await sharp(input).flop().toBuffer();
```
## affine
> affine(matrix, [options]) ⇒ <code>Sharp</code>
Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.
You must provide an array of length 4 or a 2x2 affine transformation matrix.
By default, new pixels are filled with a black background. You can provide a background colour with the `background` option.
A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`.
In the case of a 2x2 matrix, the transform is:
- X = `matrix[0, 0]` \* (x + `idx`) + `matrix[0, 1]` \* (y + `idy`) + `odx`
- Y = `matrix[1, 0]` \* (x + `idx`) + `matrix[1, 1]` \* (y + `idy`) + `ody`
where:
- x and y are the coordinates in input image.
- X and Y are the coordinates in output image.
- (0,0) is the upper left corner.
**Throws**:
- <code>Error</code> Invalid parameters
**Since**: 0.27.0
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| matrix | <code>Array.&lt;Array.&lt;number&gt;&gt;</code> \| <code>Array.&lt;number&gt;</code> | | affine transformation matrix |
| [options] | <code>Object</code> | | if present, is an Object with optional attributes. |
| [options.background] | <code>String</code> \| <code>Object</code> | <code>&quot;#000000&quot;</code> | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |
| [options.idx] | <code>Number</code> | <code>0</code> | input horizontal offset |
| [options.idy] | <code>Number</code> | <code>0</code> | input vertical offset |
| [options.odx] | <code>Number</code> | <code>0</code> | output horizontal offset |
| [options.ody] | <code>Number</code> | <code>0</code> | output vertical offset |
| [options.interpolator] | <code>String</code> | <code>sharp.interpolators.bicubic</code> | interpolator |
**Example**
```js
const pipeline = sharp()
.affine([[1, 0.3], [0.1, 0.7]], {
background: 'white',
interpolator: sharp.interpolators.nohalo
})
.toBuffer((err, outputBuffer, info) => {
// outputBuffer contains the transformed image
// info.width and info.height contain the new dimensions
});
inputStream
.pipe(pipeline);
```
## sharpen
> sharpen([options], [flat], [jagged]) ⇒ <code>Sharp</code>
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.
Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available.
See [libvips sharpen](https://www.libvips.org/API/current/libvips-convolution.html#vips-sharpen) operation.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> \| <code>number</code> | | if present, is an Object with attributes |
| [options.sigma] | <code>number</code> | | the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`, between 0.000001 and 10 |
| [options.m1] | <code>number</code> | <code>1.0</code> | the level of sharpening to apply to "flat" areas, between 0 and 1000000 |
| [options.m2] | <code>number</code> | <code>2.0</code> | the level of sharpening to apply to "jagged" areas, between 0 and 1000000 |
| [options.x1] | <code>number</code> | <code>2.0</code> | threshold between "flat" and "jagged", between 0 and 1000000 |
| [options.y2] | <code>number</code> | <code>10.0</code> | maximum amount of brightening, between 0 and 1000000 |
| [options.y3] | <code>number</code> | <code>20.0</code> | maximum amount of darkening, between 0 and 1000000 |
| [flat] | <code>number</code> | | (deprecated) see `options.m1`. |
| [jagged] | <code>number</code> | | (deprecated) see `options.m2`. |
**Example**
```js
const data = await sharp(input).sharpen().toBuffer();
```
**Example**
```js
const data = await sharp(input).sharpen({ sigma: 2 }).toBuffer();
```
**Example**
```js
const data = await sharp(input)
.sharpen({
sigma: 2,
m1: 0,
m2: 3,
x1: 3,
y2: 15,
y3: 15,
})
.toBuffer();
```
## median
> median([size]) ⇒ <code>Sharp</code>
Apply median filter.
When used without parameters the default window is 3x3.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [size] | <code>number</code> | <code>3</code> | square mask size: size x size |
**Example**
```js
const output = await sharp(input).median().toBuffer();
```
**Example**
```js
const output = await sharp(input).median(5).toBuffer();
```
## blur
> blur([options]) ⇒ <code>Sharp</code>
Blur the image.
When used without parameters, performs a fast 3x3 box blur (equivalent to a box linear filter).
When a `sigma` is provided, performs a slower, more accurate Gaussian blur.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> \| <code>number</code> \| <code>Boolean</code> | | |
| [options.sigma] | <code>number</code> | | a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. |
| [options.precision] | <code>string</code> | <code>&quot;&#x27;integer&#x27;&quot;</code> | How accurate the operation should be, one of: integer, float, approximate. |
| [options.minAmplitude] | <code>number</code> | <code>0.2</code> | A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask. |
**Example**
```js
const boxBlurred = await sharp(input)
.blur()
.toBuffer();
```
**Example**
```js
const gaussianBlurred = await sharp(input)
.blur(5)
.toBuffer();
```
## dilate
> dilate([width]) ⇒ <code>Sharp</code>
Expand foreground objects using the dilate morphological operator.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [width] | <code>Number</code> | <code>1</code> | dilation width in pixels. |
**Example**
```js
const output = await sharp(input)
.dilate()
.toBuffer();
```
## erode
> erode([width]) ⇒ <code>Sharp</code>
Shrink foreground objects using the erode morphological operator.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [width] | <code>Number</code> | <code>1</code> | erosion width in pixels. |
**Example**
```js
const output = await sharp(input)
.erode()
.toBuffer();
```
## flatten
> flatten([options]) ⇒ <code>Sharp</code>
Merge alpha transparency channel, if any, with a background, then remove the alpha channel.
See also [removeAlpha](/api-channel#removealpha).
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> | | |
| [options.background] | <code>string</code> \| <code>Object</code> | <code>&quot;{r: 0, g: 0, b: 0}&quot;</code> | background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black. |
**Example**
```js
await sharp(rgbaInput)
.flatten({ background: '#F0A703' })
.toBuffer();
```
## unflatten
> unflatten()
Ensure the image has an alpha channel
with all white pixel values made fully transparent.
Existing alpha channel values for non-white pixels remain unchanged.
This feature is experimental and the API may change.
**Since**: 0.32.1
**Example**
```js
await sharp(rgbInput)
.unflatten()
.toBuffer();
```
**Example**
```js
await sharp(rgbInput)
.threshold(128, { grayscale: false }) // converter bright pixels to white
.unflatten()
.toBuffer();
```
## gamma
> gamma([gamma], [gammaOut]) ⇒ <code>Sharp</code>
Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of `1/gamma`
then increasing the encoding (brighten) post-resize at a factor of `gamma`.
This can improve the perceived brightness of a resized image in non-linear colour spaces.
JPEG and WebP input images will not take advantage of the shrink-on-load performance optimisation
when applying a gamma correction.
Supply a second argument to use a different output gamma value, otherwise the first value is used in both cases.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [gamma] | <code>number</code> | <code>2.2</code> | value between 1.0 and 3.0. |
| [gammaOut] | <code>number</code> | | value between 1.0 and 3.0. (optional, defaults to same as `gamma`) |
## negate
> negate([options]) ⇒ <code>Sharp</code>
Produce the "negative" of the image.
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> | | |
| [options.alpha] | <code>Boolean</code> | <code>true</code> | Whether or not to negate any alpha channel |
**Example**
```js
const output = await sharp(input)
.negate()
.toBuffer();
```
**Example**
```js
const output = await sharp(input)
.negate({ alpha: false })
.toBuffer();
```
## normalise
> normalise([options]) ⇒ <code>Sharp</code>
Enhance output image contrast by stretching its luminance to cover a full dynamic range.
Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes.
Luminance values below the `lower` percentile will be underexposed by clipping to zero.
Luminance values above the `upper` percentile will be overexposed by clipping to the max pixel value.
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> | | |
| [options.lower] | <code>number</code> | <code>1</code> | Percentile below which luminance values will be underexposed. |
| [options.upper] | <code>number</code> | <code>99</code> | Percentile above which luminance values will be overexposed. |
**Example**
```js
const output = await sharp(input)
.normalise()
.toBuffer();
```
**Example**
```js
const output = await sharp(input)
.normalise({ lower: 0, upper: 100 })
.toBuffer();
```
## normalize
> normalize([options]) ⇒ <code>Sharp</code>
Alternative spelling of normalise.
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> | | |
| [options.lower] | <code>number</code> | <code>1</code> | Percentile below which luminance values will be underexposed. |
| [options.upper] | <code>number</code> | <code>99</code> | Percentile above which luminance values will be overexposed. |
**Example**
```js
const output = await sharp(input)
.normalize()
.toBuffer();
```
## clahe
> clahe(options) ⇒ <code>Sharp</code>
Perform contrast limiting adaptive histogram equalization
[CLAHE](https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE).
This will, in general, enhance the clarity of the image by bringing out darker details.
**Throws**:
- <code>Error</code> Invalid parameters
**Since**: 0.28.3
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| options | <code>Object</code> | | |
| options.width | <code>number</code> | | Integral width of the search window, in pixels. |
| options.height | <code>number</code> | | Integral height of the search window, in pixels. |
| [options.maxSlope] | <code>number</code> | <code>3</code> | Integral level of brightening, between 0 and 100, where 0 disables contrast limiting. |
**Example**
```js
const output = await sharp(input)
.clahe({
width: 3,
height: 3,
})
.toBuffer();
```
## convolve
> convolve(kernel) ⇒ <code>Sharp</code>
Convolve the image with the specified kernel.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| kernel | <code>Object</code> | | |
| kernel.width | <code>number</code> | | width of the kernel in pixels. |
| kernel.height | <code>number</code> | | height of the kernel in pixels. |
| kernel.kernel | <code>Array.&lt;number&gt;</code> | | Array of length `width*height` containing the kernel values. |
| [kernel.scale] | <code>number</code> | <code>sum</code> | the scale of the kernel in pixels. |
| [kernel.offset] | <code>number</code> | <code>0</code> | the offset of the kernel in pixels. |
**Example**
```js
sharp(input)
.convolve({
width: 3,
height: 3,
kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1]
})
.raw()
.toBuffer(function(err, data, info) {
// data contains the raw pixel data representing the convolution
// of the input image with the horizontal Sobel operator
});
```
## threshold
> threshold([threshold], [options]) ⇒ <code>Sharp</code>
Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [threshold] | <code>number</code> | <code>128</code> | a value in the range 0-255 representing the level at which the threshold will be applied. |
| [options] | <code>Object</code> | | |
| [options.greyscale] | <code>Boolean</code> | <code>true</code> | convert to single channel greyscale. |
| [options.grayscale] | <code>Boolean</code> | <code>true</code> | alternative spelling for greyscale. |
## boolean
> boolean(operand, operator, [options]) ⇒ <code>Sharp</code>
Perform a bitwise boolean operation with operand image.
This operation creates an output image where each pixel is the result of
the selected bitwise boolean `operation` between the corresponding pixels of the input images.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Description |
| --- | --- | --- |
| operand | <code>Buffer</code> \| <code>string</code> | Buffer containing image data or string containing the path to an image file. |
| operator | <code>string</code> | one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. |
| [options] | <code>Object</code> | |
| [options.raw] | <code>Object</code> | describes operand when using raw pixel data. |
| [options.raw.width] | <code>number</code> | |
| [options.raw.height] | <code>number</code> | |
| [options.raw.channels] | <code>number</code> | |
## linear
> linear([a], [b]) ⇒ <code>Sharp</code>
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.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [a] | <code>number</code> \| <code>Array.&lt;number&gt;</code> | <code>[]</code> | multiplier |
| [b] | <code>number</code> \| <code>Array.&lt;number&gt;</code> | <code>[]</code> | offset |
**Example**
```js
await sharp(input)
.linear(0.5, 2)
.toBuffer();
```
**Example**
```js
await sharp(rgbInput)
.linear(
[0.25, 0.5, 0.75],
[150, 100, 50]
)
.toBuffer();
```
## recomb
> recomb(inputMatrix) ⇒ <code>Sharp</code>
Recombine the image with the specified matrix.
**Throws**:
- <code>Error</code> Invalid parameters
**Since**: 0.21.1
| Param | Type | Description |
| --- | --- | --- |
| inputMatrix | <code>Array.&lt;Array.&lt;number&gt;&gt;</code> | 3x3 or 4x4 Recombination matrix |
**Example**
```js
sharp(input)
.recomb([
[0.3588, 0.7044, 0.1368],
[0.2990, 0.5870, 0.1140],
[0.2392, 0.4696, 0.0912],
])
.raw()
.toBuffer(function(err, data, info) {
// data contains the raw pixel data after applying the matrix
// With this example input, a sepia filter has been applied
});
```
## modulate
> modulate([options]) ⇒ <code>Sharp</code>
Transforms the image using brightness, saturation, hue rotation, and lightness.
Brightness and lightness both operate on luminance, with the difference being that
brightness is multiplicative whereas lightness is additive.
**Since**: 0.22.1
| Param | Type | Description |
| --- | --- | --- |
| [options] | <code>Object</code> | |
| [options.brightness] | <code>number</code> | Brightness multiplier |
| [options.saturation] | <code>number</code> | Saturation multiplier |
| [options.hue] | <code>number</code> | Degrees for hue rotation |
| [options.lightness] | <code>number</code> | Lightness addend |
**Example**
```js
// increase brightness by a factor of 2
const output = await sharp(input)
.modulate({
brightness: 2
})
.toBuffer();
```
**Example**
```js
// hue-rotate by 180 degrees
const output = await sharp(input)
.modulate({
hue: 180
})
.toBuffer();
```
**Example**
```js
// increase lightness by +50
const output = await sharp(input)
.modulate({
lightness: 50
})
.toBuffer();
```
**Example**
```js
// decrease brightness and saturation while also hue-rotating by 90 degrees
const output = await sharp(input)
.modulate({
brightness: 0.5,
saturation: 0.5,
hue: 90,
})
.toBuffer();
```

View File

@ -0,0 +1,902 @@
---
# This file was auto-generated from JSDoc in lib/output.js
title: Output options
---
## toFile
> toFile(fileOut, [callback]) ⇒ <code>Promise.&lt;Object&gt;</code>
Write output image data to a file.
If an explicit output format is not selected, it will be inferred from the extension,
with JPEG, PNG, WebP, AVIF, TIFF, GIF, DZI, and libvips' V format supported.
Note that raw pixel data is only supported for buffer output.
By default all metadata will be removed, which includes EXIF-based orientation.
See [withMetadata](#withmetadata) for control over this.
The caller is responsible for ensuring directory structures and permissions exist.
A `Promise` is returned when `callback` is not provided.
**Returns**: <code>Promise.&lt;Object&gt;</code> - - when no callback is provided
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Description |
| --- | --- | --- |
| fileOut | <code>string</code> | the path to write the image data to. |
| [callback] | <code>function</code> | called on completion with two arguments `(err, info)`. `info` contains the output image `format`, `size` (bytes), `width`, `height`, `channels` and `premultiplied` (indicating if premultiplication was used). When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region. Animated output will also contain `pageHeight` and `pages`. May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. |
**Example**
```js
sharp(input)
.toFile('output.png', (err, info) => { ... });
```
**Example**
```js
sharp(input)
.toFile('output.png')
.then(info => { ... })
.catch(err => { ... });
```
## toBuffer
> toBuffer([options], [callback]) ⇒ <code>Promise.&lt;Buffer&gt;</code>
Write output to a Buffer.
JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.
Use [toFormat](#toformat) or one of the format-specific functions such as [jpeg](#jpeg), [png](#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.
By default all metadata will be removed, which includes EXIF-based orientation.
See [withMetadata](#withmetadata) for control over this.
`callback`, if present, gets three arguments `(err, data, info)` where:
- `err` is an error, if any.
- `data` is the output image data.
- `info` contains the output image `format`, `size` (bytes), `width`, `height`,
`channels` and `premultiplied` (indicating if premultiplication was used).
When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
Animated output will also contain `pageHeight` and `pages`.
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.
**Returns**: <code>Promise.&lt;Buffer&gt;</code> - - when no callback is provided
| Param | Type | Description |
| --- | --- | --- |
| [options] | <code>Object</code> | |
| [options.resolveWithObject] | <code>boolean</code> | Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`. |
| [callback] | <code>function</code> | |
**Example**
```js
sharp(input)
.toBuffer((err, data, info) => { ... });
```
**Example**
```js
sharp(input)
.toBuffer()
.then(data => { ... })
.catch(err => { ... });
```
**Example**
```js
sharp(input)
.png()
.toBuffer({ resolveWithObject: true })
.then(({ data, info }) => { ... })
.catch(err => { ... });
```
**Example**
```js
const { data, info } = await sharp('my-image.jpg')
// output the raw pixels
.raw()
.toBuffer({ resolveWithObject: true });
// create a more type safe way to work with the raw pixel data
// this will not copy the data, instead it will change `data`s underlying ArrayBuffer
// so `data` and `pixelArray` point to the same memory location
const pixelArray = new Uint8ClampedArray(data.buffer);
// When you are done changing the pixelArray, sharp takes the `pixelArray` as an input
const { width, height, channels } = info;
await sharp(pixelArray, { raw: { width, height, channels } })
.toFile('my-changed-image.jpg');
```
## keepExif
> keepExif() ⇒ <code>Sharp</code>
Keep all EXIF metadata from the input image in the output image.
EXIF metadata is unsupported for TIFF output.
**Since**: 0.33.0
**Example**
```js
const outputWithExif = await sharp(inputWithExif)
.keepExif()
.toBuffer();
```
## withExif
> withExif(exif) ⇒ <code>Sharp</code>
Set EXIF metadata in the output image, ignoring any EXIF in the input image.
**Throws**:
- <code>Error</code> Invalid parameters
**Since**: 0.33.0
| Param | Type | Description |
| --- | --- | --- |
| exif | <code>Object.&lt;string, Object.&lt;string, string&gt;&gt;</code> | Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. |
**Example**
```js
const dataWithExif = await sharp(input)
.withExif({
IFD0: {
Copyright: 'The National Gallery'
},
IFD3: {
GPSLatitudeRef: 'N',
GPSLatitude: '51/1 30/1 3230/100',
GPSLongitudeRef: 'W',
GPSLongitude: '0/1 7/1 4366/100'
}
})
.toBuffer();
```
## withExifMerge
> withExifMerge(exif) ⇒ <code>Sharp</code>
Update EXIF metadata from the input image in the output image.
**Throws**:
- <code>Error</code> Invalid parameters
**Since**: 0.33.0
| Param | Type | Description |
| --- | --- | --- |
| exif | <code>Object.&lt;string, Object.&lt;string, string&gt;&gt;</code> | Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. |
**Example**
```js
const dataWithMergedExif = await sharp(inputWithExif)
.withExifMerge({
IFD0: {
Copyright: 'The National Gallery'
}
})
.toBuffer();
```
## keepIccProfile
> keepIccProfile() ⇒ <code>Sharp</code>
Keep ICC profile from the input image in the output image.
Where necessary, will attempt to convert the output colour space to match the profile.
**Since**: 0.33.0
**Example**
```js
const outputWithIccProfile = await sharp(inputWithIccProfile)
.keepIccProfile()
.toBuffer();
```
## withIccProfile
> withIccProfile(icc, [options]) ⇒ <code>Sharp</code>
Transform using an ICC profile and attach to the output image.
This can either be an absolute filesystem path or
built-in profile name (`srgb`, `p3`, `cmyk`).
**Throws**:
- <code>Error</code> Invalid parameters
**Since**: 0.33.0
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| icc | <code>string</code> | | Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk). |
| [options] | <code>Object</code> | | |
| [options.attach] | <code>number</code> | <code>true</code> | Should the ICC profile be included in the output image metadata? |
**Example**
```js
const outputWithP3 = await sharp(input)
.withIccProfile('p3')
.toBuffer();
```
## keepXmp
> keepXmp() ⇒ <code>Sharp</code>
Keep XMP metadata from the input image in the output image.
**Since**: 0.34.3
**Example**
```js
const outputWithXmp = await sharp(inputWithXmp)
.keepXmp()
.toBuffer();
```
## withXmp
> withXmp(xmp) ⇒ <code>Sharp</code>
Set XMP metadata in the output image.
Supported by PNG, JPEG, WebP, and TIFF output.
**Throws**:
- <code>Error</code> Invalid parameters
**Since**: 0.34.3
| Param | Type | Description |
| --- | --- | --- |
| xmp | <code>string</code> | String containing XMP metadata to be embedded in the output image. |
**Example**
```js
const xmpString = `
<?xml version="1.0"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">
<dc:creator><rdf:Seq><rdf:li>John Doe</rdf:li></rdf:Seq></dc:creator>
</rdf:Description>
</rdf:RDF>
</x:xmpmeta>`;
const data = await sharp(input)
.withXmp(xmpString)
.toBuffer();
```
## keepMetadata
> keepMetadata() ⇒ <code>Sharp</code>
Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image.
The default behaviour, when `keepMetadata` is not used, is to convert to the device-independent
sRGB colour space and strip all metadata, including the removal of any ICC profile.
**Since**: 0.33.0
**Example**
```js
const outputWithMetadata = await sharp(inputWithMetadata)
.keepMetadata()
.toBuffer();
```
## withMetadata
> withMetadata([options]) ⇒ <code>Sharp</code>
Keep most metadata (EXIF, XMP, IPTC) from the input image in the output image.
This will also convert to and add a web-friendly sRGB ICC profile if appropriate.
Allows orientation and density to be set or updated.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Description |
| --- | --- | --- |
| [options] | <code>Object</code> | |
| [options.orientation] | <code>number</code> | Used to update the EXIF `Orientation` tag, integer between 1 and 8. |
| [options.density] | <code>number</code> | Number of pixels per inch (DPI). |
**Example**
```js
const outputSrgbWithMetadata = await sharp(inputRgbWithMetadata)
.withMetadata()
.toBuffer();
```
**Example**
```js
// Set output metadata to 96 DPI
const data = await sharp(input)
.withMetadata({ density: 96 })
.toBuffer();
```
## toFormat
> toFormat(format, options) ⇒ <code>Sharp</code>
Force output to a given format.
**Throws**:
- <code>Error</code> unsupported format or options
| Param | Type | Description |
| --- | --- | --- |
| format | <code>string</code> \| <code>Object</code> | as a string or an Object with an 'id' attribute |
| options | <code>Object</code> | output options |
**Example**
```js
// Convert any input to PNG output
const data = await sharp(input)
.toFormat('png')
.toBuffer();
```
## jpeg
> jpeg([options]) ⇒ <code>Sharp</code>
Use these JPEG options for output image.
**Throws**:
- <code>Error</code> Invalid options
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> | | output options |
| [options.quality] | <code>number</code> | <code>80</code> | quality, integer 1-100 |
| [options.progressive] | <code>boolean</code> | <code>false</code> | use progressive (interlace) scan |
| [options.chromaSubsampling] | <code>string</code> | <code>&quot;&#x27;4:2:0&#x27;&quot;</code> | set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling |
| [options.optimiseCoding] | <code>boolean</code> | <code>true</code> | optimise Huffman coding tables |
| [options.optimizeCoding] | <code>boolean</code> | <code>true</code> | alternative spelling of optimiseCoding |
| [options.mozjpeg] | <code>boolean</code> | <code>false</code> | use mozjpeg defaults, equivalent to `{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }` |
| [options.trellisQuantisation] | <code>boolean</code> | <code>false</code> | apply trellis quantisation |
| [options.overshootDeringing] | <code>boolean</code> | <code>false</code> | apply overshoot deringing |
| [options.optimiseScans] | <code>boolean</code> | <code>false</code> | optimise progressive scans, forces progressive |
| [options.optimizeScans] | <code>boolean</code> | <code>false</code> | alternative spelling of optimiseScans |
| [options.quantisationTable] | <code>number</code> | <code>0</code> | quantization table to use, integer 0-8 |
| [options.quantizationTable] | <code>number</code> | <code>0</code> | alternative spelling of quantisationTable |
| [options.force] | <code>boolean</code> | <code>true</code> | force JPEG output, otherwise attempt to use input format |
**Example**
```js
// Convert any input to very high quality JPEG output
const data = await sharp(input)
.jpeg({
quality: 100,
chromaSubsampling: '4:4:4'
})
.toBuffer();
```
**Example**
```js
// Use mozjpeg to reduce output JPEG file size (slower)
const data = await sharp(input)
.jpeg({ mozjpeg: true })
.toBuffer();
```
## png
> png([options]) ⇒ <code>Sharp</code>
Use these PNG options for output image.
By default, PNG output is full colour at 8 bits per pixel.
Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel.
Set `palette` to `true` for slower, indexed PNG output.
For 16 bits per pixel output, convert to `rgb16` via
[toColourspace](/api-colour#tocolourspace).
**Throws**:
- <code>Error</code> Invalid options
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> | | |
| [options.progressive] | <code>boolean</code> | <code>false</code> | use progressive (interlace) scan |
| [options.compressionLevel] | <code>number</code> | <code>6</code> | zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest) |
| [options.adaptiveFiltering] | <code>boolean</code> | <code>false</code> | use adaptive row filtering |
| [options.palette] | <code>boolean</code> | <code>false</code> | quantise to a palette-based image with alpha transparency support |
| [options.quality] | <code>number</code> | <code>100</code> | use the lowest number of colours needed to achieve given quality, sets `palette` to `true` |
| [options.effort] | <code>number</code> | <code>7</code> | CPU effort, between 1 (fastest) and 10 (slowest), sets `palette` to `true` |
| [options.colours] | <code>number</code> | <code>256</code> | maximum number of palette entries, sets `palette` to `true` |
| [options.colors] | <code>number</code> | <code>256</code> | alternative spelling of `options.colours`, sets `palette` to `true` |
| [options.dither] | <code>number</code> | <code>1.0</code> | level of Floyd-Steinberg error diffusion, sets `palette` to `true` |
| [options.force] | <code>boolean</code> | <code>true</code> | force PNG output, otherwise attempt to use input format |
**Example**
```js
// Convert any input to full colour PNG output
const data = await sharp(input)
.png()
.toBuffer();
```
**Example**
```js
// Convert any input to indexed PNG output (slower)
const data = await sharp(input)
.png({ palette: true })
.toBuffer();
```
**Example**
```js
// Output 16 bits per pixel RGB(A)
const data = await sharp(input)
.toColourspace('rgb16')
.png()
.toBuffer();
```
## webp
> webp([options]) ⇒ <code>Sharp</code>
Use these WebP options for output image.
**Throws**:
- <code>Error</code> Invalid options
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> | | output options |
| [options.quality] | <code>number</code> | <code>80</code> | quality, integer 1-100 |
| [options.alphaQuality] | <code>number</code> | <code>100</code> | quality of alpha layer, integer 0-100 |
| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression mode |
| [options.nearLossless] | <code>boolean</code> | <code>false</code> | use near_lossless compression mode |
| [options.smartSubsample] | <code>boolean</code> | <code>false</code> | use high quality chroma subsampling |
| [options.smartDeblock] | <code>boolean</code> | <code>false</code> | auto-adjust the deblocking filter, can improve low contrast edges (slow) |
| [options.preset] | <code>string</code> | <code>&quot;&#x27;default&#x27;&quot;</code> | named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text |
| [options.effort] | <code>number</code> | <code>4</code> | CPU effort, between 0 (fastest) and 6 (slowest) |
| [options.loop] | <code>number</code> | <code>0</code> | number of animation iterations, use 0 for infinite animation |
| [options.delay] | <code>number</code> \| <code>Array.&lt;number&gt;</code> | | delay(s) between animation frames (in milliseconds) |
| [options.minSize] | <code>boolean</code> | <code>false</code> | prevent use of animation key frames to minimise file size (slow) |
| [options.mixed] | <code>boolean</code> | <code>false</code> | allow mixture of lossy and lossless animation frames (slow) |
| [options.force] | <code>boolean</code> | <code>true</code> | force WebP output, otherwise attempt to use input format |
**Example**
```js
// Convert any input to lossless WebP output
const data = await sharp(input)
.webp({ lossless: true })
.toBuffer();
```
**Example**
```js
// Optimise the file size of an animated WebP
const outputWebp = await sharp(inputWebp, { animated: true })
.webp({ effort: 6 })
.toBuffer();
```
## gif
> gif([options]) ⇒ <code>Sharp</code>
Use these GIF options for the output image.
The first entry in the palette is reserved for transparency.
The palette of the input image will be re-used if possible.
**Throws**:
- <code>Error</code> Invalid options
**Since**: 0.30.0
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> | | output options |
| [options.reuse] | <code>boolean</code> | <code>true</code> | re-use existing palette, otherwise generate new (slow) |
| [options.progressive] | <code>boolean</code> | <code>false</code> | use progressive (interlace) scan |
| [options.colours] | <code>number</code> | <code>256</code> | maximum number of palette entries, including transparency, between 2 and 256 |
| [options.colors] | <code>number</code> | <code>256</code> | alternative spelling of `options.colours` |
| [options.effort] | <code>number</code> | <code>7</code> | CPU effort, between 1 (fastest) and 10 (slowest) |
| [options.dither] | <code>number</code> | <code>1.0</code> | level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) |
| [options.interFrameMaxError] | <code>number</code> | <code>0</code> | maximum inter-frame error for transparency, between 0 (lossless) and 32 |
| [options.interPaletteMaxError] | <code>number</code> | <code>3</code> | maximum inter-palette error for palette reuse, between 0 and 256 |
| [options.keepDuplicateFrames] | <code>boolean</code> | <code>false</code> | keep duplicate frames in the output instead of combining them |
| [options.loop] | <code>number</code> | <code>0</code> | number of animation iterations, use 0 for infinite animation |
| [options.delay] | <code>number</code> \| <code>Array.&lt;number&gt;</code> | | delay(s) between animation frames (in milliseconds) |
| [options.force] | <code>boolean</code> | <code>true</code> | force GIF output, otherwise attempt to use input format |
**Example**
```js
// Convert PNG to GIF
await sharp(pngBuffer)
.gif()
.toBuffer();
```
**Example**
```js
// Convert animated WebP to animated GIF
await sharp('animated.webp', { animated: true })
.toFile('animated.gif');
```
**Example**
```js
// Create a 128x128, cropped, non-dithered, animated thumbnail of an animated GIF
const out = await sharp('in.gif', { animated: true })
.resize({ width: 128, height: 128 })
.gif({ dither: 0 })
.toBuffer();
```
**Example**
```js
// Lossy file size reduction of animated GIF
await sharp('in.gif', { animated: true })
.gif({ interFrameMaxError: 8 })
.toFile('optim.gif');
```
## jp2
> jp2([options]) ⇒ <code>Sharp</code>
Use these JP2 options for output image.
Requires libvips compiled with support for OpenJPEG.
The prebuilt binaries do not include this - see
[installing a custom libvips](https://sharp.pixelplumbing.com/install#custom-libvips).
**Throws**:
- <code>Error</code> Invalid options
**Since**: 0.29.1
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> | | output options |
| [options.quality] | <code>number</code> | <code>80</code> | quality, integer 1-100 |
| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression mode |
| [options.tileWidth] | <code>number</code> | <code>512</code> | horizontal tile size |
| [options.tileHeight] | <code>number</code> | <code>512</code> | vertical tile size |
| [options.chromaSubsampling] | <code>string</code> | <code>&quot;&#x27;4:4:4&#x27;&quot;</code> | set to '4:2:0' to use chroma subsampling |
**Example**
```js
// Convert any input to lossless JP2 output
const data = await sharp(input)
.jp2({ lossless: true })
.toBuffer();
```
**Example**
```js
// Convert any input to very high quality JP2 output
const data = await sharp(input)
.jp2({
quality: 100,
chromaSubsampling: '4:4:4'
})
.toBuffer();
```
## tiff
> tiff([options]) ⇒ <code>Sharp</code>
Use these TIFF options for output image.
The `density` can be set in pixels/inch via [withMetadata](#withmetadata)
instead of providing `xres` and `yres` in pixels/mm.
**Throws**:
- <code>Error</code> Invalid options
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> | | output options |
| [options.quality] | <code>number</code> | <code>80</code> | quality, integer 1-100 |
| [options.force] | <code>boolean</code> | <code>true</code> | force TIFF output, otherwise attempt to use input format |
| [options.compression] | <code>string</code> | <code>&quot;&#x27;jpeg&#x27;&quot;</code> | compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k |
| [options.predictor] | <code>string</code> | <code>&quot;&#x27;horizontal&#x27;&quot;</code> | compression predictor options: none, horizontal, float |
| [options.pyramid] | <code>boolean</code> | <code>false</code> | write an image pyramid |
| [options.tile] | <code>boolean</code> | <code>false</code> | write a tiled tiff |
| [options.tileWidth] | <code>number</code> | <code>256</code> | horizontal tile size |
| [options.tileHeight] | <code>number</code> | <code>256</code> | vertical tile size |
| [options.xres] | <code>number</code> | <code>1.0</code> | horizontal resolution in pixels/mm |
| [options.yres] | <code>number</code> | <code>1.0</code> | vertical resolution in pixels/mm |
| [options.resolutionUnit] | <code>string</code> | <code>&quot;&#x27;inch&#x27;&quot;</code> | resolution unit options: inch, cm |
| [options.bitdepth] | <code>number</code> | <code>8</code> | reduce bitdepth to 1, 2 or 4 bit |
| [options.miniswhite] | <code>boolean</code> | <code>false</code> | write 1-bit images as miniswhite |
**Example**
```js
// Convert SVG input to LZW-compressed, 1 bit per pixel TIFF output
sharp('input.svg')
.tiff({
compression: 'lzw',
bitdepth: 1
})
.toFile('1-bpp-output.tiff')
.then(info => { ... });
```
## avif
> avif([options]) ⇒ <code>Sharp</code>
Use these AVIF options for output image.
AVIF image sequences are not supported.
Prebuilt binaries support a bitdepth of 8 only.
This feature is experimental on the Windows ARM64 platform
and requires a CPU with ARM64v8.4 or later.
**Throws**:
- <code>Error</code> Invalid options
**Since**: 0.27.0
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> | | output options |
| [options.quality] | <code>number</code> | <code>50</code> | quality, integer 1-100 |
| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression |
| [options.effort] | <code>number</code> | <code>4</code> | CPU effort, between 0 (fastest) and 9 (slowest) |
| [options.chromaSubsampling] | <code>string</code> | <code>&quot;&#x27;4:4:4&#x27;&quot;</code> | set to '4:2:0' to use chroma subsampling |
| [options.bitdepth] | <code>number</code> | <code>8</code> | set bitdepth to 8, 10 or 12 bit |
**Example**
```js
const data = await sharp(input)
.avif({ effort: 2 })
.toBuffer();
```
**Example**
```js
const data = await sharp(input)
.avif({ lossless: true })
.toBuffer();
```
## heif
> heif(options) ⇒ <code>Sharp</code>
Use these HEIF options for output image.
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.
**Throws**:
- <code>Error</code> Invalid options
**Since**: 0.23.0
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| options | <code>Object</code> | | output options |
| options.compression | <code>string</code> | | compression format: av1, hevc |
| [options.quality] | <code>number</code> | <code>50</code> | quality, integer 1-100 |
| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression |
| [options.effort] | <code>number</code> | <code>4</code> | CPU effort, between 0 (fastest) and 9 (slowest) |
| [options.chromaSubsampling] | <code>string</code> | <code>&quot;&#x27;4:4:4&#x27;&quot;</code> | set to '4:2:0' to use chroma subsampling |
| [options.bitdepth] | <code>number</code> | <code>8</code> | set bitdepth to 8, 10 or 12 bit |
**Example**
```js
const data = await sharp(input)
.heif({ compression: 'hevc' })
.toBuffer();
```
## jxl
> jxl([options]) ⇒ <code>Sharp</code>
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](https://sharp.pixelplumbing.com/install#custom-libvips).
**Throws**:
- <code>Error</code> Invalid options
**Since**: 0.31.3
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> | | output options |
| [options.distance] | <code>number</code> | <code>1.0</code> | maximum encoding error, between 0 (highest quality) and 15 (lowest quality) |
| [options.quality] | <code>number</code> | | calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified |
| [options.decodingTier] | <code>number</code> | <code>0</code> | target decode speed tier, between 0 (highest quality) and 4 (lowest quality) |
| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression |
| [options.effort] | <code>number</code> | <code>7</code> | CPU effort, between 1 (fastest) and 9 (slowest) |
| [options.loop] | <code>number</code> | <code>0</code> | number of animation iterations, use 0 for infinite animation |
| [options.delay] | <code>number</code> \| <code>Array.&lt;number&gt;</code> | | delay(s) between animation frames (in milliseconds) |
## raw
> raw([options]) ⇒ <code>Sharp</code>
Force output to be raw, uncompressed pixel data.
Pixel ordering is left-to-right, top-to-bottom, without padding.
Channel ordering will be RGB or RGBA for non-greyscale colourspaces.
**Throws**:
- <code>Error</code> Invalid options
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> | | output options |
| [options.depth] | <code>string</code> | <code>&quot;&#x27;uchar&#x27;&quot;</code> | bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex |
**Example**
```js
// Extract raw, unsigned 8-bit RGB pixel data from JPEG input
const { data, info } = await sharp('input.jpg')
.raw()
.toBuffer({ resolveWithObject: true });
```
**Example**
```js
// Extract alpha channel as raw, unsigned 16-bit pixel data from PNG input
const data = await sharp('input.png')
.ensureAlpha()
.extractChannel(3)
.toColourspace('b-w')
.raw({ depth: 'ushort' })
.toBuffer();
```
## tile
> tile([options]) ⇒ <code>Sharp</code>
Use tile-based deep zoom (image pyramid) output.
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.
The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> | | |
| [options.size] | <code>number</code> | <code>256</code> | tile size in pixels, a value between 1 and 8192. |
| [options.overlap] | <code>number</code> | <code>0</code> | tile overlap in pixels, a value between 0 and 8192. |
| [options.angle] | <code>number</code> | <code>0</code> | tile angle of rotation, must be a multiple of 90. |
| [options.background] | <code>string</code> \| <code>Object</code> | <code>&quot;{r: 255, g: 255, b: 255, alpha: 1}&quot;</code> | background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to white without transparency. |
| [options.depth] | <code>string</code> | | how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout. |
| [options.skipBlanks] | <code>number</code> | <code>-1</code> | Threshold to skip tile generation. Range is 0-255 for 8-bit images, 0-65535 for 16-bit images. Default is 5 for `google` layout, -1 (no skip) otherwise. |
| [options.container] | <code>string</code> | <code>&quot;&#x27;fs&#x27;&quot;</code> | tile container, with value `fs` (filesystem) or `zip` (compressed file). |
| [options.layout] | <code>string</code> | <code>&quot;&#x27;dz&#x27;&quot;</code> | filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`. |
| [options.centre] | <code>boolean</code> | <code>false</code> | centre image in tile. |
| [options.center] | <code>boolean</code> | <code>false</code> | alternative spelling of centre. |
| [options.id] | <code>string</code> | <code>&quot;&#x27;https://example.com/iiif&#x27;&quot;</code> | when `layout` is `iiif`/`iiif3`, sets the `@id`/`id` attribute of `info.json` |
| [options.basename] | <code>string</code> | | the name of the directory within the zip file when container is `zip`. |
**Example**
```js
sharp('input.tiff')
.png()
.tile({
size: 512
})
.toFile('output.dz', function(err, info) {
// output.dzi is the Deep Zoom XML definition
// output_files contains 512x512 tiles grouped by zoom level
});
```
**Example**
```js
const zipFileWithTiles = await sharp(input)
.tile({ basename: "tiles" })
.toBuffer();
```
**Example**
```js
const iiififier = sharp().tile({ layout: "iiif" });
readableStream
.pipe(iiififier)
.pipe(writeableStream);
```
## timeout
> timeout(options) ⇒ <code>Sharp</code>
Set a timeout for processing, in seconds.
Use a value of zero to continue processing indefinitely, the default behaviour.
The clock starts when libvips opens an input image for processing.
Time spent waiting for a libuv thread to become available is not included.
**Since**: 0.29.2
| Param | Type | Description |
| --- | --- | --- |
| options | <code>Object</code> | |
| options.seconds | <code>number</code> | Number of seconds after which processing will be stopped |
**Example**
```js
// 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')) { ... }
}
```

View File

@ -0,0 +1,323 @@
---
# This file was auto-generated from JSDoc in lib/resize.js
title: Resizing images
---
## resize
> resize([width], [height], [options]) ⇒ <code>Sharp</code>
Resize image to `width`, `height` or `width x height`.
When both a `width` and `height` are provided, the possible methods by which the image should **fit** these are:
- `cover`: (default) Preserving aspect ratio, attempt to ensure the image covers both provided dimensions by cropping/clipping to fit.
- `contain`: Preserving aspect ratio, contain within both provided dimensions using "letterboxing" where necessary.
- `fill`: Ignore the aspect ratio of the input and stretch to both provided dimensions.
- `inside`: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified.
- `outside`: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified.
Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property.
<img alt="Examples of various values for the fit property when resizing" width="100%" style="aspect-ratio: 998/243" src="/api-resize-fit.svg">
When using a **fit** of `cover` or `contain`, the default **position** is `centre`. Other options are:
- `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`.
- `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`.
- `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy.
Some of these values are based on the [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS property.
The strategy-based approach initially resizes so one dimension is at its target length
then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.
- `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29).
- `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
Possible downsizing kernels are:
- `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation).
- `linear`: Use a [triangle filter](https://en.wikipedia.org/wiki/Triangular_function).
- `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline).
- `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf).
- `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`.
- `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
- `mks2013`: Use a [Magic Kernel Sharp](https://johncostella.com/magic/mks.pdf) 2013 kernel, as adopted by Facebook.
- `mks2021`: Use a Magic Kernel Sharp 2021 kernel, with more accurate (reduced) sharpening than the 2013 version.
When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators.
Downsampling kernels without a matching upsampling interpolator map to `cubic`.
Only one resize can occur per pipeline.
Previous calls to `resize` in the same pipeline will be ignored.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [width] | <code>number</code> | | How many pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height. |
| [height] | <code>number</code> | | How many pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width. |
| [options] | <code>Object</code> | | |
| [options.width] | <code>number</code> | | An alternative means of specifying `width`. If both are present this takes priority. |
| [options.height] | <code>number</code> | | An alternative means of specifying `height`. If both are present this takes priority. |
| [options.fit] | <code>String</code> | <code>&#x27;cover&#x27;</code> | How the image should be resized/cropped to fit the target dimension(s), one of `cover`, `contain`, `fill`, `inside` or `outside`. |
| [options.position] | <code>String</code> | <code>&#x27;centre&#x27;</code> | A position, gravity or strategy to use when `fit` is `cover` or `contain`. |
| [options.background] | <code>String</code> \| <code>Object</code> | <code>{r: 0, g: 0, b: 0, alpha: 1}</code> | background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency. |
| [options.kernel] | <code>String</code> | <code>&#x27;lanczos3&#x27;</code> | The kernel to use for image reduction and the inferred interpolator to use for upsampling. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load. |
| [options.withoutEnlargement] | <code>Boolean</code> | <code>false</code> | Do not scale up if the width *or* height are already less than the target dimensions, equivalent to GraphicsMagick's `>` geometry option. This may result in output dimensions smaller than the target dimensions. |
| [options.withoutReduction] | <code>Boolean</code> | <code>false</code> | Do not scale down if the width *or* height are already greater than the target dimensions, equivalent to GraphicsMagick's `<` geometry option. This may still result in a crop to reach the target dimensions. |
| [options.fastShrinkOnLoad] | <code>Boolean</code> | <code>true</code> | Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern or round-down of an auto-scaled dimension. |
**Example**
```js
sharp(input)
.resize({ width: 100 })
.toBuffer()
.then(data => {
// 100 pixels wide, auto-scaled height
});
```
**Example**
```js
sharp(input)
.resize({ height: 100 })
.toBuffer()
.then(data => {
// 100 pixels high, auto-scaled width
});
```
**Example**
```js
sharp(input)
.resize(200, 300, {
kernel: sharp.kernel.nearest,
fit: 'contain',
position: 'right top',
background: { r: 255, g: 255, b: 255, alpha: 0.5 }
})
.toFile('output.png')
.then(() => {
// output.png is a 200 pixels wide and 300 pixels high image
// containing a nearest-neighbour scaled version
// contained within the north-east corner of a semi-transparent white canvas
});
```
**Example**
```js
const transformer = sharp()
.resize({
width: 200,
height: 200,
fit: sharp.fit.cover,
position: sharp.strategy.entropy
});
// Read image data from readableStream
// Write 200px square auto-cropped image data to writableStream
readableStream
.pipe(transformer)
.pipe(writableStream);
```
**Example**
```js
sharp(input)
.resize(200, 200, {
fit: sharp.fit.inside,
withoutEnlargement: true
})
.toFormat('jpeg')
.toBuffer()
.then(function(outputBuffer) {
// outputBuffer contains JPEG image data
// no wider and no higher than 200 pixels
// and no larger than the input image
});
```
**Example**
```js
sharp(input)
.resize(200, 200, {
fit: sharp.fit.outside,
withoutReduction: true
})
.toFormat('jpeg')
.toBuffer()
.then(function(outputBuffer) {
// outputBuffer contains JPEG image data
// of at least 200 pixels wide and 200 pixels high while maintaining aspect ratio
// and no smaller than the input image
});
```
**Example**
```js
const scaleByHalf = await sharp(input)
.metadata()
.then(({ width }) => sharp(input)
.resize(Math.round(width * 0.5))
.toBuffer()
);
```
## extend
> extend(extend) ⇒ <code>Sharp</code>
Extend / pad / extrude one or more edges of the image with either
the provided background colour or pixels derived from the image.
This operation will always occur after resizing and extraction, if any.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| extend | <code>number</code> \| <code>Object</code> | | single pixel count to add to all edges or an Object with per-edge counts |
| [extend.top] | <code>number</code> | <code>0</code> | |
| [extend.left] | <code>number</code> | <code>0</code> | |
| [extend.bottom] | <code>number</code> | <code>0</code> | |
| [extend.right] | <code>number</code> | <code>0</code> | |
| [extend.extendWith] | <code>String</code> | <code>&#x27;background&#x27;</code> | populate new pixels using this method, one of: background, copy, repeat, mirror. |
| [extend.background] | <code>String</code> \| <code>Object</code> | <code>{r: 0, g: 0, b: 0, alpha: 1}</code> | background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency. |
**Example**
```js
// Resize to 140 pixels wide, then add 10 transparent pixels
// to the top, left and right edges and 20 to the bottom edge
sharp(input)
.resize(140)
.extend({
top: 10,
bottom: 20,
left: 10,
right: 10,
background: { r: 0, g: 0, b: 0, alpha: 0 }
})
...
```
**Example**
```js
// Add a row of 10 red pixels to the bottom
sharp(input)
.extend({
bottom: 10,
background: 'red'
})
...
```
**Example**
```js
// Extrude image by 8 pixels to the right, mirroring existing right hand edge
sharp(input)
.extend({
right: 8,
background: 'mirror'
})
...
```
## extract
> extract(options) ⇒ <code>Sharp</code>
Extract/crop a region of the image.
- Use `extract` before `resize` for pre-resize extraction.
- Use `extract` after `resize` for post-resize extraction.
- Use `extract` twice and `resize` once for extract-then-resize-then-extract in a fixed operation order.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Description |
| --- | --- | --- |
| options | <code>Object</code> | describes the region to extract using integral pixel values |
| options.left | <code>number</code> | zero-indexed offset from left edge |
| options.top | <code>number</code> | zero-indexed offset from top edge |
| options.width | <code>number</code> | width of region to extract |
| options.height | <code>number</code> | height of region to extract |
**Example**
```js
sharp(input)
.extract({ left: left, top: top, width: width, height: height })
.toFile(output, function(err) {
// Extract a region of the input image, saving in the same format.
});
```
**Example**
```js
sharp(input)
.extract({ left: leftOffsetPre, top: topOffsetPre, width: widthPre, height: heightPre })
.resize(width, height)
.extract({ left: leftOffsetPost, top: topOffsetPost, width: widthPost, height: heightPost })
.toFile(output, function(err) {
// Extract a region, resize, then extract from the resized image
});
```
## trim
> trim([options]) ⇒ <code>Sharp</code>
Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.
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 will contain `trimOffsetLeft` and `trimOffsetTop` properties.
**Throws**:
- <code>Error</code> Invalid parameters
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> | | |
| [options.background] | <code>string</code> \| <code>Object</code> | <code>&quot;&#x27;top-left pixel&#x27;&quot;</code> | Background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel. |
| [options.threshold] | <code>number</code> | <code>10</code> | Allowed difference from the above colour, a positive number. |
| [options.lineArt] | <code>boolean</code> | <code>false</code> | Does the input more closely resemble line art (e.g. vector) rather than being photographic? |
**Example**
```js
// Trim pixels with a colour similar to that of the top-left pixel.
await sharp(input)
.trim()
.toFile(output);
```
**Example**
```js
// Trim pixels with the exact same colour as that of the top-left pixel.
await sharp(input)
.trim({
threshold: 0
})
.toFile(output);
```
**Example**
```js
// Assume input is line art and trim only pixels with a similar colour to red.
const output = await sharp(input)
.trim({
background: "#FF0000",
lineArt: true
})
.toBuffer();
```
**Example**
```js
// Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
const output = await sharp(input)
.trim({
background: "yellow",
threshold: 42,
})
.toBuffer();
```

View File

@ -0,0 +1,232 @@
---
# This file was auto-generated from JSDoc in lib/utility.js
title: Global properties
---
## versions
> versions
An Object containing the version numbers of sharp, libvips
and (when using prebuilt binaries) its dependencies.
**Example**
```js
console.log(sharp.versions);
```
## interpolators
> interpolators : <code>enum</code>
An Object containing the available interpolators and their proper values
**Read only**: true
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| nearest | <code>string</code> | <code>&quot;nearest&quot;</code> | [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. |
| bilinear | <code>string</code> | <code>&quot;bilinear&quot;</code> | [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. |
| bicubic | <code>string</code> | <code>&quot;bicubic&quot;</code> | [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). |
| locallyBoundedBicubic | <code>string</code> | <code>&quot;lbb&quot;</code> | [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. |
| nohalo | <code>string</code> | <code>&quot;nohalo&quot;</code> | [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. |
| vertexSplitQuadraticBasisSpline | <code>string</code> | <code>&quot;vsqbs&quot;</code> | [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents "staircasing" when enlarging. |
## format
> format ⇒ <code>Object</code>
An Object containing nested boolean values representing the available input and output formats/methods.
**Example**
```js
console.log(sharp.format);
```
## queue
> queue
An EventEmitter that emits a `change` event when a task is either:
- queued, waiting for _libuv_ to provide a worker thread
- complete
**Example**
```js
sharp.queue.on('change', function(queueLength) {
console.log('Queue contains ' + queueLength + ' task(s)');
});
```
## cache
> cache([options]) ⇒ <code>Object</code>
Gets or, when options are provided, sets the limits of _libvips'_ operation cache.
Existing entries in the cache will be trimmed after any change in limits.
This method always returns cache statistics,
useful for determining how much working memory is required for a particular task.
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> \| <code>boolean</code> | <code>true</code> | Object with the following attributes, or boolean where true uses default cache settings and false removes all caching |
| [options.memory] | <code>number</code> | <code>50</code> | is the maximum memory in MB to use for this cache |
| [options.files] | <code>number</code> | <code>20</code> | is the maximum number of files to hold open |
| [options.items] | <code>number</code> | <code>100</code> | is the maximum number of operations to cache |
**Example**
```js
const stats = sharp.cache();
```
**Example**
```js
sharp.cache( { items: 200 } );
sharp.cache( { files: 0 } );
sharp.cache(false);
```
## concurrency
> concurrency([concurrency]) ⇒ <code>number</code>
Gets or, when a concurrency is provided, sets
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,
except when using glibc-based Linux without jemalloc,
where the default is `1` to help reduce memory fragmentation.
A value of `0` will reset this to the number of CPU cores.
Some image format libraries spawn additional threads,
e.g. libaom manages its own 4 threads when encoding AVIF images,
and these are independent of the value set here.
:::note
Further [control over performance](/performance) is available.
:::
**Returns**: <code>number</code> - concurrency
| Param | Type |
| --- | --- |
| [concurrency] | <code>number</code> |
**Example**
```js
const threads = sharp.concurrency(); // 4
sharp.concurrency(2); // 2
sharp.concurrency(0); // 4
```
## counters
> counters() ⇒ <code>Object</code>
Provides access to internal task counters.
- queue is the number of tasks this module has queued waiting for _libuv_ to provide a worker thread from its pool.
- process is the number of resize tasks currently being processed.
**Example**
```js
const counters = sharp.counters(); // { queue: 2, process: 4 }
```
## simd
> simd([simd]) ⇒ <code>boolean</code>
Get and set use of SIMD vector unit instructions.
Requires libvips to have been compiled with highway support.
Improves the performance of `resize`, `blur` and `sharpen` operations
by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.
| Param | Type | Default |
| --- | --- | --- |
| [simd] | <code>boolean</code> | <code>true</code> |
**Example**
```js
const simd = sharp.simd();
// simd is `true` if the runtime use of highway is currently enabled
```
**Example**
```js
const simd = sharp.simd(false);
// prevent libvips from using highway at runtime
```
## block
> block(options)
Block libvips operations at runtime.
This is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable,
which when set will block all "untrusted" operations.
**Since**: 0.32.4
| Param | Type | Description |
| --- | --- | --- |
| options | <code>Object</code> | |
| options.operation | <code>Array.&lt;string&gt;</code> | List of libvips low-level operation names to block. |
**Example** *(Block all TIFF input.)*
```js
sharp.block({
operation: ['VipsForeignLoadTiff']
});
```
## unblock
> unblock(options)
Unblock libvips operations at runtime.
This is useful for defining a list of allowed operations.
**Since**: 0.32.4
| Param | Type | Description |
| --- | --- | --- |
| options | <code>Object</code> | |
| options.operation | <code>Array.&lt;string&gt;</code> | List of libvips low-level operation names to unblock. |
**Example** *(Block all input except WebP from the filesystem.)*
```js
sharp.block({
operation: ['VipsForeignLoad']
});
sharp.unblock({
operation: ['VipsForeignLoadWebpFile']
});
```
**Example** *(Block all input except JPEG and PNG from a Buffer or Stream.)*
```js
sharp.block({
operation: ['VipsForeignLoad']
});
sharp.unblock({
operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer']
});
```

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,98 @@
---
title: "High performance Node.js image processing"
---
<img src="/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right">
The typical use case for this high speed Node-API module
is to convert large images in common formats to
smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions.
It can be used with all JavaScript runtimes
that provide support for Node-API v9, including
Node.js >= 18.17.0, Deno and Bun.
Resizing an image is typically 4x-5x faster than using the
quickest ImageMagick and GraphicsMagick settings
due to its use of [libvips](https://github.com/libvips/libvips).
Colour spaces, embedded ICC profiles and alpha transparency channels are all handled correctly.
Lanczos resampling ensures quality is not sacrificed for speed.
As well as image resizing, operations such as
rotation, extraction, compositing and gamma correction are available.
Most modern macOS, Windows and Linux systems
do not require any additional install or runtime dependencies.
```sh
npm install sharp
```
## Formats
This module supports reading JPEG, PNG, WebP, GIF, AVIF, TIFF and SVG images.
Output images can be in JPEG, PNG, WebP, GIF, AVIF and TIFF formats as well as uncompressed raw pixel data.
Streams, Buffer objects and the filesystem can be used for input and output.
A single input Stream can be split into multiple processing pipelines and output Streams.
Deep Zoom image pyramids can be generated,
suitable for use with "slippy map" tile viewers like
[OpenSeadragon](https://github.com/openseadragon/openseadragon).
## Fast
This module is powered by the blazingly fast
[libvips](https://github.com/libvips/libvips) image processing library,
originally created in 1989 at Birkbeck College
and currently maintained by a small team led by
[John Cupitt](https://github.com/jcupitt).
Only small regions of uncompressed image data
are held in memory and processed at a time,
taking full advantage of multiple CPU cores and L1/L2/L3 cache.
Everything remains non-blocking thanks to _libuv_,
no child processes are spawned and Promises/async/await are supported.
## Optimal
The features of `mozjpeg` and `pngquant` can be used
to optimise the file size of JPEG and PNG images respectively,
without having to invoke separate `imagemin` processes.
Huffman tables are optimised when generating JPEG output images
without having to use separate command line tools like
[jpegoptim](https://github.com/tjko/jpegoptim) and
[jpegtran](http://jpegclub.org/jpegtran/).
PNG filtering is disabled by default,
which for diagrams and line art often produces the same result
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
A [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md)
covers reporting bugs, requesting features and submitting code changes.
## Licensing
Copyright 2013 Lovell Fuller and others.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,357 @@
---
title: Installation
---
Works with your choice of JavaScript package manager.
:::caution
Please ensure your package manager is configured to install optional dependencies
:::
If a package manager lockfile must support multiple platforms,
please see the [cross-platform](#cross-platform) section
to help decide which package manager is appropriate.
```sh
npm install sharp
```
```sh
pnpm add sharp
```
When using `pnpm`, you may need to add `sharp` to
[ignoredBuiltDependencies](https://pnpm.io/settings#ignoredbuiltdependencies)
to silence warnings.
```sh
yarn add sharp
```
```sh
bun add sharp
```
```sh
deno run --allow-ffi ...
```
## Prerequisites
* Node-API v9 compatible runtime e.g. Node.js ^18.17.0 or >=20.3.0.
## Prebuilt binaries
Ready-compiled sharp and libvips binaries are provided for use on the most common platforms:
* macOS x64 (>= 10.15)
* macOS ARM64
* Linux ARM (glibc >= 2.31)
* Linux ARM64 (glibc >= 2.26, musl >= 1.2.2)
* Linux ppc64 (glibc >= 2.31)
* Linux s390x (glibc >= 2.31)
* Linux x64 (glibc >= 2.26, musl >= 1.2.2, CPU with SSE4.2)
* Windows x64
* Windows x86
* Windows ARM64 (experimental, CPU with ARMv8.4 required for all features)
This provides support for the
JPEG, PNG, WebP, AVIF (limited to 8-bit depth), TIFF, GIF and SVG (input) image formats.
## Cross-platform
At install time, package managers will automatically select prebuilt binaries
for the current OS platform and CPU architecture, where available.
Some package managers support multiple platforms and architectures
within the same installation tree and/or using the same lockfile.
### npm v10+
:::caution
npm `package-lock.json` files shared by multiple platforms can cause installation problems due to [npm bug #4828](https://github.com/npm/cli/issues/4828)
:::
Provides limited support via `--os`, `--cpu` and `--libc` flags.
To support macOS with Intel x64 and ARM64 CPUs:
```sh
npm install --cpu=x64 --os=darwin sharp
npm install --cpu=arm64 --os=darwin sharp
```
When the cross-target is Linux, the C standard library must be specified.
To support glibc (e.g. Debian) and musl (e.g. Alpine) Linux with Intel x64 CPUs:
```sh
npm install --cpu=x64 --os=linux --libc=glibc sharp
npm install --cpu=x64 --os=linux --libc=musl sharp
```
### yarn v3+
Use the [supportedArchitectures](https://yarnpkg.com/configuration/yarnrc#supportedArchitectures) configuration.
### pnpm v8+
Use the [supportedArchitectures](https://pnpm.io/settings#supportedarchitectures) configuration.
## Custom libvips
To use a custom, globally-installed version of libvips instead of the provided binaries,
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`.
For help compiling libvips and its dependencies, please see
[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
and on macOS when running Node.js under Rosetta.
## Building from source
This module will be compiled from source at `npm install` time when:
* a globally-installed libvips is detected, or
* when the `npm install --build-from-source` flag is used.
The logic to detect a globally-installed libvips can be skipped by setting the
`SHARP_IGNORE_GLOBAL_LIBVIPS` (never try to use it) or
`SHARP_FORCE_GLOBAL_LIBVIPS` (always try to use it, even when missing or outdated)
environment variables.
Building from source requires:
* C++17 compiler
* [node-addon-api](https://www.npmjs.com/package/node-addon-api) version 7+
* [node-gyp](https://github.com/nodejs/node-gyp#installation) version 9+ and its dependencies
There is an install-time check for these dependencies.
If `node-addon-api` or `node-gyp` cannot be found, try adding them via:
```sh
npm install --save node-addon-api node-gyp
```
When using `pnpm`, you may need to add `sharp` to
[onlyBuiltDependencies](https://pnpm.io/settings#onlybuiltdependencies)
to ensure the installation script can be run.
For cross-compiling, the `--platform`, `--arch` and `--libc` npm flags
(or the `npm_config_platform`, `npm_config_arch` and `npm_config_libc` environment variables)
can be used to configure the target environment.
## WebAssembly
Experimental support is provided for runtime environments that provide
multi-threaded Wasm via Workers.
Use in web browsers is unsupported.
Native text rendering is unsupported.
[Tile-based output](/api-output#tile) is unsupported.
```sh
npm install --cpu=wasm32 sharp
```
## FreeBSD
The `vips` package must be installed before `npm install` is run.
```sh
pkg install -y pkgconf vips
```
```sh
cd /usr/ports/graphics/vips/ && make install clean
```
## Linux memory allocator
The default memory allocator on most glibc-based Linux systems
(e.g. Debian, Red Hat) is unsuitable for long-running, multi-threaded
processes that involve lots of small memory allocations.
For this reason, by default, sharp will limit the use of thread-based
[concurrency](/api-utility#concurrency) when the glibc allocator is
detected at runtime.
To help avoid fragmentation and improve performance on these systems,
the use of an alternative memory allocator such as
[jemalloc](https://github.com/jemalloc/jemalloc) is recommended.
Those using musl-based Linux (e.g. Alpine) and non-Linux systems are
unaffected.
## AWS Lambda
The `node_modules` directory of the
[deployment package](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-package.html)
must include binaries for either the linux-x64 or linux-arm64 platforms
depending on the chosen architecture.
When building your deployment package on a machine that differs from the target architecture,
see the [cross-platform](#cross-platform) section to help decide which package manager is appropriate
and how to configure it.
Some package managers use symbolic links
but AWS Lambda does not support these within deployment packages.
To get the best performance select the largest memory available.
A 1536 MB function provides ~12x more CPU time than a 128 MB function.
When integrating with AWS API Gateway, ensure it is configured with the relevant
[binary media types](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings.html).
## Bundlers
### webpack
Ensure sharp is excluded from bundling via the
[externals](https://webpack.js.org/configuration/externals/)
configuration.
```js
externals: {
'sharp': 'commonjs sharp'
}
```
### 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 --os=linux --cpu=x64 sharp
```
### electron
#### electron-builder
Ensure `sharp` is unpacked from the ASAR archive file using the
[asarUnpack](https://www.electron.build/app-builder-lib.interface.platformspecificbuildoptions#asarunpack)
option.
```json
{
"build": {
"asar": true,
"asarUnpack": [
"**/node_modules/sharp/**/*",
"**/node_modules/@img/**/*"
]
}
}
```
#### electron-forge
Ensure `sharp` is unpacked from the ASAR archive file using the
[unpack](https://js.electronforge.io/interfaces/_electron_forge_maker_squirrel.InternalOptions.Options.html#asar)
option.
```json
{
"packagerConfig": {
"asar": {
"unpack": "**/node_modules/{sharp,@img}/**/*"
}
}
}
```
When using `electron-forge` with [Webpack](#webpack),
you may also need to add
[forge-externals-plugin](https://www.npmjs.com/package/@timfish/forge-externals-plugin).
### vite
Ensure `sharp` is excluded from bundling via the
[build.rollupOptions](https://vitejs.dev/config/build-options.html)
configuration.
```js
import { defineConfig } from 'vite';
export default defineConfig({
build: {
rollupOptions: {
external: [
"sharp"
]
}
}
});
```
## TypeScript
TypeScript definitions are published as part of
the `sharp` package from v0.32.0.
Previously these were available via the `@types/sharp` package,
which is now deprecated.
When using Typescript, please ensure `devDependencies` includes
the `@types/node` package.
## 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.
## Known conflicts
### Canvas and Windows
If both `canvas` and `sharp` modules are used in the same Windows process, the following error may occur:
```
The specified procedure could not be found.
```

View File

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

View File

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

5
docs/tsconfig.json Normal file
View File

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

View File

@ -1,13 +0,0 @@
var sharp = require("./build/Release/sharp");
module.exports.crop = function(input, output, width, height, callback) {
sharp.resize(input, output, width, height, "c", callback)
}
module.exports.embedWhite = function(input, output, width, height, callback) {
sharp.resize(input, output, width, height, "w", callback)
}
module.exports.embedBlack = function(input, output, width, height, callback) {
sharp.resize(input, output, width, height, "b", callback)
}

41
install/check.js Normal file
View File

@ -0,0 +1,41 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
try {
const { useGlobalLibvips, globalLibvipsVersion, log, spawnRebuild } = require('../lib/libvips');
const buildFromSource = (msg) => {
log(msg);
log('Attempting to build from source via node-gyp');
try {
const addonApi = require('node-addon-api');
log(`Found node-addon-api ${addonApi.version || ''}`);
} catch (err) {
log('Please add node-addon-api to your dependencies');
return;
}
try {
const gyp = require('node-gyp');
log(`Found node-gyp ${gyp().version}`);
} catch (err) {
log('Please add node-gyp to your dependencies');
return;
}
log('See https://sharp.pixelplumbing.com/install#building-from-source');
const status = spawnRebuild();
if (status !== 0) {
process.exit(status);
}
};
if (useGlobalLibvips(log)) {
buildFromSource(`Detected globally-installed libvips v${globalLibvipsVersion()}`);
} else if (process.env.npm_config_build_from_source) {
buildFromSource('Detected --build-from-source flag');
}
} catch (err) {
const summary = err.message.split(/\n/).slice(0, 1);
console.log(`sharp: skipping install check: ${summary}`);
}

175
lib/channel.js Normal file
View File

@ -0,0 +1,175 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
const is = require('./is');
/**
* Boolean operations for bandbool.
* @private
*/
const bool = {
and: 'and',
or: 'or',
eor: 'eor'
};
/**
* Remove alpha channels, if any. This is a no-op if the image does not have an alpha channel.
*
* See also {@link /api-operation#flatten|flatten}.
*
* @example
* sharp('rgba.png')
* .removeAlpha()
* .toFile('rgb.png', function(err, info) {
* // rgb.png is a 3 channel image without an alpha channel
* });
*
* @returns {Sharp}
*/
function removeAlpha () {
this.options.removeAlpha = true;
return this;
}
/**
* Ensure the output image has an alpha transparency channel.
* If missing, the added alpha channel will have the specified
* transparency level, defaulting to fully-opaque (1).
* This is a no-op if the image already has an alpha channel.
*
* @since 0.21.2
*
* @example
* // rgba.png will be a 4 channel image with a fully-opaque alpha channel
* await sharp('rgb.jpg')
* .ensureAlpha()
* .toFile('rgba.png')
*
* @example
* // rgba is a 4 channel image with a fully-transparent alpha channel
* const rgba = await sharp(rgb)
* .ensureAlpha(0)
* .toBuffer();
*
* @param {number} [alpha=1] - alpha transparency level (0=fully-transparent, 1=fully-opaque)
* @returns {Sharp}
* @throws {Error} Invalid alpha transparency level
*/
function ensureAlpha (alpha) {
if (is.defined(alpha)) {
if (is.number(alpha) && is.inRange(alpha, 0, 1)) {
this.options.ensureAlpha = alpha;
} else {
throw is.invalidParameterError('alpha', 'number between 0 and 1', alpha);
}
} else {
this.options.ensureAlpha = 1;
}
return this;
}
/**
* Extract a single channel from a multi-channel image.
*
* @example
* // green.jpg is a greyscale image containing the green channel of the input
* await sharp(input)
* .extractChannel('green')
* .toFile('green.jpg');
*
* @example
* // red1 is the red value of the first pixel, red2 the second pixel etc.
* const [red1, red2, ...] = await sharp(input)
* .extractChannel(0)
* .raw()
* .toBuffer();
*
* @param {number|string} channel - zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`.
* @returns {Sharp}
* @throws {Error} Invalid channel
*/
function extractChannel (channel) {
const channelMap = { red: 0, green: 1, blue: 2, alpha: 3 };
if (Object.keys(channelMap).includes(channel)) {
channel = channelMap[channel];
}
if (is.integer(channel) && is.inRange(channel, 0, 4)) {
this.options.extractChannel = channel;
} else {
throw is.invalidParameterError('channel', 'integer or one of: red, green, blue, alpha', channel);
}
return this;
}
/**
* Join one or more channels to the image.
* The meaning of the added channels depends on the output colourspace, set with `toColourspace()`.
* By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.
* Channel ordering follows vips convention:
* - sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha.
* - CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha.
*
* Buffers may be any of the image formats supported by sharp.
* For raw pixel input, the `options` object should contain a `raw` attribute, which follows the format of the attribute of the same name in the `sharp()` constructor.
*
* @param {Array<string|Buffer>|string|Buffer} images - one or more images (file paths, Buffers).
* @param {Object} options - image options, see `sharp()` constructor.
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
function joinChannel (images, options) {
if (Array.isArray(images)) {
images.forEach(function (image) {
this.options.joinChannelIn.push(this._createInputDescriptor(image, options));
}, this);
} else {
this.options.joinChannelIn.push(this._createInputDescriptor(images, options));
}
return this;
}
/**
* Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image.
*
* @example
* sharp('3-channel-rgb-input.png')
* .bandbool(sharp.bool.and)
* .toFile('1-channel-output.png', function (err, info) {
* // The output will be a single channel image where each pixel `P = R & G & B`.
* // If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]`
* // then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`.
* });
*
* @param {string} boolOp - one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
function bandbool (boolOp) {
if (is.string(boolOp) && is.inArray(boolOp, ['and', 'or', 'eor'])) {
this.options.bandBoolOp = boolOp;
} else {
throw is.invalidParameterError('boolOp', 'one of: and, or, eor', boolOp);
}
return this;
}
/**
* Decorate the Sharp prototype with channel-related functions.
* @module Sharp
* @private
*/
module.exports = function (Sharp) {
Object.assign(Sharp.prototype, {
// Public instance functions
removeAlpha,
ensureAlpha,
extractChannel,
joinChannel,
bandbool
});
// Class attributes
Sharp.bool = bool;
};

192
lib/colour.js Normal file
View File

@ -0,0 +1,192 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
const color = require('color');
const is = require('./is');
/**
* Colourspaces.
* @private
*/
const colourspace = {
multiband: 'multiband',
'b-w': 'b-w',
bw: 'b-w',
cmyk: 'cmyk',
srgb: 'srgb'
};
/**
* Tint the image using the provided colour.
* 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} tint - Parsed by the [color](https://www.npmjs.org/package/color) module.
* @returns {Sharp}
* @throws {Error} Invalid parameter
*/
function tint (tint) {
this._setBackgroundColourOption('tint', tint);
return this;
}
/**
* Convert to 8-bit greyscale; 256 shades of grey.
* This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results.
* By default the output image will be web-friendly sRGB and contain three (identical) colour channels.
* This may be overridden by other sharp operations such as `toColourspace('b-w')`,
* which will produce an output image containing one colour channel.
* 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]
* @returns {Sharp}
*/
function greyscale (greyscale) {
this.options.greyscale = is.bool(greyscale) ? greyscale : true;
return this;
}
/**
* Alternative spelling of `greyscale`.
* @param {Boolean} [grayscale=true]
* @returns {Sharp}
*/
function grayscale (grayscale) {
return this.greyscale(grayscale);
}
/**
* Set the pipeline colourspace.
*
* The input image will be converted to the provided colourspace at the start of the pipeline.
* All operations will use this colourspace before converting to the output colourspace,
* as defined by {@link #tocolourspace|toColourspace}.
*
* @since 0.29.0
*
* @example
* // Run pipeline in 16 bits per channel RGB while converting final result to 8 bits per channel sRGB.
* await sharp(input)
* .pipelineColourspace('rgb16')
* .toColourspace('srgb')
* .toFile('16bpc-pipeline-to-8bpc-output.png')
*
* @param {string} [colourspace] - pipeline colourspace e.g. `rgb16`, `scrgb`, `lab`, `grey16` [...](https://github.com/libvips/libvips/blob/41cff4e9d0838498487a00623462204eb10ee5b8/libvips/iofuncs/enumtypes.c#L774)
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
function pipelineColourspace (colourspace) {
if (!is.string(colourspace)) {
throw is.invalidParameterError('colourspace', 'string', colourspace);
}
this.options.colourspacePipeline = colourspace;
return this;
}
/**
* Alternative spelling of `pipelineColourspace`.
* @param {string} [colorspace] - pipeline colorspace.
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
function pipelineColorspace (colorspace) {
return this.pipelineColourspace(colorspace);
}
/**
* Set the output colourspace.
* By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.
*
* @example
* // Output 16 bits per pixel RGB
* await sharp(input)
* .toColourspace('rgb16')
* .toFile('16-bpp.png')
*
* @param {string} [colourspace] - output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/libvips/libvips/blob/3c0bfdf74ce1dc37a6429bed47fa76f16e2cd70a/libvips/iofuncs/enumtypes.c#L777-L794)
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
function toColourspace (colourspace) {
if (!is.string(colourspace)) {
throw is.invalidParameterError('colourspace', 'string', colourspace);
}
this.options.colourspace = colourspace;
return this;
}
/**
* Alternative spelling of `toColourspace`.
* @param {string} [colorspace] - output colorspace.
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
function toColorspace (colorspace) {
return this.toColourspace(colorspace);
}
/**
* Create a RGBA colour array from a given value.
* @private
* @param {string|Object} value
* @throws {Error} Invalid value
*/
function _getBackgroundColourOption (value) {
if (is.object(value) || is.string(value)) {
const colour = color(value);
return [
colour.red(),
colour.green(),
colour.blue(),
Math.round(colour.alpha() * 255)
];
} else {
throw is.invalidParameterError('background', 'object or string', value);
}
}
/**
* Update a colour attribute of the this.options Object.
* @private
* @param {string} key
* @param {string|Object} value
* @throws {Error} Invalid value
*/
function _setBackgroundColourOption (key, value) {
if (is.defined(value)) {
this.options[key] = _getBackgroundColourOption(value);
}
}
/**
* Decorate the Sharp prototype with colour-related functions.
* @module Sharp
* @private
*/
module.exports = function (Sharp) {
Object.assign(Sharp.prototype, {
// Public
tint,
greyscale,
grayscale,
pipelineColourspace,
pipelineColorspace,
toColourspace,
toColorspace,
// Private
_getBackgroundColourOption,
_setBackgroundColourOption
});
// Class attributes
Sharp.colourspace = colourspace;
Sharp.colorspace = colourspace;
};

212
lib/composite.js Normal file
View File

@ -0,0 +1,212 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
const is = require('./is');
/**
* Blend modes.
* @member
* @private
*/
const blend = {
clear: 'clear',
source: 'source',
over: 'over',
in: 'in',
out: 'out',
atop: 'atop',
dest: 'dest',
'dest-over': 'dest-over',
'dest-in': 'dest-in',
'dest-out': 'dest-out',
'dest-atop': 'dest-atop',
xor: 'xor',
add: 'add',
saturate: 'saturate',
multiply: 'multiply',
screen: 'screen',
overlay: 'overlay',
darken: 'darken',
lighten: 'lighten',
'colour-dodge': 'colour-dodge',
'color-dodge': 'colour-dodge',
'colour-burn': 'colour-burn',
'color-burn': 'colour-burn',
'hard-light': 'hard-light',
'soft-light': 'soft-light',
difference: 'difference',
exclusion: 'exclusion'
};
/**
* 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.
* If both `top` and `left` options are provided, they take precedence over `gravity`.
*
* Other operations in the same processing pipeline (e.g. resize, rotate, flip,
* flop, extract) will always be applied to the input image before composition.
*
* The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`,
* `dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`,
* `xor`, `add`, `saturate`, `multiply`, `screen`, `overlay`, `darken`, `lighten`,
* `colour-dodge`, `color-dodge`, `colour-burn`,`color-burn`,
* `hard-light`, `soft-light`, `difference`, `exclusion`.
*
* More information about blend modes can be found at
* https://www.libvips.org/API/current/libvips-conversion.html#VipsBlendMode
* and https://www.cairographics.org/operators/
*
* @since 0.22.0
*
* @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')
* .rotate(180)
* .resize(300)
* .flatten( { background: '#ff6600' } )
* .composite([{ input: 'overlay.png', gravity: 'southeast' }])
* .sharpen()
* .withMetadata()
* .webp( { quality: 90 } )
* .toBuffer()
* .then(function(outputBuffer) {
* // outputBuffer contains upside down, 300px wide, alpha channel flattened
* // onto orange background, composited with overlay.png with SE gravity,
* // sharpened, with metadata, 90% quality WebP image data. Phew!
* });
*
* @param {Object[]} images - Ordered list of images to composite
* @param {Buffer|String} [images[].input] - Buffer containing image data, String containing the path to an image file, or Create object (see below)
* @param {Object} [images[].input.create] - describes a blank overlay to be created.
* @param {Number} [images[].input.create.width]
* @param {Number} [images[].input.create.height]
* @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 {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 {Boolean} [images[].autoOrient=false] - set to true to use EXIF orientation data, if present, to orient the image.
* @param {String} [images[].blend='over'] - how to blend this image with the image below.
* @param {String} [images[].gravity='centre'] - gravity at which to place the overlay.
* @param {Number} [images[].top] - the pixel offset from the top edge.
* @param {Number} [images[].left] - the pixel offset from the left edge.
* @param {Boolean} [images[].tile=false] - set to true to repeat the overlay image across the entire image with the given `gravity`.
* @param {Boolean} [images[].premultiplied=false] - set to true to avoid premultiplying the image below. Equivalent to the `--premultiplied` vips option.
* @param {Number} [images[].density=72] - number representing the DPI for vector overlay image.
* @param {Object} [images[].raw] - describes overlay when using raw pixel data.
* @param {Number} [images[].raw.width]
* @param {Number} [images[].raw.height]
* @param {Number} [images[].raw.channels]
* @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}
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
function composite (images) {
if (!Array.isArray(images)) {
throw is.invalidParameterError('images to composite', 'array', images);
}
this.options.composite = images.map(image => {
if (!is.object(image)) {
throw is.invalidParameterError('image to composite', 'object', image);
}
const inputOptions = this._inputOptionsFromObject(image);
const composite = {
input: this._createInputDescriptor(image.input, inputOptions, { allowStream: false }),
blend: 'over',
tile: false,
left: 0,
top: 0,
hasOffset: false,
gravity: 0,
premultiplied: false
};
if (is.defined(image.blend)) {
if (is.string(blend[image.blend])) {
composite.blend = blend[image.blend];
} else {
throw is.invalidParameterError('blend', 'valid blend name', image.blend);
}
}
if (is.defined(image.tile)) {
if (is.bool(image.tile)) {
composite.tile = image.tile;
} else {
throw is.invalidParameterError('tile', 'boolean', image.tile);
}
}
if (is.defined(image.left)) {
if (is.integer(image.left)) {
composite.left = image.left;
} else {
throw is.invalidParameterError('left', 'integer', image.left);
}
}
if (is.defined(image.top)) {
if (is.integer(image.top)) {
composite.top = image.top;
} else {
throw is.invalidParameterError('top', 'integer', image.top);
}
}
if (is.defined(image.top) !== is.defined(image.left)) {
throw new Error('Expected both left and top to be set');
} else {
composite.hasOffset = is.integer(image.top) && is.integer(image.left);
}
if (is.defined(image.gravity)) {
if (is.integer(image.gravity) && is.inRange(image.gravity, 0, 8)) {
composite.gravity = image.gravity;
} else if (is.string(image.gravity) && is.integer(this.constructor.gravity[image.gravity])) {
composite.gravity = this.constructor.gravity[image.gravity];
} else {
throw is.invalidParameterError('gravity', 'valid gravity', image.gravity);
}
}
if (is.defined(image.premultiplied)) {
if (is.bool(image.premultiplied)) {
composite.premultiplied = image.premultiplied;
} else {
throw is.invalidParameterError('premultiplied', 'boolean', image.premultiplied);
}
}
return composite;
});
return this;
}
/**
* Decorate the Sharp prototype with composite-related functions.
* @module Sharp
* @private
*/
module.exports = function (Sharp) {
Sharp.prototype.composite = composite;
Sharp.blend = blend;
};

494
lib/constructor.js Normal file
View File

@ -0,0 +1,494 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
const util = require('node:util');
const stream = require('node:stream');
const is = require('./is');
require('./sharp');
// Use NODE_DEBUG=sharp to enable libvips warnings
const debuglog = util.debuglog('sharp');
/**
* Constructor factory to create an instance of `sharp`, to which further methods are chained.
*
* JPEG, PNG, WebP, GIF, AVIF or TIFF format image data can be streamed out from this object.
* When using Stream based output, derived attributes are available from the `info` event.
*
* Non-critical problems encountered during processing are emitted as `warning` events.
*
* Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.
*
* When loading more than one page/frame of an animated image,
* these are combined as a vertically-stacked "toilet roll" image
* where the overall height is the `pageHeight` multiplied by the number of `pages`.
*
* @constructs Sharp
*
* @emits Sharp#info
* @emits Sharp#warning
*
* @example
* sharp('input.jpg')
* .resize(300, 200)
* .toFile('output.jpg', function(err) {
* // output.jpg is a 300 pixels wide and 200 pixels high image
* // containing a scaled and cropped version of input.jpg
* });
*
* @example
* // Read image data from remote URL,
* // resize to 300 pixels wide,
* // emit an 'info' event with calculated dimensions
* // and finally write image data to writableStream
* const { body } = fetch('https://...');
* const readableStream = Readable.fromWeb(body);
* const transformer = sharp()
* .resize(300)
* .on('info', ({ height }) => {
* console.log(`Image height is ${height}`);
* });
* readableStream.pipe(transformer).pipe(writableStream);
*
* @example
* // Create a blank 300x200 PNG image of semi-translucent red pixels
* sharp({
* create: {
* width: 300,
* height: 200,
* channels: 4,
* background: { r: 255, g: 0, b: 0, alpha: 0.5 }
* }
* })
* .png()
* .toBuffer()
* .then( ... );
*
* @example
* // Convert an animated GIF to an animated WebP
* await sharp('in.gif', { animated: true }).toFile('out.webp');
*
* @example
* // Read a raw array of pixels and save it to a png
* const input = Uint8Array.from([255, 255, 255, 0, 0, 0]); // or Uint8ClampedArray
* const image = sharp(input, {
* // because the input does not contain its dimensions or how many channels it has
* // we need to specify it in the constructor options
* raw: {
* width: 2,
* height: 1,
* channels: 3
* }
* });
* await image.toFile('my-two-pixels.png');
*
* @example
* // Generate RGB Gaussian noise
* await sharp({
* create: {
* width: 300,
* height: 200,
* channels: 3,
* noise: {
* type: 'gaussian',
* mean: 128,
* sigma: 30
* }
* }
* }).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');
*
* @example
* // Join four input images as a 2x2 grid with a 4 pixel gutter
* const data = await sharp(
* [image1, image2, image3, image4],
* { join: { across: 2, shim: 4 } }
* ).toBuffer();
*
* @example
* // Generate a two-frame animated image from emoji
* const images = ['😀', '😛'].map(text => ({
* text: { text, width: 64, height: 64, channels: 4, rgba: true }
* }));
* await sharp(images, { join: { animated: true } }).toFile('out.gif');
*
* @param {(Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string|Array)} [input] - if present, can be
* a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or
* a TypedArray containing raw pixel image data, or
* a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file.
* An array of inputs can be provided, and these will be joined together.
* JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present.
* @param {Object} [options] - if present, is an Object with optional attributes.
* @param {string} [options.failOn='warning'] - When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort.
* @param {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.
* An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF).
* @param {boolean} [options.unlimited=false] - Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF).
* @param {boolean} [options.autoOrient=false] - Set this to `true` to rotate/flip the image to match EXIF `Orientation`, if any.
* @param {boolean} [options.sequentialRead=true] - Set this to `false` to use random access rather than sequential read. Some operations will do this automatically.
* @param {number} [options.density=72] - number representing the DPI for vector images in the range 1 to 100000.
* @param {number} [options.ignoreIcc=false] - should the embedded ICC profile, if any, be ignored.
* @param {number} [options.pages=1] - Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages.
* @param {number} [options.page=0] - Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based.
* @param {boolean} [options.animated=false] - Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`.
* @param {Object} [options.raw] - describes raw pixel input image data. See `raw()` for pixel ordering.
* @param {number} [options.raw.width] - integral number of pixels wide.
* @param {number} [options.raw.height] - integral number of pixels high.
* @param {number} [options.raw.channels] - integral number of channels, between 1 and 4.
* @param {boolean} [options.raw.premultiplied] - specifies that the raw input has already been premultiplied, set to `true`
* to avoid sharp premultiplying the image. (optional, default `false`)
* @param {number} [options.raw.pageHeight] - The pixel height of each page/frame for animated images, must be an integral factor of `raw.height`.
* @param {Object} [options.create] - describes a new image to be created.
* @param {number} [options.create.width] - integral number of pixels wide.
* @param {number} [options.create.height] - integral number of pixels high.
* @param {number} [options.create.channels] - integral number of channels, either 3 (RGB) or 4 (RGBA).
* @param {string|Object} [options.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
* @param {number} [options.create.pageHeight] - The pixel height of each page/frame for animated images, must be an integral factor of `create.height`.
* @param {Object} [options.create.noise] - describes a noise to be created.
* @param {string} [options.create.noise.type] - type of generated noise, currently only `gaussian` is supported.
* @param {number} [options.create.noise.mean=128] - Mean value of pixels in the generated noise.
* @param {number} [options.create.noise.sigma=30] - Standard deviation of pixel values in the generated noise.
* @param {Object} [options.text] - describes a new text image to be created.
* @param {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] - Maximum 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'] - Alignment style for multi-line text (`'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.
* @param {string} [options.text.wrap='word'] - word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'.
* @param {Object} [options.join] - describes how an array of input images should be joined.
* @param {number} [options.join.across=1] - number of images to join horizontally.
* @param {boolean} [options.join.animated=false] - set this to `true` to join the images as an animated image.
* @param {number} [options.join.shim=0] - number of pixels to insert between joined images.
* @param {string|Object} [options.join.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
* @param {string} [options.join.halign='left'] - horizontal alignment style for images joined horizontally (`'left'`, `'centre'`, `'center'`, `'right'`).
* @param {string} [options.join.valign='top'] - vertical alignment style for images joined vertically (`'top'`, `'centre'`, `'center'`, `'bottom'`).
* @param {Object} [options.tiff] - Describes TIFF specific options.
* @param {number} [options.tiff.subifd=-1] - Sub Image File Directory to extract for OME-TIFF, defaults to main image.
* @param {Object} [options.svg] - Describes SVG specific options.
* @param {string} [options.svg.stylesheet] - Custom CSS for SVG input, applied with a User Origin during the CSS cascade.
* @param {boolean} [options.svg.highBitdepth=false] - Set to `true` to render SVG input at 32-bits per channel (128-bit) instead of 8-bits per channel (32-bit) RGBA.
* @param {Object} [options.pdf] - Describes PDF specific options. Requires the use of a globally-installed libvips compiled with support for PDFium, Poppler, ImageMagick or GraphicsMagick.
* @param {string|Object} [options.pdf.background] - Background colour to use when PDF is partially transparent. Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
* @param {Object} [options.openSlide] - Describes OpenSlide specific options. Requires the use of a globally-installed libvips compiled with support for OpenSlide.
* @param {number} [options.openSlide.level=0] - Level to extract from a multi-level input, zero based.
* @param {Object} [options.jp2] - Describes JPEG 2000 specific options. Requires the use of a globally-installed libvips compiled with support for OpenJPEG.
* @param {boolean} [options.jp2.oneshot=false] - Set to `true` to decode tiled JPEG 2000 images in a single operation, improving compatibility.
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
const Sharp = function (input, options) {
if (arguments.length === 1 && !is.defined(input)) {
throw new Error('Invalid input');
}
if (!(this instanceof Sharp)) {
return new Sharp(input, options);
}
stream.Duplex.call(this);
this.options = {
// resize options
topOffsetPre: -1,
leftOffsetPre: -1,
widthPre: -1,
heightPre: -1,
topOffsetPost: -1,
leftOffsetPost: -1,
widthPost: -1,
heightPost: -1,
width: -1,
height: -1,
canvas: 'crop',
position: 0,
resizeBackground: [0, 0, 0, 255],
angle: 0,
rotationAngle: 0,
rotationBackground: [0, 0, 0, 255],
rotateBeforePreExtract: false,
flip: false,
flop: false,
extendTop: 0,
extendBottom: 0,
extendLeft: 0,
extendRight: 0,
extendBackground: [0, 0, 0, 255],
extendWith: 'background',
withoutEnlargement: false,
withoutReduction: false,
affineMatrix: [],
affineBackground: [0, 0, 0, 255],
affineIdx: 0,
affineIdy: 0,
affineOdx: 0,
affineOdy: 0,
affineInterpolator: this.constructor.interpolators.bilinear,
kernel: 'lanczos3',
fastShrinkOnLoad: true,
// operations
tint: [-1, 0, 0, 0],
flatten: false,
flattenBackground: [0, 0, 0],
unflatten: false,
negate: false,
negateAlpha: true,
medianSize: 0,
blurSigma: 0,
precision: 'integer',
minAmpl: 0.2,
sharpenSigma: 0,
sharpenM1: 1,
sharpenM2: 2,
sharpenX1: 2,
sharpenY2: 10,
sharpenY3: 20,
threshold: 0,
thresholdGrayscale: true,
trimBackground: [],
trimThreshold: -1,
trimLineArt: false,
dilateWidth: 0,
erodeWidth: 0,
gamma: 0,
gammaOut: 0,
greyscale: false,
normalise: false,
normaliseLower: 1,
normaliseUpper: 99,
claheWidth: 0,
claheHeight: 0,
claheMaxSlope: 3,
brightness: 1,
saturation: 1,
hue: 0,
lightness: 0,
booleanBufferIn: null,
booleanFileIn: '',
joinChannelIn: [],
extractChannel: -1,
removeAlpha: false,
ensureAlpha: -1,
colourspace: 'srgb',
colourspacePipeline: 'last',
composite: [],
// output
fileOut: '',
formatOut: 'input',
streamOut: false,
keepMetadata: 0,
withMetadataOrientation: -1,
withMetadataDensity: 0,
withIccProfile: '',
withExif: {},
withExifMerge: true,
withXmp: '',
resolveWithObject: false,
loop: -1,
delay: [],
// output format
jpegQuality: 80,
jpegProgressive: false,
jpegChromaSubsampling: '4:2:0',
jpegTrellisQuantisation: false,
jpegOvershootDeringing: false,
jpegOptimiseScans: false,
jpegOptimiseCoding: true,
jpegQuantisationTable: 0,
pngProgressive: false,
pngCompressionLevel: 6,
pngAdaptiveFiltering: false,
pngPalette: false,
pngQuality: 100,
pngEffort: 7,
pngBitdepth: 8,
pngDither: 1,
jp2Quality: 80,
jp2TileHeight: 512,
jp2TileWidth: 512,
jp2Lossless: false,
jp2ChromaSubsampling: '4:4:4',
webpQuality: 80,
webpAlphaQuality: 100,
webpLossless: false,
webpNearLossless: false,
webpSmartSubsample: false,
webpSmartDeblock: false,
webpPreset: 'default',
webpEffort: 4,
webpMinSize: false,
webpMixed: false,
gifBitdepth: 8,
gifEffort: 7,
gifDither: 1,
gifInterFrameMaxError: 0,
gifInterPaletteMaxError: 3,
gifKeepDuplicateFrames: false,
gifReuse: true,
gifProgressive: false,
tiffQuality: 80,
tiffCompression: 'jpeg',
tiffPredictor: 'horizontal',
tiffPyramid: false,
tiffMiniswhite: false,
tiffBitdepth: 8,
tiffTile: false,
tiffTileHeight: 256,
tiffTileWidth: 256,
tiffXres: 1.0,
tiffYres: 1.0,
tiffResolutionUnit: 'inch',
heifQuality: 50,
heifLossless: false,
heifCompression: 'av1',
heifEffort: 4,
heifChromaSubsampling: '4:4:4',
heifBitdepth: 8,
jxlDistance: 1,
jxlDecodingTier: 0,
jxlEffort: 7,
jxlLossless: false,
rawDepth: 'uchar',
tileSize: 256,
tileOverlap: 0,
tileContainer: 'fs',
tileLayout: 'dz',
tileFormat: 'last',
tileDepth: 'last',
tileAngle: 0,
tileSkipBlanks: -1,
tileBackground: [255, 255, 255, 255],
tileCentre: false,
tileId: 'https://example.com/iiif',
tileBasename: '',
timeoutSeconds: 0,
linearA: [],
linearB: [],
pdfBackground: [255, 255, 255, 255],
// Function to notify of libvips warnings
debuglog: warning => {
this.emit('warning', warning);
debuglog(warning);
},
// Function to notify of queue length changes
queueListener: function (queueLength) {
Sharp.queue.emit('change', queueLength);
}
};
this.options.input = this._createInputDescriptor(input, options, { allowStream: true });
return this;
};
Object.setPrototypeOf(Sharp.prototype, stream.Duplex.prototype);
Object.setPrototypeOf(Sharp, stream.Duplex);
/**
* Take a "snapshot" of the Sharp instance, returning a new instance.
* Cloned instances inherit the input of their parent instance.
* This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream.
*
* @example
* const pipeline = sharp().rotate();
* pipeline.clone().resize(800, 600).pipe(firstWritableStream);
* pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 }).pipe(secondWritableStream);
* readableStream.pipe(pipeline);
* // firstWritableStream receives auto-rotated, resized readableStream
* // secondWritableStream receives auto-rotated, extracted region of readableStream
*
* @example
* // Create a pipeline that will download an image, resize it and format it to different files
* // Using Promises to know when the pipeline is complete
* const fs = require("fs");
* const got = require("got");
* const sharpStream = sharp({ failOn: 'none' });
*
* const promises = [];
*
* promises.push(
* sharpStream
* .clone()
* .jpeg({ quality: 100 })
* .toFile("originalFile.jpg")
* );
*
* promises.push(
* sharpStream
* .clone()
* .resize({ width: 500 })
* .jpeg({ quality: 80 })
* .toFile("optimized-500.jpg")
* );
*
* promises.push(
* sharpStream
* .clone()
* .resize({ width: 500 })
* .webp({ quality: 80 })
* .toFile("optimized-500.webp")
* );
*
* // https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md
* got.stream("https://www.example.com/some-file.jpg").pipe(sharpStream);
*
* Promise.all(promises)
* .then(res => { console.log("Done!", res); })
* .catch(err => {
* console.error("Error processing files, let's clean it up", err);
* try {
* fs.unlinkSync("originalFile.jpg");
* fs.unlinkSync("optimized-500.jpg");
* fs.unlinkSync("optimized-500.webp");
* } catch (e) {}
* });
*
* @returns {Sharp}
*/
function clone () {
// Clone existing options
const clone = this.constructor.call();
const { debuglog, queueListener, ...options } = this.options;
clone.options = structuredClone(options);
clone.options.debuglog = debuglog;
clone.options.queueListener = queueListener;
// Pass 'finish' event to clone for Stream-based input
if (this._isStreamInput()) {
this.on('finish', () => {
// Clone inherits input data
this._flattenBufferIn();
clone.options.input.buffer = this.options.input.buffer;
clone.emit('finish');
});
}
return clone;
}
Object.assign(Sharp.prototype, { clone });
/**
* Export constructor.
* @module Sharp
* @private
*/
module.exports = Sharp;

1963
lib/index.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

16
lib/index.js Normal file
View File

@ -0,0 +1,16 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
const Sharp = require('./constructor');
require('./input')(Sharp);
require('./resize')(Sharp);
require('./composite')(Sharp);
require('./operation')(Sharp);
require('./colour')(Sharp);
require('./channel')(Sharp);
require('./output')(Sharp);
require('./utility')(Sharp);
module.exports = Sharp;

811
lib/input.js Normal file
View File

@ -0,0 +1,811 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
const is = require('./is');
const sharp = require('./sharp');
/**
* Justification alignment
* @member
* @private
*/
const align = {
left: 'low',
top: 'low',
low: 'low',
center: 'centre',
centre: 'centre',
right: 'high',
bottom: 'high',
high: 'high'
};
const inputStreamParameters = [
// Limits and error handling
'failOn', 'limitInputPixels', 'unlimited',
// Format-generic
'animated', 'autoOrient', 'density', 'ignoreIcc', 'page', 'pages', 'sequentialRead',
// Format-specific
'jp2', 'openSlide', 'pdf', 'raw', 'svg', 'tiff',
// Deprecated
'failOnError', 'openSlideLevel', 'pdfBackground', 'tiffSubifd'
];
/**
* Extract input options, if any, from an object.
* @private
*/
function _inputOptionsFromObject (obj) {
const params = inputStreamParameters
.filter(p => is.defined(obj[p]))
.map(p => ([p, obj[p]]));
return params.length
? Object.fromEntries(params)
: undefined;
}
/**
* Create Object containing input and input-related options.
* @private
*/
function _createInputDescriptor (input, inputOptions, containerOptions) {
const inputDescriptor = {
autoOrient: false,
failOn: 'warning',
limitInputPixels: Math.pow(0x3FFF, 2),
ignoreIcc: false,
unlimited: false,
sequentialRead: true
};
if (is.string(input)) {
// filesystem
inputDescriptor.file = input;
} else if (is.buffer(input)) {
// Buffer
if (input.length === 0) {
throw Error('Input Buffer is empty');
}
inputDescriptor.buffer = input;
} else if (is.arrayBuffer(input)) {
if (input.byteLength === 0) {
throw Error('Input bit Array is empty');
}
inputDescriptor.buffer = Buffer.from(input, 0, input.byteLength);
} else if (is.typedArray(input)) {
if (input.length === 0) {
throw Error('Input Bit Array is empty');
}
inputDescriptor.buffer = Buffer.from(input.buffer, input.byteOffset, input.byteLength);
} else if (is.plainObject(input) && !is.defined(inputOptions)) {
// Plain Object descriptor, e.g. create
inputOptions = input;
if (_inputOptionsFromObject(inputOptions)) {
// Stream with options
inputDescriptor.buffer = [];
}
} else if (!is.defined(input) && !is.defined(inputOptions) && is.object(containerOptions) && containerOptions.allowStream) {
// Stream without options
inputDescriptor.buffer = [];
} else if (Array.isArray(input)) {
if (input.length > 1) {
// Join images together
if (!this.options.joining) {
this.options.joining = true;
this.options.join = input.map(i => this._createInputDescriptor(i));
} else {
throw new Error('Recursive join is unsupported');
}
} else {
throw new Error('Expected at least two images to join');
}
} else {
throw new Error(`Unsupported input '${input}' of type ${typeof input}${
is.defined(inputOptions) ? ` when also providing options of type ${typeof inputOptions}` : ''
}`);
}
if (is.object(inputOptions)) {
// Deprecated: failOnError
if (is.defined(inputOptions.failOnError)) {
if (is.bool(inputOptions.failOnError)) {
inputDescriptor.failOn = inputOptions.failOnError ? 'warning' : 'none';
} else {
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);
}
}
// autoOrient
if (is.defined(inputOptions.autoOrient)) {
if (is.bool(inputOptions.autoOrient)) {
inputDescriptor.autoOrient = inputOptions.autoOrient;
} else {
throw is.invalidParameterError('autoOrient', 'boolean', inputOptions.autoOrient);
}
}
// Density
if (is.defined(inputOptions.density)) {
if (is.inRange(inputOptions.density, 1, 100000)) {
inputDescriptor.density = inputOptions.density;
} else {
throw is.invalidParameterError('density', 'number between 1 and 100000', inputOptions.density);
}
}
// Ignore embeddded ICC profile
if (is.defined(inputOptions.ignoreIcc)) {
if (is.bool(inputOptions.ignoreIcc)) {
inputDescriptor.ignoreIcc = inputOptions.ignoreIcc;
} else {
throw is.invalidParameterError('ignoreIcc', 'boolean', inputOptions.ignoreIcc);
}
}
// limitInputPixels
if (is.defined(inputOptions.limitInputPixels)) {
if (is.bool(inputOptions.limitInputPixels)) {
inputDescriptor.limitInputPixels = inputOptions.limitInputPixels
? Math.pow(0x3FFF, 2)
: 0;
} else if (is.integer(inputOptions.limitInputPixels) && is.inRange(inputOptions.limitInputPixels, 0, Number.MAX_SAFE_INTEGER)) {
inputDescriptor.limitInputPixels = inputOptions.limitInputPixels;
} else {
throw is.invalidParameterError('limitInputPixels', 'positive integer', inputOptions.limitInputPixels);
}
}
// unlimited
if (is.defined(inputOptions.unlimited)) {
if (is.bool(inputOptions.unlimited)) {
inputDescriptor.unlimited = inputOptions.unlimited;
} else {
throw is.invalidParameterError('unlimited', 'boolean', inputOptions.unlimited);
}
}
// sequentialRead
if (is.defined(inputOptions.sequentialRead)) {
if (is.bool(inputOptions.sequentialRead)) {
inputDescriptor.sequentialRead = inputOptions.sequentialRead;
} else {
throw is.invalidParameterError('sequentialRead', 'boolean', inputOptions.sequentialRead);
}
}
// Raw pixel input
if (is.defined(inputOptions.raw)) {
if (
is.object(inputOptions.raw) &&
is.integer(inputOptions.raw.width) && inputOptions.raw.width > 0 &&
is.integer(inputOptions.raw.height) && inputOptions.raw.height > 0 &&
is.integer(inputOptions.raw.channels) && is.inRange(inputOptions.raw.channels, 1, 4)
) {
inputDescriptor.rawWidth = inputOptions.raw.width;
inputDescriptor.rawHeight = inputOptions.raw.height;
inputDescriptor.rawChannels = inputOptions.raw.channels;
switch (input.constructor) {
case Uint8Array:
case Uint8ClampedArray:
inputDescriptor.rawDepth = 'uchar';
break;
case Int8Array:
inputDescriptor.rawDepth = 'char';
break;
case Uint16Array:
inputDescriptor.rawDepth = 'ushort';
break;
case Int16Array:
inputDescriptor.rawDepth = 'short';
break;
case Uint32Array:
inputDescriptor.rawDepth = 'uint';
break;
case Int32Array:
inputDescriptor.rawDepth = 'int';
break;
case Float32Array:
inputDescriptor.rawDepth = 'float';
break;
case Float64Array:
inputDescriptor.rawDepth = 'double';
break;
default:
inputDescriptor.rawDepth = 'uchar';
break;
}
} else {
throw new Error('Expected width, height and channels for raw pixel input');
}
inputDescriptor.rawPremultiplied = false;
if (is.defined(inputOptions.raw.premultiplied)) {
if (is.bool(inputOptions.raw.premultiplied)) {
inputDescriptor.rawPremultiplied = inputOptions.raw.premultiplied;
} else {
throw is.invalidParameterError('raw.premultiplied', 'boolean', inputOptions.raw.premultiplied);
}
}
inputDescriptor.rawPageHeight = 0;
if (is.defined(inputOptions.raw.pageHeight)) {
if (is.integer(inputOptions.raw.pageHeight) && inputOptions.raw.pageHeight > 0 && inputOptions.raw.pageHeight <= inputOptions.raw.height) {
if (inputOptions.raw.height % inputOptions.raw.pageHeight !== 0) {
throw new Error(`Expected raw.height ${inputOptions.raw.height} to be a multiple of raw.pageHeight ${inputOptions.raw.pageHeight}`);
}
inputDescriptor.rawPageHeight = inputOptions.raw.pageHeight;
} else {
throw is.invalidParameterError('raw.pageHeight', 'positive integer', inputOptions.raw.pageHeight);
}
}
}
// Multi-page input (GIF, TIFF, PDF)
if (is.defined(inputOptions.animated)) {
if (is.bool(inputOptions.animated)) {
inputDescriptor.pages = inputOptions.animated ? -1 : 1;
} else {
throw is.invalidParameterError('animated', 'boolean', inputOptions.animated);
}
}
if (is.defined(inputOptions.pages)) {
if (is.integer(inputOptions.pages) && is.inRange(inputOptions.pages, -1, 100000)) {
inputDescriptor.pages = inputOptions.pages;
} else {
throw is.invalidParameterError('pages', 'integer between -1 and 100000', inputOptions.pages);
}
}
if (is.defined(inputOptions.page)) {
if (is.integer(inputOptions.page) && is.inRange(inputOptions.page, 0, 100000)) {
inputDescriptor.page = inputOptions.page;
} else {
throw is.invalidParameterError('page', 'integer between 0 and 100000', inputOptions.page);
}
}
// OpenSlide specific options
if (is.object(inputOptions.openSlide) && is.defined(inputOptions.openSlide.level)) {
if (is.integer(inputOptions.openSlide.level) && is.inRange(inputOptions.openSlide.level, 0, 256)) {
inputDescriptor.openSlideLevel = inputOptions.openSlide.level;
} else {
throw is.invalidParameterError('openSlide.level', 'integer between 0 and 256', inputOptions.openSlide.level);
}
} else if (is.defined(inputOptions.level)) {
// Deprecated
if (is.integer(inputOptions.level) && is.inRange(inputOptions.level, 0, 256)) {
inputDescriptor.openSlideLevel = inputOptions.level;
} else {
throw is.invalidParameterError('level', 'integer between 0 and 256', inputOptions.level);
}
}
// TIFF specific options
if (is.object(inputOptions.tiff) && is.defined(inputOptions.tiff.subifd)) {
if (is.integer(inputOptions.tiff.subifd) && is.inRange(inputOptions.tiff.subifd, -1, 100000)) {
inputDescriptor.tiffSubifd = inputOptions.tiff.subifd;
} else {
throw is.invalidParameterError('tiff.subifd', 'integer between -1 and 100000', inputOptions.tiff.subifd);
}
} else if (is.defined(inputOptions.subifd)) {
// Deprecated
if (is.integer(inputOptions.subifd) && is.inRange(inputOptions.subifd, -1, 100000)) {
inputDescriptor.tiffSubifd = inputOptions.subifd;
} else {
throw is.invalidParameterError('subifd', 'integer between -1 and 100000', inputOptions.subifd);
}
}
// SVG specific options
if (is.object(inputOptions.svg)) {
if (is.defined(inputOptions.svg.stylesheet)) {
if (is.string(inputOptions.svg.stylesheet)) {
inputDescriptor.svgStylesheet = inputOptions.svg.stylesheet;
} else {
throw is.invalidParameterError('svg.stylesheet', 'string', inputOptions.svg.stylesheet);
}
}
if (is.defined(inputOptions.svg.highBitdepth)) {
if (is.bool(inputOptions.svg.highBitdepth)) {
inputDescriptor.svgHighBitdepth = inputOptions.svg.highBitdepth;
} else {
throw is.invalidParameterError('svg.highBitdepth', 'boolean', inputOptions.svg.highBitdepth);
}
}
}
// PDF specific options
if (is.object(inputOptions.pdf) && is.defined(inputOptions.pdf.background)) {
inputDescriptor.pdfBackground = this._getBackgroundColourOption(inputOptions.pdf.background);
} else if (is.defined(inputOptions.pdfBackground)) {
// Deprecated
inputDescriptor.pdfBackground = this._getBackgroundColourOption(inputOptions.pdfBackground);
}
// JPEG 2000 specific options
if (is.object(inputOptions.jp2) && is.defined(inputOptions.jp2.oneshot)) {
if (is.bool(inputOptions.jp2.oneshot)) {
inputDescriptor.jp2Oneshot = inputOptions.jp2.oneshot;
} else {
throw is.invalidParameterError('jp2.oneshot', 'boolean', inputOptions.jp2.oneshot);
}
}
// Create new image
if (is.defined(inputOptions.create)) {
if (
is.object(inputOptions.create) &&
is.integer(inputOptions.create.width) && inputOptions.create.width > 0 &&
is.integer(inputOptions.create.height) && inputOptions.create.height > 0 &&
is.integer(inputOptions.create.channels)
) {
inputDescriptor.createWidth = inputOptions.create.width;
inputDescriptor.createHeight = inputOptions.create.height;
inputDescriptor.createChannels = inputOptions.create.channels;
inputDescriptor.createPageHeight = 0;
if (is.defined(inputOptions.create.pageHeight)) {
if (is.integer(inputOptions.create.pageHeight) && inputOptions.create.pageHeight > 0 && inputOptions.create.pageHeight <= inputOptions.create.height) {
if (inputOptions.create.height % inputOptions.create.pageHeight !== 0) {
throw new Error(`Expected create.height ${inputOptions.create.height} to be a multiple of create.pageHeight ${inputOptions.create.pageHeight}`);
}
inputDescriptor.createPageHeight = inputOptions.create.pageHeight;
} else {
throw is.invalidParameterError('create.pageHeight', 'positive integer', inputOptions.create.pageHeight);
}
}
// Noise
if (is.defined(inputOptions.create.noise)) {
if (!is.object(inputOptions.create.noise)) {
throw new Error('Expected noise to be an object');
}
if (inputOptions.create.noise.type !== 'gaussian') {
throw new Error('Only gaussian noise is supported at the moment');
}
inputDescriptor.createNoiseType = inputOptions.create.noise.type;
if (!is.inRange(inputOptions.create.channels, 1, 4)) {
throw is.invalidParameterError('create.channels', 'number between 1 and 4', inputOptions.create.channels);
}
inputDescriptor.createNoiseMean = 128;
if (is.defined(inputOptions.create.noise.mean)) {
if (is.number(inputOptions.create.noise.mean) && is.inRange(inputOptions.create.noise.mean, 0, 10000)) {
inputDescriptor.createNoiseMean = inputOptions.create.noise.mean;
} else {
throw is.invalidParameterError('create.noise.mean', 'number between 0 and 10000', inputOptions.create.noise.mean);
}
}
inputDescriptor.createNoiseSigma = 30;
if (is.defined(inputOptions.create.noise.sigma)) {
if (is.number(inputOptions.create.noise.sigma) && is.inRange(inputOptions.create.noise.sigma, 0, 10000)) {
inputDescriptor.createNoiseSigma = inputOptions.create.noise.sigma;
} else {
throw is.invalidParameterError('create.noise.sigma', 'number between 0 and 10000', inputOptions.create.noise.sigma);
}
}
} else if (is.defined(inputOptions.create.background)) {
if (!is.inRange(inputOptions.create.channels, 3, 4)) {
throw is.invalidParameterError('create.channels', 'number between 3 and 4', inputOptions.create.channels);
}
inputDescriptor.createBackground = this._getBackgroundColourOption(inputOptions.create.background);
} else {
throw new Error('Expected valid noise or background to create a new input image');
}
delete inputDescriptor.buffer;
} else {
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.integer(inputOptions.text.width) && inputOptions.text.width > 0) {
inputDescriptor.textWidth = inputOptions.text.width;
} else {
throw is.invalidParameterError('text.width', 'positive integer', inputOptions.text.width);
}
}
if (is.defined(inputOptions.text.height)) {
if (is.integer(inputOptions.text.height) && inputOptions.text.height > 0) {
inputDescriptor.textHeight = inputOptions.text.height;
} else {
throw is.invalidParameterError('text.height', 'positive integer', 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.integer(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 1000000)) {
inputDescriptor.textDpi = inputOptions.text.dpi;
} else {
throw is.invalidParameterError('text.dpi', 'integer between 1 and 1000000', 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.integer(inputOptions.text.spacing) && is.inRange(inputOptions.text.spacing, -1000000, 1000000)) {
inputDescriptor.textSpacing = inputOptions.text.spacing;
} else {
throw is.invalidParameterError('text.spacing', 'integer between -1000000 and 1000000', inputOptions.text.spacing);
}
}
if (is.defined(inputOptions.text.wrap)) {
if (is.string(inputOptions.text.wrap) && is.inArray(inputOptions.text.wrap, ['word', 'char', 'word-char', 'none'])) {
inputDescriptor.textWrap = inputOptions.text.wrap;
} else {
throw is.invalidParameterError('text.wrap', 'one of: word, char, word-char, none', inputOptions.text.wrap);
}
}
delete inputDescriptor.buffer;
} else {
throw new Error('Expected a valid string to create an image with text.');
}
}
// Join images together
if (is.defined(inputOptions.join)) {
if (is.defined(this.options.join)) {
if (is.defined(inputOptions.join.animated)) {
if (is.bool(inputOptions.join.animated)) {
inputDescriptor.joinAnimated = inputOptions.join.animated;
} else {
throw is.invalidParameterError('join.animated', 'boolean', inputOptions.join.animated);
}
}
if (is.defined(inputOptions.join.across)) {
if (is.integer(inputOptions.join.across) && is.inRange(inputOptions.join.across, 1, 1000000)) {
inputDescriptor.joinAcross = inputOptions.join.across;
} else {
throw is.invalidParameterError('join.across', 'integer between 1 and 100000', inputOptions.join.across);
}
}
if (is.defined(inputOptions.join.shim)) {
if (is.integer(inputOptions.join.shim) && is.inRange(inputOptions.join.shim, 0, 1000000)) {
inputDescriptor.joinShim = inputOptions.join.shim;
} else {
throw is.invalidParameterError('join.shim', 'integer between 0 and 100000', inputOptions.join.shim);
}
}
if (is.defined(inputOptions.join.background)) {
inputDescriptor.joinBackground = this._getBackgroundColourOption(inputOptions.join.background);
}
if (is.defined(inputOptions.join.halign)) {
if (is.string(inputOptions.join.halign) && is.string(this.constructor.align[inputOptions.join.halign])) {
inputDescriptor.joinHalign = this.constructor.align[inputOptions.join.halign];
} else {
throw is.invalidParameterError('join.halign', 'valid alignment', inputOptions.join.halign);
}
}
if (is.defined(inputOptions.join.valign)) {
if (is.string(inputOptions.join.valign) && is.string(this.constructor.align[inputOptions.join.valign])) {
inputDescriptor.joinValign = this.constructor.align[inputOptions.join.valign];
} else {
throw is.invalidParameterError('join.valign', 'valid alignment', inputOptions.join.valign);
}
}
} else {
throw new Error('Expected input to be an array of images to join');
}
}
} else if (is.defined(inputOptions)) {
throw new Error('Invalid input options ' + inputOptions);
}
return inputDescriptor;
}
/**
* Handle incoming Buffer chunk on Writable Stream.
* @private
* @param {Buffer} chunk
* @param {string} encoding - unused
* @param {Function} callback
*/
function _write (chunk, encoding, callback) {
/* istanbul ignore else */
if (Array.isArray(this.options.input.buffer)) {
/* istanbul ignore else */
if (is.buffer(chunk)) {
if (this.options.input.buffer.length === 0) {
this.on('finish', () => {
this.streamInFinished = true;
});
}
this.options.input.buffer.push(chunk);
callback();
} else {
callback(new Error('Non-Buffer data on Writable Stream'));
}
} else {
callback(new Error('Unexpected data on Writable Stream'));
}
}
/**
* Flattens the array of chunks accumulated in input.buffer.
* @private
*/
function _flattenBufferIn () {
if (this._isStreamInput()) {
this.options.input.buffer = Buffer.concat(this.options.input.buffer);
}
}
/**
* Are we expecting Stream-based input?
* @private
* @returns {boolean}
*/
function _isStreamInput () {
return Array.isArray(this.options.input.buffer);
}
/**
* Fast access to (uncached) image metadata without decoding any compressed pixel data.
*
* This is read from the header of the input image.
* It does not take into consideration any operations to be applied to the output image,
* such as resize or rotate.
*
* 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.
*
* - `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg`
* - `size`: Total size of image in bytes, for Stream and Buffer input only
* - `width`: Number of pixels wide (EXIF orientation is not taken into consideration, see example below)
* - `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://www.libvips.org/API/current/VipsImage.html#VipsInterpretation)
* - `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://www.libvips.org/API/current/VipsImage.html#VipsBandFormat)
* - `density`: Number of pixels per inch (DPI), if present
* - `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK
* - `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan
* - `isPalette`: Boolean indicating whether the image is palette-based (GIF, PNG).
* - `bitsPerSample`: Number of bits per sample for each channel (GIF, PNG, HEIF).
* - `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP
* - `pageHeight`: Number of pixels high each page in a multi-page image will be.
* - `loop`: Number of times to loop an animated image, zero refers to a continuous loop.
* - `delay`: Delay in ms between each page in an animated image, provided as an array of integers.
* - `pagePrimary`: Number of the primary page in a HEIF image
* - `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide
* - `subifds`: Number of Sub Image File Directories in an OME-TIFF image
* - `background`: Default background colour, if present, for PNG (bKGD) and GIF images
* - `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC)
* - `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present
* - `hasProfile`: Boolean indicating the presence of an embedded ICC profile
* - `hasAlpha`: Boolean indicating the presence of an alpha transparency channel
* - `orientation`: Number value of the EXIF Orientation header, if present
* - `exif`: Buffer containing raw EXIF data, if present
* - `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present
* - `iptc`: Buffer containing raw IPTC data, if present
* - `xmp`: Buffer containing raw XMP data, if present
* - `xmpAsString`: String containing XMP data, if valid UTF-8.
* - `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present
* - `formatMagick`: String containing format for images loaded via *magick
* - `comments`: Array of keyword/text pairs representing PNG text blocks, if present.
*
* @example
* const metadata = await sharp(input).metadata();
*
* @example
* const image = sharp(inputJpg);
* image
* .metadata()
* .then(function(metadata) {
* return image
* .resize(Math.round(metadata.width / 2))
* .webp()
* .toBuffer();
* })
* .then(function(data) {
* // data contains a WebP image half the width and height of the original JPEG
* });
*
* @example
* // Get dimensions taking EXIF Orientation into account.
* const { autoOrient } = await sharp(input).metadata();
* const { width, height } = autoOrient;
*
* @param {Function} [callback] - called with the arguments `(err, metadata)`
* @returns {Promise<Object>|Sharp}
*/
function metadata (callback) {
const stack = Error();
if (is.fn(callback)) {
if (this._isStreamInput()) {
this.on('finish', () => {
this._flattenBufferIn();
sharp.metadata(this.options, (err, metadata) => {
if (err) {
callback(is.nativeError(err, stack));
} else {
callback(null, metadata);
}
});
});
} else {
sharp.metadata(this.options, (err, metadata) => {
if (err) {
callback(is.nativeError(err, stack));
} else {
callback(null, metadata);
}
});
}
return this;
} else {
if (this._isStreamInput()) {
return new Promise((resolve, reject) => {
const finished = () => {
this._flattenBufferIn();
sharp.metadata(this.options, (err, metadata) => {
if (err) {
reject(is.nativeError(err, stack));
} else {
resolve(metadata);
}
});
};
if (this.writableFinished) {
finished();
} else {
this.once('finish', finished);
}
});
} else {
return new Promise((resolve, reject) => {
sharp.metadata(this.options, (err, metadata) => {
if (err) {
reject(is.nativeError(err, stack));
} else {
resolve(metadata);
}
});
});
}
}
}
/**
* Access to pixel-derived image statistics for every channel in the image.
* A `Promise` is returned when `callback` is not provided.
*
* - `channels`: Array of channel statistics for each channel in the image. Each channel statistic contains
* - `min` (minimum value in the channel)
* - `max` (maximum value in the channel)
* - `sum` (sum of all values in a channel)
* - `squaresSum` (sum of squared values in a channel)
* - `mean` (mean of the values in a channel)
* - `stdev` (standard deviation for the values in a channel)
* - `minX` (x-coordinate of one of the pixel where the minimum lies)
* - `minY` (y-coordinate of one of the pixel where the minimum lies)
* - `maxX` (x-coordinate of one of the pixel where the maximum lies)
* - `maxY` (y-coordinate of one of the pixel where the maximum lies)
* - `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque.
* - `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any.
* - `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.
*
* **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).
*
* @example
* const image = sharp(inputJpg);
* image
* .stats()
* .then(function(stats) {
* // stats contains the channel-wise statistics array and the isOpaque value
* });
*
* @example
* const { entropy, sharpness, dominant } = await sharp(input).stats();
* const { r, g, b } = dominant;
*
* @example
* const image = sharp(input);
* // store intermediate result
* const part = await image.extract(region).toBuffer();
* // create new instance to obtain statistics of extracted region
* const stats = await sharp(part).stats();
*
* @param {Function} [callback] - called with the arguments `(err, stats)`
* @returns {Promise<Object>}
*/
function stats (callback) {
const stack = Error();
if (is.fn(callback)) {
if (this._isStreamInput()) {
this.on('finish', () => {
this._flattenBufferIn();
sharp.stats(this.options, (err, stats) => {
if (err) {
callback(is.nativeError(err, stack));
} else {
callback(null, stats);
}
});
});
} else {
sharp.stats(this.options, (err, stats) => {
if (err) {
callback(is.nativeError(err, stack));
} else {
callback(null, stats);
}
});
}
return this;
} else {
if (this._isStreamInput()) {
return new Promise((resolve, reject) => {
this.on('finish', function () {
this._flattenBufferIn();
sharp.stats(this.options, (err, stats) => {
if (err) {
reject(is.nativeError(err, stack));
} else {
resolve(stats);
}
});
});
});
} else {
return new Promise((resolve, reject) => {
sharp.stats(this.options, (err, stats) => {
if (err) {
reject(is.nativeError(err, stack));
} else {
resolve(stats);
}
});
});
}
}
}
/**
* Decorate the Sharp prototype with input-related functions.
* @module Sharp
* @private
*/
module.exports = function (Sharp) {
Object.assign(Sharp.prototype, {
// Private
_inputOptionsFromObject,
_createInputDescriptor,
_write,
_flattenBufferIn,
_isStreamInput,
// Public
metadata,
stats
});
// Class attributes
Sharp.align = align;
};

169
lib/is.js Normal file
View File

@ -0,0 +1,169 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
/**
* Is this value defined and not null?
* @private
*/
const defined = function (val) {
return typeof val !== 'undefined' && val !== null;
};
/**
* Is this value an object?
* @private
*/
const object = function (val) {
return typeof val === 'object';
};
/**
* Is this value a plain object?
* @private
*/
const plainObject = function (val) {
return Object.prototype.toString.call(val) === '[object Object]';
};
/**
* Is this value a function?
* @private
*/
const fn = function (val) {
return typeof val === 'function';
};
/**
* Is this value a boolean?
* @private
*/
const bool = function (val) {
return typeof val === 'boolean';
};
/**
* Is this value a Buffer object?
* @private
*/
const buffer = function (val) {
return val instanceof Buffer;
};
/**
* Is this value a typed array object?. E.g. Uint8Array or Uint8ClampedArray?
* @private
*/
const typedArray = function (val) {
if (defined(val)) {
switch (val.constructor) {
case Uint8Array:
case Uint8ClampedArray:
case Int8Array:
case Uint16Array:
case Int16Array:
case Uint32Array:
case Int32Array:
case Float32Array:
case Float64Array:
return true;
}
}
return false;
};
/**
* Is this value an ArrayBuffer object?
* @private
*/
const arrayBuffer = function (val) {
return val instanceof ArrayBuffer;
};
/**
* Is this value a non-empty string?
* @private
*/
const string = function (val) {
return typeof val === 'string' && val.length > 0;
};
/**
* Is this value a real number?
* @private
*/
const number = function (val) {
return typeof val === 'number' && !Number.isNaN(val);
};
/**
* Is this value an integer?
* @private
*/
const integer = function (val) {
return Number.isInteger(val);
};
/**
* Is this value within an inclusive given range?
* @private
*/
const inRange = function (val, min, max) {
return val >= min && val <= max;
};
/**
* Is this value within the elements of an array?
* @private
*/
const inArray = function (val, list) {
return list.includes(val);
};
/**
* Create an Error with a message relating to an invalid parameter.
*
* @param {string} name - parameter name.
* @param {string} expected - description of the type/value/range expected.
* @param {*} actual - the value received.
* @returns {Error} Containing the formatted message.
* @private
*/
const invalidParameterError = function (name, expected, actual) {
return new Error(
`Expected ${expected} for ${name} but received ${actual} of type ${typeof actual}`
);
};
/**
* Ensures an Error from C++ contains a JS stack.
*
* @param {Error} native - Error with message from C++.
* @param {Error} context - Error with stack from JS.
* @returns {Error} Error with message and stack.
* @private
*/
const nativeError = function (native, context) {
context.message = native.message;
return context;
};
module.exports = {
defined,
object,
plainObject,
fn,
bool,
buffer,
typedArray,
arrayBuffer,
string,
number,
integer,
inRange,
inArray,
invalidParameterError,
nativeError
};

205
lib/libvips.js Normal file
View File

@ -0,0 +1,205 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
const { spawnSync } = require('node:child_process');
const { createHash } = require('node:crypto');
const semverCoerce = require('semver/functions/coerce');
const semverGreaterThanOrEqualTo = require('semver/functions/gte');
const semverSatisfies = require('semver/functions/satisfies');
const detectLibc = require('detect-libc');
const { config, engines, optionalDependencies } = require('../package.json');
const minimumLibvipsVersionLabelled = process.env.npm_package_config_libvips || /* istanbul ignore next */
config.libvips;
const minimumLibvipsVersion = semverCoerce(minimumLibvipsVersionLabelled).version;
const prebuiltPlatforms = [
'darwin-arm64', 'darwin-x64',
'linux-arm', 'linux-arm64', 'linux-ppc64', 'linux-s390x', 'linux-x64',
'linuxmusl-arm64', 'linuxmusl-x64',
'win32-arm64', 'win32-ia32', 'win32-x64'
];
const spawnSyncOptions = {
encoding: 'utf8',
shell: true
};
const log = (item) => {
if (item instanceof Error) {
console.error(`sharp: Installation error: ${item.message}`);
} else {
console.log(`sharp: ${item}`);
}
};
/* istanbul ignore next */
const runtimeLibc = () => detectLibc.isNonGlibcLinuxSync() ? detectLibc.familySync() : '';
const runtimePlatformArch = () => `${process.platform}${runtimeLibc()}-${process.arch}`;
/* istanbul ignore next */
const buildPlatformArch = () => {
if (isEmscripten()) {
return 'wasm32';
}
/* eslint camelcase: ["error", { allow: ["^npm_config_"] }] */
const { npm_config_arch, npm_config_platform, npm_config_libc } = process.env;
const libc = typeof npm_config_libc === 'string' ? npm_config_libc : runtimeLibc();
return `${npm_config_platform || process.platform}${libc}-${npm_config_arch || process.arch}`;
};
const buildSharpLibvipsIncludeDir = () => {
try {
return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/include`);
} catch {
try {
return require('@img/sharp-libvips-dev/include');
} catch {}
}
/* istanbul ignore next */
return '';
};
const buildSharpLibvipsCPlusPlusDir = () => {
try {
return require('@img/sharp-libvips-dev/cplusplus');
} catch {}
/* istanbul ignore next */
return '';
};
const buildSharpLibvipsLibDir = () => {
try {
return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/lib`);
} catch {
try {
return require(`@img/sharp-libvips-${buildPlatformArch()}/lib`);
} catch {}
}
/* istanbul ignore next */
return '';
};
const isUnsupportedNodeRuntime = () => {
/* istanbul ignore next */
if (process.release?.name === 'node' && process.versions) {
if (!semverSatisfies(process.versions.node, engines.node)) {
return { found: process.versions.node, expected: engines.node };
}
}
};
/* istanbul ignore next */
const isEmscripten = () => {
const { CC } = process.env;
return Boolean(CC && CC.endsWith('/emcc'));
};
const isRosetta = () => {
/* istanbul ignore next */
if (process.platform === 'darwin' && process.arch === 'x64') {
const translated = spawnSync('sysctl sysctl.proc_translated', spawnSyncOptions).stdout;
return (translated || '').trim() === 'sysctl.proc_translated: 1';
}
return false;
};
const sha512 = (s) => createHash('sha512').update(s).digest('hex');
const yarnLocator = () => {
try {
const identHash = sha512(`imgsharp-libvips-${buildPlatformArch()}`);
const npmVersion = semverCoerce(optionalDependencies[`@img/sharp-libvips-${buildPlatformArch()}`], {
includePrerelease: true
}).version;
return sha512(`${identHash}npm:${npmVersion}`).slice(0, 10);
} catch {}
return '';
};
/* istanbul ignore next */
const spawnRebuild = () =>
spawnSync(`node-gyp rebuild --directory=src ${isEmscripten() ? '--nodedir=emscripten' : ''}`, {
...spawnSyncOptions,
stdio: 'inherit'
}).status;
const globalLibvipsVersion = () => {
if (process.platform !== 'win32') {
const globalLibvipsVersion = spawnSync('pkg-config --modversion vips-cpp', {
...spawnSyncOptions,
env: {
...process.env,
PKG_CONFIG_PATH: pkgConfigPath()
}
}).stdout;
/* istanbul ignore next */
return (globalLibvipsVersion || '').trim();
} else {
return '';
}
};
/* istanbul ignore next */
const pkgConfigPath = () => {
if (process.platform !== 'win32') {
const brewPkgConfigPath = spawnSync(
'which brew >/dev/null 2>&1 && brew environment --plain | grep PKG_CONFIG_LIBDIR | cut -d" " -f2',
spawnSyncOptions
).stdout || '';
return [
brewPkgConfigPath.trim(),
process.env.PKG_CONFIG_PATH,
'/usr/local/lib/pkgconfig',
'/usr/lib/pkgconfig',
'/usr/local/libdata/pkgconfig',
'/usr/libdata/pkgconfig'
].filter(Boolean).join(':');
} else {
return '';
}
};
const skipSearch = (status, reason, logger) => {
if (logger) {
logger(`Detected ${reason}, skipping search for globally-installed libvips`);
}
return status;
};
const useGlobalLibvips = (logger) => {
if (Boolean(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS) === true) {
return skipSearch(false, 'SHARP_IGNORE_GLOBAL_LIBVIPS', logger);
}
if (Boolean(process.env.SHARP_FORCE_GLOBAL_LIBVIPS) === true) {
return skipSearch(true, 'SHARP_FORCE_GLOBAL_LIBVIPS', logger);
}
/* istanbul ignore next */
if (isRosetta()) {
return skipSearch(false, 'Rosetta', logger);
}
const globalVipsVersion = globalLibvipsVersion();
return !!globalVipsVersion && /* istanbul ignore next */
semverGreaterThanOrEqualTo(globalVipsVersion, minimumLibvipsVersion);
};
module.exports = {
minimumLibvipsVersion,
prebuiltPlatforms,
buildPlatformArch,
buildSharpLibvipsIncludeDir,
buildSharpLibvipsCPlusPlusDir,
buildSharpLibvipsLibDir,
isUnsupportedNodeRuntime,
runtimePlatformArch,
log,
yarnLocator,
spawnRebuild,
globalLibvipsVersion,
pkgConfigPath,
useGlobalLibvips
};

1018
lib/operation.js Normal file

File diff suppressed because it is too large Load Diff

1655
lib/output.js Normal file

File diff suppressed because it is too large Load Diff

592
lib/resize.js Normal file
View File

@ -0,0 +1,592 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
const is = require('./is');
/**
* Weighting to apply when using contain/cover fit.
* @member
* @private
*/
const gravity = {
center: 0,
centre: 0,
north: 1,
east: 2,
south: 3,
west: 4,
northeast: 5,
southeast: 6,
southwest: 7,
northwest: 8
};
/**
* Position to apply when using contain/cover fit.
* @member
* @private
*/
const position = {
top: 1,
right: 2,
bottom: 3,
left: 4,
'right top': 5,
'right bottom': 6,
'left bottom': 7,
'left top': 8
};
/**
* How to extend the image.
* @member
* @private
*/
const extendWith = {
background: 'background',
copy: 'copy',
repeat: 'repeat',
mirror: 'mirror'
};
/**
* Strategies for automagic cover behaviour.
* @member
* @private
*/
const strategy = {
entropy: 16,
attention: 17
};
/**
* Reduction kernels.
* @member
* @private
*/
const kernel = {
nearest: 'nearest',
linear: 'linear',
cubic: 'cubic',
mitchell: 'mitchell',
lanczos2: 'lanczos2',
lanczos3: 'lanczos3',
mks2013: 'mks2013',
mks2021: 'mks2021'
};
/**
* Methods by which an image can be resized to fit the provided dimensions.
* @member
* @private
*/
const fit = {
contain: 'contain',
cover: 'cover',
fill: 'fill',
inside: 'inside',
outside: 'outside'
};
/**
* Map external fit property to internal canvas property.
* @member
* @private
*/
const mapFitToCanvas = {
contain: 'embed',
cover: 'crop',
fill: 'ignore_aspect',
inside: 'max',
outside: 'min'
};
/**
* @private
*/
function isRotationExpected (options) {
return (options.angle % 360) !== 0 || options.input.autoOrient === true || options.rotationAngle !== 0;
}
/**
* @private
*/
function isResizeExpected (options) {
return options.width !== -1 || options.height !== -1;
}
/**
* Resize image to `width`, `height` or `width x height`.
*
* When both a `width` and `height` are provided, the possible methods by which the image should **fit** these are:
* - `cover`: (default) Preserving aspect ratio, attempt to ensure the image covers both provided dimensions by cropping/clipping to fit.
* - `contain`: Preserving aspect ratio, contain within both provided dimensions using "letterboxing" where necessary.
* - `fill`: Ignore the aspect ratio of the input and stretch to both provided dimensions.
* - `inside`: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified.
* - `outside`: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified.
*
* Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property.
*
* <img alt="Examples of various values for the fit property when resizing" width="100%" style="aspect-ratio: 998/243" src="/api-resize-fit.svg">
*
* When using a **fit** of `cover` or `contain`, the default **position** is `centre`. Other options are:
* - `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`.
* - `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`.
* - `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy.
*
* Some of these values are based on the [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS property.
*
* The strategy-based approach initially resizes so one dimension is at its target length
* then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.
* - `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29).
* - `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
*
* Possible downsizing kernels are:
* - `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation).
* - `linear`: Use a [triangle filter](https://en.wikipedia.org/wiki/Triangular_function).
* - `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline).
* - `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf).
* - `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`.
* - `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
* - `mks2013`: Use a [Magic Kernel Sharp](https://johncostella.com/magic/mks.pdf) 2013 kernel, as adopted by Facebook.
* - `mks2021`: Use a Magic Kernel Sharp 2021 kernel, with more accurate (reduced) sharpening than the 2013 version.
*
* When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators.
* Downsampling kernels without a matching upsampling interpolator map to `cubic`.
*
* Only one resize can occur per pipeline.
* Previous calls to `resize` in the same pipeline will be ignored.
*
* @example
* sharp(input)
* .resize({ width: 100 })
* .toBuffer()
* .then(data => {
* // 100 pixels wide, auto-scaled height
* });
*
* @example
* sharp(input)
* .resize({ height: 100 })
* .toBuffer()
* .then(data => {
* // 100 pixels high, auto-scaled width
* });
*
* @example
* sharp(input)
* .resize(200, 300, {
* kernel: sharp.kernel.nearest,
* fit: 'contain',
* position: 'right top',
* background: { r: 255, g: 255, b: 255, alpha: 0.5 }
* })
* .toFile('output.png')
* .then(() => {
* // output.png is a 200 pixels wide and 300 pixels high image
* // containing a nearest-neighbour scaled version
* // contained within the north-east corner of a semi-transparent white canvas
* });
*
* @example
* const transformer = sharp()
* .resize({
* width: 200,
* height: 200,
* fit: sharp.fit.cover,
* position: sharp.strategy.entropy
* });
* // Read image data from readableStream
* // Write 200px square auto-cropped image data to writableStream
* readableStream
* .pipe(transformer)
* .pipe(writableStream);
*
* @example
* sharp(input)
* .resize(200, 200, {
* fit: sharp.fit.inside,
* withoutEnlargement: true
* })
* .toFormat('jpeg')
* .toBuffer()
* .then(function(outputBuffer) {
* // outputBuffer contains JPEG image data
* // no wider and no higher than 200 pixels
* // and no larger than the input image
* });
*
* @example
* sharp(input)
* .resize(200, 200, {
* fit: sharp.fit.outside,
* withoutReduction: true
* })
* .toFormat('jpeg')
* .toBuffer()
* .then(function(outputBuffer) {
* // outputBuffer contains JPEG image data
* // of at least 200 pixels wide and 200 pixels high while maintaining aspect ratio
* // and no smaller than the input image
* });
*
* @example
* const scaleByHalf = await sharp(input)
* .metadata()
* .then(({ width }) => sharp(input)
* .resize(Math.round(width * 0.5))
* .toBuffer()
* );
*
* @param {number} [width] - How many pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height.
* @param {number} [height] - How many pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width.
* @param {Object} [options]
* @param {number} [options.width] - An alternative means of specifying `width`. If both are present this takes priority.
* @param {number} [options.height] - An alternative means of specifying `height`. If both are present this takes priority.
* @param {String} [options.fit='cover'] - How the image should be resized/cropped to fit the target dimension(s), one of `cover`, `contain`, `fill`, `inside` or `outside`.
* @param {String} [options.position='centre'] - A 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 `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 and the inferred interpolator to use for upsampling. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load.
* @param {Boolean} [options.withoutEnlargement=false] - Do not scale up if the width *or* height are already less than the target dimensions, equivalent to GraphicsMagick's `>` geometry option. This may result in output dimensions smaller than the target dimensions.
* @param {Boolean} [options.withoutReduction=false] - Do not scale down if the width *or* height are already greater than the target dimensions, equivalent to GraphicsMagick's `<` geometry option. This may still result in a crop to reach the target dimensions.
* @param {Boolean} [options.fastShrinkOnLoad=true] - Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern or round-down of an auto-scaled dimension.
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
function resize (widthOrOptions, height, options) {
if (isResizeExpected(this.options)) {
this.options.debuglog('ignoring previous resize options');
}
if (this.options.widthPost !== -1) {
this.options.debuglog('operation order will be: extract, resize, extract');
}
if (is.defined(widthOrOptions)) {
if (is.object(widthOrOptions) && !is.defined(options)) {
options = widthOrOptions;
} else if (is.integer(widthOrOptions) && widthOrOptions > 0) {
this.options.width = widthOrOptions;
} else {
throw is.invalidParameterError('width', 'positive integer', widthOrOptions);
}
} else {
this.options.width = -1;
}
if (is.defined(height)) {
if (is.integer(height) && height > 0) {
this.options.height = height;
} else {
throw is.invalidParameterError('height', 'positive integer', height);
}
} else {
this.options.height = -1;
}
if (is.object(options)) {
// Width
if (is.defined(options.width)) {
if (is.integer(options.width) && options.width > 0) {
this.options.width = options.width;
} else {
throw is.invalidParameterError('width', 'positive integer', options.width);
}
}
// Height
if (is.defined(options.height)) {
if (is.integer(options.height) && options.height > 0) {
this.options.height = options.height;
} else {
throw is.invalidParameterError('height', 'positive integer', options.height);
}
}
// Fit
if (is.defined(options.fit)) {
const canvas = mapFitToCanvas[options.fit];
if (is.string(canvas)) {
this.options.canvas = canvas;
} else {
throw is.invalidParameterError('fit', 'valid fit', options.fit);
}
}
// Position
if (is.defined(options.position)) {
const pos = is.integer(options.position)
? options.position
: strategy[options.position] || position[options.position] || gravity[options.position];
if (is.integer(pos) && (is.inRange(pos, 0, 8) || is.inRange(pos, 16, 17))) {
this.options.position = pos;
} else {
throw is.invalidParameterError('position', 'valid position/gravity/strategy', options.position);
}
}
// Background
this._setBackgroundColourOption('resizeBackground', options.background);
// Kernel
if (is.defined(options.kernel)) {
if (is.string(kernel[options.kernel])) {
this.options.kernel = kernel[options.kernel];
} else {
throw is.invalidParameterError('kernel', 'valid kernel name', options.kernel);
}
}
// Without enlargement
if (is.defined(options.withoutEnlargement)) {
this._setBooleanOption('withoutEnlargement', options.withoutEnlargement);
}
// Without reduction
if (is.defined(options.withoutReduction)) {
this._setBooleanOption('withoutReduction', options.withoutReduction);
}
// Shrink on load
if (is.defined(options.fastShrinkOnLoad)) {
this._setBooleanOption('fastShrinkOnLoad', options.fastShrinkOnLoad);
}
}
if (isRotationExpected(this.options) && isResizeExpected(this.options)) {
this.options.rotateBeforePreExtract = true;
}
return this;
}
/**
* Extend / pad / extrude one or more edges of the image with either
* the provided background colour or pixels derived from the image.
* This operation will always occur after resizing and extraction, if any.
*
* @example
* // Resize to 140 pixels wide, then add 10 transparent pixels
* // to the top, left and right edges and 20 to the bottom edge
* sharp(input)
* .resize(140)
* .extend({
* top: 10,
* bottom: 20,
* left: 10,
* right: 10,
* background: { r: 0, g: 0, b: 0, alpha: 0 }
* })
* ...
*
* @example
* // Add a row of 10 red pixels to the bottom
* sharp(input)
* .extend({
* bottom: 10,
* background: 'red'
* })
* ...
*
* @example
* // Extrude image by 8 pixels to the right, mirroring existing right hand edge
* sharp(input)
* .extend({
* right: 8,
* background: 'mirror'
* })
* ...
*
* @param {(number|Object)} extend - single pixel count to add to all edges or an Object with per-edge counts
* @param {number} [extend.top=0]
* @param {number} [extend.left=0]
* @param {number} [extend.bottom=0]
* @param {number} [extend.right=0]
* @param {String} [extend.extendWith='background'] - populate new pixels using this method, one of: background, copy, repeat, mirror.
* @param {String|Object} [extend.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency.
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
function extend (extend) {
if (is.integer(extend) && extend > 0) {
this.options.extendTop = extend;
this.options.extendBottom = extend;
this.options.extendLeft = extend;
this.options.extendRight = extend;
} else if (is.object(extend)) {
if (is.defined(extend.top)) {
if (is.integer(extend.top) && extend.top >= 0) {
this.options.extendTop = extend.top;
} else {
throw is.invalidParameterError('top', 'positive integer', extend.top);
}
}
if (is.defined(extend.bottom)) {
if (is.integer(extend.bottom) && extend.bottom >= 0) {
this.options.extendBottom = extend.bottom;
} else {
throw is.invalidParameterError('bottom', 'positive integer', extend.bottom);
}
}
if (is.defined(extend.left)) {
if (is.integer(extend.left) && extend.left >= 0) {
this.options.extendLeft = extend.left;
} else {
throw is.invalidParameterError('left', 'positive integer', extend.left);
}
}
if (is.defined(extend.right)) {
if (is.integer(extend.right) && extend.right >= 0) {
this.options.extendRight = extend.right;
} else {
throw is.invalidParameterError('right', 'positive integer', extend.right);
}
}
this._setBackgroundColourOption('extendBackground', extend.background);
if (is.defined(extend.extendWith)) {
if (is.string(extendWith[extend.extendWith])) {
this.options.extendWith = extendWith[extend.extendWith];
} else {
throw is.invalidParameterError('extendWith', 'one of: background, copy, repeat, mirror', extend.extendWith);
}
}
} else {
throw is.invalidParameterError('extend', 'integer or object', extend);
}
return this;
}
/**
* Extract/crop a region of the image.
*
* - Use `extract` before `resize` for pre-resize extraction.
* - Use `extract` after `resize` for post-resize extraction.
* - Use `extract` twice and `resize` once for extract-then-resize-then-extract in a fixed operation order.
*
* @example
* sharp(input)
* .extract({ left: left, top: top, width: width, height: height })
* .toFile(output, function(err) {
* // Extract a region of the input image, saving in the same format.
* });
* @example
* sharp(input)
* .extract({ left: leftOffsetPre, top: topOffsetPre, width: widthPre, height: heightPre })
* .resize(width, height)
* .extract({ left: leftOffsetPost, top: topOffsetPost, width: widthPost, height: heightPost })
* .toFile(output, function(err) {
* // Extract a region, resize, then extract from the resized image
* });
*
* @param {Object} options - describes the region to extract using integral pixel values
* @param {number} options.left - zero-indexed offset from left edge
* @param {number} options.top - zero-indexed offset from top edge
* @param {number} options.width - width of region to extract
* @param {number} options.height - height of region to extract
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
function extract (options) {
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) {
const value = options[name];
if (is.integer(value) && value >= 0) {
this.options[name + (name === 'left' || name === 'top' ? 'Offset' : '') + suffix] = value;
} else {
throw is.invalidParameterError(name, 'integer', value);
}
}, this);
// Ensure existing rotation occurs before pre-resize extraction
if (isRotationExpected(this.options) && !isResizeExpected(this.options)) {
if (this.options.widthPre === -1 || this.options.widthPost === -1) {
this.options.rotateBeforePreExtract = true;
}
}
return this;
}
/**
* Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.
*
* 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 will contain `trimOffsetLeft` and `trimOffsetTop` properties.
*
* @example
* // Trim pixels with a colour similar to that of the top-left pixel.
* await sharp(input)
* .trim()
* .toFile(output);
*
* @example
* // Trim pixels with the exact same colour as that of the top-left pixel.
* await sharp(input)
* .trim({
* threshold: 0
* })
* .toFile(output);
*
* @example
* // Assume input is line art and trim only pixels with a similar colour to red.
* const output = await sharp(input)
* .trim({
* background: "#FF0000",
* lineArt: true
* })
* .toBuffer();
*
* @example
* // Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
* const output = await sharp(input)
* .trim({
* background: "yellow",
* threshold: 42,
* })
* .toBuffer();
*
* @param {Object} [options]
* @param {string|Object} [options.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} [options.threshold=10] - Allowed difference from the above colour, a positive number.
* @param {boolean} [options.lineArt=false] - Does the input more closely resemble line art (e.g. vector) rather than being photographic?
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
function trim (options) {
this.options.trimThreshold = 10;
if (is.defined(options)) {
if (is.object(options)) {
if (is.defined(options.background)) {
this._setBackgroundColourOption('trimBackground', options.background);
}
if (is.defined(options.threshold)) {
if (is.number(options.threshold) && options.threshold >= 0) {
this.options.trimThreshold = options.threshold;
} else {
throw is.invalidParameterError('threshold', 'positive number', options.threshold);
}
}
if (is.defined(options.lineArt)) {
this._setBooleanOption('trimLineArt', options.lineArt);
}
} else {
throw is.invalidParameterError('trim', 'object', options);
}
}
if (isRotationExpected(this.options)) {
this.options.rotateBeforePreExtract = true;
}
return this;
}
/**
* Decorate the Sharp prototype with resize-related functions.
* @module Sharp
* @private
*/
module.exports = function (Sharp) {
Object.assign(Sharp.prototype, {
resize,
extend,
extract,
trim
});
// Class attributes
Sharp.gravity = gravity;
Sharp.strategy = strategy;
Sharp.kernel = kernel;
Sharp.fit = fit;
Sharp.position = position;
};

122
lib/sharp.js Normal file
View File

@ -0,0 +1,122 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
// Inspects the runtime environment and exports the relevant sharp.node binary
const { familySync, versionSync } = require('detect-libc');
const { runtimePlatformArch, isUnsupportedNodeRuntime, prebuiltPlatforms, minimumLibvipsVersion } = require('./libvips');
const runtimePlatform = runtimePlatformArch();
const paths = [
`../src/build/Release/sharp-${runtimePlatform}.node`,
'../src/build/Release/sharp-wasm32.node',
`@img/sharp-${runtimePlatform}/sharp.node`,
'@img/sharp-wasm32/sharp.node'
];
let path, sharp;
const errors = [];
for (path of paths) {
try {
sharp = require(path);
break;
} catch (err) {
/* istanbul ignore next */
errors.push(err);
}
}
/* istanbul ignore next */
if (sharp && path.startsWith('@img/sharp-linux-x64') && !sharp._isUsingX64V2()) {
const err = new Error('Prebuilt binaries for linux-x64 require v2 microarchitecture');
err.code = 'Unsupported CPU';
errors.push(err);
sharp = null;
}
/* istanbul ignore next */
if (sharp) {
module.exports = sharp;
} else {
const [isLinux, isMacOs, isWindows] = ['linux', 'darwin', 'win32'].map(os => runtimePlatform.startsWith(os));
const help = [`Could not load the "sharp" module using the ${runtimePlatform} runtime`];
errors.forEach(err => {
if (err.code !== 'MODULE_NOT_FOUND') {
help.push(`${err.code}: ${err.message}`);
}
});
const messages = errors.map(err => err.message).join(' ');
help.push('Possible solutions:');
// Common error messages
if (isUnsupportedNodeRuntime()) {
const { found, expected } = isUnsupportedNodeRuntime();
help.push(
'- Please upgrade Node.js:',
` Found ${found}`,
` Requires ${expected}`
);
} else if (prebuiltPlatforms.includes(runtimePlatform)) {
const [os, cpu] = runtimePlatform.split('-');
const libc = os.endsWith('musl') ? ' --libc=musl' : '';
help.push(
'- Ensure optional dependencies can be installed:',
' npm install --include=optional sharp',
'- Ensure your package manager supports multi-platform installation:',
' See https://sharp.pixelplumbing.com/install#cross-platform',
'- Add platform-specific dependencies:',
` npm install --os=${os.replace('musl', '')}${libc} --cpu=${cpu} sharp`
);
} else {
help.push(
`- Manually install libvips >= ${minimumLibvipsVersion}`,
'- Add experimental WebAssembly-based dependencies:',
' npm install --cpu=wasm32 sharp',
' npm install @img/sharp-wasm32'
);
}
if (isLinux && /(symbol not found|CXXABI_)/i.test(messages)) {
try {
const { config } = require(`@img/sharp-libvips-${runtimePlatform}/package`);
const libcFound = `${familySync()} ${versionSync()}`;
const libcRequires = `${config.musl ? 'musl' : 'glibc'} ${config.musl || config.glibc}`;
help.push(
'- Update your OS:',
` Found ${libcFound}`,
` Requires ${libcRequires}`
);
} catch (errEngines) {}
}
if (isLinux && /\/snap\/core[0-9]{2}/.test(messages)) {
help.push(
'- Remove the Node.js Snap, which does not support native modules',
' snap remove node'
);
}
if (isMacOs && /Incompatible library version/.test(messages)) {
help.push(
'- Update Homebrew:',
' brew update && brew upgrade vips'
);
}
if (errors.some(err => err.code === 'ERR_DLOPEN_DISABLED')) {
help.push('- Run Node.js without using the --no-addons flag');
}
// Link to installation docs
if (isWindows && /The specified procedure could not be found/.test(messages)) {
help.push(
'- Using the canvas package on Windows?',
' See https://sharp.pixelplumbing.com/install#canvas-and-windows',
'- Check for outdated versions of sharp in the dependency tree:',
' npm ls sharp'
);
}
help.push(
'- Consult the installation documentation:',
' See https://sharp.pixelplumbing.com/install'
);
throw new Error(help.join('\n'));
}

291
lib/utility.js Normal file
View File

@ -0,0 +1,291 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
const events = require('node:events');
const detectLibc = require('detect-libc');
const is = require('./is');
const { runtimePlatformArch } = require('./libvips');
const sharp = require('./sharp');
const runtimePlatform = runtimePlatformArch();
const libvipsVersion = sharp.libvipsVersion();
/**
* An Object containing nested boolean values representing the available input and output formats/methods.
* @member
* @example
* console.log(sharp.format);
* @returns {Object}
*/
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
* @readonly
* @enum {string}
*/
const interpolators = {
/** [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. */
nearest: 'nearest',
/** [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. */
bilinear: 'bilinear',
/** [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). */
bicubic: 'bicubic',
/** [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',
/** [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. */
nohalo: 'nohalo',
/** [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents "staircasing" when enlarging. */
vertexSplitQuadraticBasisSpline: 'vsqbs'
};
/**
* An Object containing the version numbers of sharp, libvips
* and (when using prebuilt binaries) its dependencies.
*
* @member
* @example
* console.log(sharp.versions);
*/
let versions = {
vips: libvipsVersion.semver
};
/* istanbul ignore next */
if (!libvipsVersion.isGlobal) {
if (!libvipsVersion.isWasm) {
try {
versions = require(`@img/sharp-${runtimePlatform}/versions`);
} catch (_) {
try {
versions = require(`@img/sharp-libvips-${runtimePlatform}/versions`);
} catch (_) {}
}
} else {
try {
versions = require('@img/sharp-wasm32/versions');
} catch (_) {}
}
}
versions.sharp = require('../package.json').version;
/* istanbul ignore next */
if (versions.heif && format.heif) {
// Prebuilt binaries provide AV1
format.heif.input.fileSuffix = ['.avif'];
format.heif.output.alias = ['avif'];
}
/**
* Gets or, when options are provided, sets the limits of _libvips'_ operation cache.
* Existing entries in the cache will be trimmed after any change in limits.
* This method always returns cache statistics,
* useful for determining how much working memory is required for a particular task.
*
* @example
* const stats = sharp.cache();
* @example
* sharp.cache( { items: 200 } );
* sharp.cache( { files: 0 } );
* sharp.cache(false);
*
* @param {Object|boolean} [options=true] - Object with the following attributes, or boolean where true uses default cache settings and false removes all caching
* @param {number} [options.memory=50] - is the maximum memory in MB to use for this cache
* @param {number} [options.files=20] - is the maximum number of files to hold open
* @param {number} [options.items=100] - is the maximum number of operations to cache
* @returns {Object}
*/
function cache (options) {
if (is.bool(options)) {
if (options) {
// Default cache settings of 50MB, 20 files, 100 items
return sharp.cache(50, 20, 100);
} else {
return sharp.cache(0, 0, 0);
}
} else if (is.object(options)) {
return sharp.cache(options.memory, options.files, options.items);
} else {
return sharp.cache();
}
}
cache(true);
/**
* Gets or, when a concurrency is provided, sets
* 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,
* except when using glibc-based Linux without jemalloc,
* where the default is `1` to help reduce memory fragmentation.
*
* A value of `0` will reset this to the number of CPU cores.
*
* Some image format libraries spawn additional threads,
* e.g. libaom manages its own 4 threads when encoding AVIF images,
* and these are independent of the value set here.
*
* :::note
* Further {@link /performance|control over performance} is available.
* :::
*
* @example
* const threads = sharp.concurrency(); // 4
* sharp.concurrency(2); // 2
* sharp.concurrency(0); // 4
*
* @param {number} [concurrency]
* @returns {number} concurrency
*/
function concurrency (concurrency) {
return sharp.concurrency(is.integer(concurrency) ? concurrency : null);
}
/* istanbul ignore next */
if (detectLibc.familySync() === detectLibc.GLIBC && !sharp._isUsingJemalloc()) {
// Reduce default concurrency to 1 when using glibc memory allocator
sharp.concurrency(1);
} else if (detectLibc.familySync() === detectLibc.MUSL && sharp.concurrency() === 1024) {
// Reduce default concurrency when musl thread over-subscription detected
sharp.concurrency(require('node:os').availableParallelism());
}
/**
* An EventEmitter that emits a `change` event when a task is either:
* - queued, waiting for _libuv_ to provide a worker thread
* - complete
* @member
* @example
* sharp.queue.on('change', function(queueLength) {
* console.log('Queue contains ' + queueLength + ' task(s)');
* });
*/
const queue = new events.EventEmitter();
/**
* Provides access to internal task counters.
* - queue is the number of tasks this module has queued waiting for _libuv_ to provide a worker thread from its pool.
* - process is the number of resize tasks currently being processed.
*
* @example
* const counters = sharp.counters(); // { queue: 2, process: 4 }
*
* @returns {Object}
*/
function counters () {
return sharp.counters();
}
/**
* Get and set use of SIMD vector unit instructions.
* Requires libvips to have been compiled with highway support.
*
* Improves the performance of `resize`, `blur` and `sharpen` operations
* by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.
*
* @example
* const simd = sharp.simd();
* // simd is `true` if the runtime use of highway is currently enabled
* @example
* const simd = sharp.simd(false);
* // prevent libvips from using highway at runtime
*
* @param {boolean} [simd=true]
* @returns {boolean}
*/
function simd (simd) {
return sharp.simd(is.bool(simd) ? simd : null);
}
/**
* Block libvips operations at runtime.
*
* This is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable,
* which when set will block all "untrusted" operations.
*
* @since 0.32.4
*
* @example <caption>Block all TIFF input.</caption>
* sharp.block({
* operation: ['VipsForeignLoadTiff']
* });
*
* @param {Object} options
* @param {Array<string>} options.operation - List of libvips low-level operation names to block.
*/
function block (options) {
if (is.object(options)) {
if (Array.isArray(options.operation) && options.operation.every(is.string)) {
sharp.block(options.operation, true);
} else {
throw is.invalidParameterError('operation', 'Array<string>', options.operation);
}
} else {
throw is.invalidParameterError('options', 'object', options);
}
}
/**
* Unblock libvips operations at runtime.
*
* This is useful for defining a list of allowed operations.
*
* @since 0.32.4
*
* @example <caption>Block all input except WebP from the filesystem.</caption>
* sharp.block({
* operation: ['VipsForeignLoad']
* });
* sharp.unblock({
* operation: ['VipsForeignLoadWebpFile']
* });
*
* @example <caption>Block all input except JPEG and PNG from a Buffer or Stream.</caption>
* sharp.block({
* operation: ['VipsForeignLoad']
* });
* sharp.unblock({
* operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer']
* });
*
* @param {Object} options
* @param {Array<string>} options.operation - List of libvips low-level operation names to unblock.
*/
function unblock (options) {
if (is.object(options)) {
if (Array.isArray(options.operation) && options.operation.every(is.string)) {
sharp.block(options.operation, false);
} else {
throw is.invalidParameterError('operation', 'Array<string>', options.operation);
}
} else {
throw is.invalidParameterError('options', 'object', options);
}
}
/**
* Decorate the Sharp class with utility-related functions.
* @module Sharp
* @private
*/
module.exports = function (Sharp) {
Sharp.cache = cache;
Sharp.concurrency = concurrency;
Sharp.counters = counters;
Sharp.simd = simd;
Sharp.format = format;
Sharp.interpolators = interpolators;
Sharp.versions = versions;
Sharp.queue = queue;
Sharp.block = block;
Sharp.unblock = unblock;
};

View File

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

View File

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

64
npm/from-local-build.js Normal file
View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

20
npm/package.json Normal file
View File

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

39
npm/wasm32/package.json Normal file
View File

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

View File

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

View File

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

View File

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

228
package.json Executable file → Normal file
View File

@ -1,31 +1,219 @@
{ {
"name": "sharp", "name": "sharp",
"version": "0.0.1", "description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images",
"main": "./build/Release/sharp", "version": "0.34.3-rc.0",
"description": "High performance Node.js module to resize JPEG images using the libvips image processing library", "author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com",
"contributors": [
"Pierre Inglebert <pierre.inglebert@gmail.com>",
"Jonathan Ong <jonathanrichardong@gmail.com>",
"Chanon Sajjamanochai <chanon.s@gmail.com>",
"Juliano Julio <julianojulio@gmail.com>",
"Daniel Gasienica <daniel@gasienica.ch>",
"Julian Walker <julian@fiftythree.com>",
"Amit Pitaru <pitaru.amit@gmail.com>",
"Brandon Aaron <hello.brandon@aaron.sh>",
"Andreas Lind <andreas@one.com>",
"Maurus Cuelenaere <mcuelenaere@gmail.com>",
"Linus Unnebäck <linus@folkdatorn.se>",
"Victor Mateevitsi <mvictoras@gmail.com>",
"Alaric Holloway <alaric.holloway@gmail.com>",
"Bernhard K. Weisshuhn <bkw@codingforce.com>",
"Chris Riley <criley@primedia.com>",
"David Carley <dacarley@gmail.com>",
"John Tobin <john@limelightmobileinc.com>",
"Kenton Gray <kentongray@gmail.com>",
"Felix Bünemann <Felix.Buenemann@gmail.com>",
"Samy Al Zahrani <samyalzahrany@gmail.com>",
"Chintan Thakkar <lemnisk8@gmail.com>",
"F. Orlando Galashan <frulo@gmx.de>",
"Kleis Auke Wolthuizen <info@kleisauke.nl>",
"Matt Hirsch <mhirsch@media.mit.edu>",
"Matthias Thoemmes <thoemmes@gmail.com>",
"Patrick Paskaris <patrick@paskaris.gr>",
"Jérémy Lal <kapouer@melix.org>",
"Rahul Nanwani <r.nanwani@gmail.com>",
"Alice Monday <alice0meta@gmail.com>",
"Kristo Jorgenson <kristo.jorgenson@gmail.com>",
"YvesBos <yves_bos@outlook.com>",
"Guy Maliar <guy@tailorbrands.com>",
"Nicolas Coden <nicolas@ncoden.fr>",
"Matt Parrish <matt.r.parrish@gmail.com>",
"Marcel Bretschneider <marcel.bretschneider@gmail.com>",
"Matthew McEachen <matthew+github@mceachen.org>",
"Jarda Kotěšovec <jarda.kotesovec@gmail.com>",
"Kenric D'Souza <kenric.dsouza@gmail.com>",
"Oleh Aleinyk <oleg.aleynik@gmail.com>",
"Marcel Bretschneider <marcel.bretschneider@gmail.com>",
"Andrea Bianco <andrea.bianco@unibas.ch>",
"Rik Heywood <rik@rik.org>",
"Thomas Parisot <hi@oncletom.io>",
"Nathan Graves <nathanrgraves+github@gmail.com>",
"Tom Lokhorst <tom@lokhorst.eu>",
"Espen Hovlandsdal <espen@hovlandsdal.com>",
"Sylvain Dumont <sylvain.dumont35@gmail.com>",
"Alun Davies <alun.owain.davies@googlemail.com>",
"Aidan Hoolachan <ajhoolachan21@gmail.com>",
"Axel Eirola <axel.eirola@iki.fi>",
"Freezy <freezy@xbmc.org>",
"Daiz <taneli.vatanen@gmail.com>",
"Julian Aubourg <j@ubourg.net>",
"Keith Belovay <keith@picthrive.com>",
"Michael B. Klein <mbklein@gmail.com>",
"Jordan Prudhomme <jordan@raboland.fr>",
"Ilya Ovdin <iovdin@gmail.com>",
"Andargor <andargor@yahoo.com>",
"Paul Neave <paul.neave@gmail.com>",
"Brendan Kennedy <brenwken@gmail.com>",
"Brychan Bennett-Odlum <git@brychan.io>",
"Edward Silverton <e.silverton@gmail.com>",
"Roman Malieiev <aromaleev@gmail.com>",
"Tomas Szabo <tomas.szabo@deftomat.com>",
"Robert O'Rourke <robert@o-rourke.org>",
"Guillermo Alfonso Varela Chouciño <guillevch@gmail.com>",
"Christian Flintrup <chr@gigahost.dk>",
"Manan Jadhav <manan@motionden.com>",
"Leon Radley <leon@radley.se>",
"alza54 <alza54@thiocod.in>",
"Jacob Smith <jacob@frende.me>",
"Michael Nutt <michael@nutt.im>",
"Brad Parham <baparham@gmail.com>",
"Taneli Vatanen <taneli.vatanen@gmail.com>",
"Joris Dugué <zaruike10@gmail.com>",
"Chris Banks <christopher.bradley.banks@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>",
"Lachlan Newman <lachnewman007@gmail.com>",
"Dennis Beatty <dennis@dcbeatty.com>",
"Ingvar Stepanyan <me@rreverser.com>",
"Don Denton <don@happycollision.com>"
],
"scripts": {
"install": "node install/check.js",
"clean": "rm -rf src/build/ .nyc_output/ coverage/ test/fixtures/output.*",
"test": "npm run test-lint && npm run test-unit && npm run test-licensing && npm run test-types",
"test-lint": "semistandard && cpplint",
"test-unit": "nyc --reporter=lcov --reporter=text --check-coverage --branches=100 mocha",
"test-licensing": "license-checker --production --summary --onlyAllow=\"Apache-2.0;BSD;ISC;LGPL-3.0-or-later;MIT\"",
"test-leak": "./test/leak/leak.sh",
"test-types": "tsd",
"package-from-local-build": "node npm/from-local-build.js",
"docs-build": "node docs/build.mjs",
"docs-serve": "cd docs && npm start",
"docs-publish": "cd docs && npm run build && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp"
},
"type": "commonjs",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"files": [
"install",
"lib",
"src/*.{cc,h,gyp}"
],
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git://github.com/lovell/sharp" "url": "git://github.com/lovell/sharp.git"
},
"devDependencies": {
"imagemagick": "*"
},
"scripts": {
"test": "node tests/perf.js"
},
"engines": {
"node": "*"
}, },
"keywords": [ "keywords": [
"jpeg", "jpeg",
"png",
"webp",
"avif",
"tiff",
"gif",
"svg",
"jp2",
"dzi",
"image",
"resize", "resize",
"thumbnail", "thumbnail",
"sharpen", "crop",
"crop", "embed",
"embed",
"libvips", "libvips",
"fast" "vips"
], ],
"author": "Lovell Fuller", "dependencies": {
"license": "Apache 2.0" "color": "^4.2.3",
} "detect-libc": "^2.0.4",
"semver": "^7.7.2"
},
"optionalDependencies": {
"@img/sharp-darwin-arm64": "0.34.3-rc.0",
"@img/sharp-darwin-x64": "0.34.3-rc.0",
"@img/sharp-libvips-darwin-arm64": "1.2.0",
"@img/sharp-libvips-darwin-x64": "1.2.0",
"@img/sharp-libvips-linux-arm": "1.2.0",
"@img/sharp-libvips-linux-arm64": "1.2.0",
"@img/sharp-libvips-linux-ppc64": "1.2.0",
"@img/sharp-libvips-linux-s390x": "1.2.0",
"@img/sharp-libvips-linux-x64": "1.2.0",
"@img/sharp-libvips-linuxmusl-arm64": "1.2.0",
"@img/sharp-libvips-linuxmusl-x64": "1.2.0",
"@img/sharp-linux-arm": "0.34.3-rc.0",
"@img/sharp-linux-arm64": "0.34.3-rc.0",
"@img/sharp-linux-ppc64": "0.34.3-rc.0",
"@img/sharp-linux-s390x": "0.34.3-rc.0",
"@img/sharp-linux-x64": "0.34.3-rc.0",
"@img/sharp-linuxmusl-arm64": "0.34.3-rc.0",
"@img/sharp-linuxmusl-x64": "0.34.3-rc.0",
"@img/sharp-wasm32": "0.34.3-rc.0",
"@img/sharp-win32-arm64": "0.34.3-rc.0",
"@img/sharp-win32-ia32": "0.34.3-rc.0",
"@img/sharp-win32-x64": "0.34.3-rc.0"
},
"devDependencies": {
"@emnapi/runtime": "^1.4.4",
"@img/sharp-libvips-dev": "1.2.0",
"@img/sharp-libvips-dev-wasm32": "1.2.0",
"@img/sharp-libvips-win32-arm64": "1.2.0",
"@img/sharp-libvips-win32-ia32": "1.2.0",
"@img/sharp-libvips-win32-x64": "1.2.0",
"@types/node": "*",
"cc": "^3.0.1",
"emnapi": "^1.4.4",
"exif-reader": "^2.0.2",
"extract-zip": "^2.0.1",
"icc": "^3.0.0",
"jsdoc-to-markdown": "^9.1.1",
"license-checker": "^25.0.1",
"mocha": "^11.7.1",
"node-addon-api": "^8.4.0",
"node-gyp": "^11.2.0",
"nyc": "^17.1.0",
"semistandard": "^17.0.0",
"tar-fs": "^3.1.0",
"tsd": "^0.32.0"
},
"license": "Apache-2.0",
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"config": {
"libvips": ">=8.17.1"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"semistandard": {
"env": [
"mocha"
]
},
"cc": {
"linelength": "120",
"filter": [
"build/include"
]
},
"nyc": {
"include": [
"lib"
]
},
"tsd": {
"directory": "test/types/"
}
}

299
src/binding.gyp Normal file
View File

@ -0,0 +1,299 @@
# Copyright 2013 Lovell Fuller and others.
# SPDX-License-Identifier: Apache-2.0
{
'variables': {
'vips_version': '<!(node -p "require(\'../lib/libvips\').minimumLibvipsVersion")',
'platform_and_arch': '<!(node -p "require(\'../lib/libvips\').buildPlatformArch()")',
'sharp_libvips_version': '<!(node -p "require(\'../package.json\').optionalDependencies[\'@img/sharp-libvips-<(platform_and_arch)\']")',
'sharp_libvips_yarn_locator': '<!(node -p "require(\'../lib/libvips\').yarnLocator()")',
'sharp_libvips_include_dir': '<!(node -p "require(\'../lib/libvips\').buildSharpLibvipsIncludeDir()")',
'sharp_libvips_cplusplus_dir': '<!(node -p "require(\'../lib/libvips\').buildSharpLibvipsCPlusPlusDir()")',
'sharp_libvips_lib_dir': '<!(node -p "require(\'../lib/libvips\').buildSharpLibvipsLibDir()")'
},
'targets': [{
'target_name': 'libvips-cpp-<(vips_version)',
'conditions': [
['OS == "win"', {
# Build libvips C++ binding for Windows due to MSVC std library ABI changes
'type': 'shared_library',
'defines': [
'_VIPS_PUBLIC=__declspec(dllexport)',
'_ALLOW_KEYWORD_MACROS',
'G_DISABLE_ASSERT',
'G_DISABLE_CAST_CHECKS',
'G_DISABLE_CHECKS'
],
'sources': [
'<(sharp_libvips_cplusplus_dir)/VConnection.cpp',
'<(sharp_libvips_cplusplus_dir)/VError.cpp',
'<(sharp_libvips_cplusplus_dir)/VImage.cpp',
'<(sharp_libvips_cplusplus_dir)/VInterpolate.cpp',
'<(sharp_libvips_cplusplus_dir)/VRegion.cpp'
],
'include_dirs': [
'<(sharp_libvips_include_dir)',
'<(sharp_libvips_include_dir)/glib-2.0',
'<(sharp_libvips_lib_dir)/glib-2.0/include'
],
'link_settings': {
'library_dirs': [
'<(sharp_libvips_lib_dir)'
],
'libraries': [
'libvips.lib'
],
},
'configurations': {
'Release': {
'msvs_settings': {
'VCCLCompilerTool': {
"AdditionalOptions": [
"/std:c++17"
],
'ExceptionHandling': 1,
'Optimization': 1,
'WholeProgramOptimization': 'true'
},
'VCLibrarianTool': {
'AdditionalOptions': [
'/LTCG:INCREMENTAL'
]
},
'VCLinkerTool': {
'ImageHasSafeExceptionHandlers': 'false',
'OptimizeReferences': 2,
'EnableCOMDATFolding': 2,
'LinkIncremental': 1,
'AdditionalOptions': [
'/LTCG:INCREMENTAL'
]
}
},
'msvs_disabled_warnings': [
4275
]
}
}
}, {
# Ignore this target for non-Windows
'type': 'none'
}]
]
}, {
'target_name': 'sharp-<(platform_and_arch)',
'defines': [
'G_DISABLE_ASSERT',
'G_DISABLE_CAST_CHECKS',
'G_DISABLE_CHECKS',
'NAPI_VERSION=9',
'NODE_ADDON_API_DISABLE_DEPRECATED',
'NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS'
],
'dependencies': [
'<!(node -p "require(\'node-addon-api\').gyp")',
'libvips-cpp-<(vips_version)'
],
'variables': {
'conditions': [
['OS != "win"', {
'pkg_config_path': '<!(node -p "require(\'../lib/libvips\').pkgConfigPath()")',
'use_global_libvips': '<!(node -p "Boolean(require(\'../lib/libvips\').useGlobalLibvips()).toString()")'
}, {
'pkg_config_path': '',
'use_global_libvips': ''
}]
]
},
'sources': [
'common.cc',
'metadata.cc',
'stats.cc',
'operations.cc',
'pipeline.cc',
'utilities.cc',
'sharp.cc'
],
'include_dirs': [
'<!(node -p "require(\'node-addon-api\').include_dir")',
],
'conditions': [
['use_global_libvips == "true"', {
# Use pkg-config for include and lib
'include_dirs': ['<!@(PKG_CONFIG_PATH="<(pkg_config_path)" pkg-config --cflags-only-I vips-cpp vips glib-2.0 | sed s\/-I//g)'],
'libraries': ['<!@(PKG_CONFIG_PATH="<(pkg_config_path)" pkg-config --libs vips-cpp)'],
'defines': [
'SHARP_USE_GLOBAL_LIBVIPS'
],
'conditions': [
['OS == "linux"', {
'defines': [
# Inspect libvips-cpp.so to determine which C++11 ABI version was used and set _GLIBCXX_USE_CXX11_ABI accordingly. This is quite horrible.
'_GLIBCXX_USE_CXX11_ABI=<!(if readelf -Ws "$(PKG_CONFIG_PATH="<(pkg_config_path)" pkg-config --variable libdir vips-cpp)/libvips-cpp.so" | c++filt | grep -qF __cxx11;then echo "1";else echo "0";fi)'
]
}]
]
}, {
# Use pre-built libvips stored locally within node_modules
'include_dirs': [
'<(sharp_libvips_include_dir)',
'<(sharp_libvips_include_dir)/glib-2.0',
'<(sharp_libvips_lib_dir)/glib-2.0/include'
],
'library_dirs': [
'<(sharp_libvips_lib_dir)'
],
'conditions': [
['OS == "win"', {
'defines': [
'_ALLOW_KEYWORD_MACROS',
'_FILE_OFFSET_BITS=64'
],
'link_settings': {
'libraries': [
'libvips.lib'
]
}
}],
['OS == "mac"', {
'link_settings': {
'libraries': [
'libvips-cpp.<(vips_version).dylib'
]
},
'xcode_settings': {
'OTHER_LDFLAGS': [
'-Wl,-s',
'-Wl,-dead_strip',
# Ensure runtime linking is relative to sharp.node
'-Wl,-rpath,\'@loader_path/../../sharp-libvips-<(platform_and_arch)/lib\'',
'-Wl,-rpath,\'@loader_path/../../../sharp-libvips-<(platform_and_arch)/<(sharp_libvips_version)/lib\'',
'-Wl,-rpath,\'@loader_path/../../node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\'',
'-Wl,-rpath,\'@loader_path/../../../node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\'',
'-Wl,-rpath,\'@loader_path/../../../../../@img-sharp-libvips-<(platform_and_arch)-npm-<(sharp_libvips_version)-<(sharp_libvips_yarn_locator)/node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\''
]
}
}],
['OS == "linux"', {
'defines': [
'_GLIBCXX_USE_CXX11_ABI=1'
],
'cflags_cc': [
'<!(node -p "require(\'detect-libc\').isNonGlibcLinuxSync() ? \'\' : \'-flto=auto\'")'
],
'link_settings': {
'libraries': [
'-l:libvips-cpp.so.<(vips_version)'
],
'ldflags': [
'-lstdc++fs',
'-Wl,-s',
'-Wl,--disable-new-dtags',
'-Wl,-z,nodelete',
'-Wl,-Bsymbolic-functions',
'-Wl,-rpath=\'$$ORIGIN/../../sharp-libvips-<(platform_and_arch)/lib\'',
'-Wl,-rpath=\'$$ORIGIN/../../../sharp-libvips-<(platform_and_arch)/<(sharp_libvips_version)/lib\'',
'-Wl,-rpath=\'$$ORIGIN/../../node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\'',
'-Wl,-rpath=\'$$ORIGIN/../../../node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\'',
'-Wl,-rpath,\'$$ORIGIN/../../../../../@img-sharp-libvips-<(platform_and_arch)-npm-<(sharp_libvips_version)-<(sharp_libvips_yarn_locator)/node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\''
]
}
}],
['OS == "emscripten"', {
'product_extension': 'node.js',
'link_settings': {
'ldflags': [
'-fexceptions',
'--pre-js=<!(node -p "require.resolve(\'./emscripten/pre.js\')")',
'-Oz',
'-sALLOW_MEMORY_GROWTH',
'-sENVIRONMENT=node',
'-sEXPORTED_FUNCTIONS=["emnapiInit", "_vips_shutdown", "_uv_library_shutdown"]',
'-sNODERAWFS',
'-sTEXTDECODER=0',
'-sWASM_ASYNC_COMPILATION=0',
'-sWASM_BIGINT'
],
'libraries': [
'<!@(PKG_CONFIG_PATH="<!(node -p "require(\'@img/sharp-libvips-dev-wasm32/lib\')")/pkgconfig" pkg-config --static --libs vips-cpp)'
],
}
}]
]
}]
],
'cflags_cc': [
'-std=c++17',
'-fexceptions',
'-Wall',
'-Os'
],
'xcode_settings': {
'CLANG_CXX_LANGUAGE_STANDARD': 'c++17',
'MACOSX_DEPLOYMENT_TARGET': '10.15',
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
'GCC_ENABLE_CPP_RTTI': 'YES',
'OTHER_CPLUSPLUSFLAGS': [
'-fexceptions',
'-Wall',
'-Oz'
]
},
'configurations': {
'Release': {
'conditions': [
['target_arch == "arm"', {
'cflags_cc': [
'-Wno-psabi'
]
}],
['OS == "win"', {
'msvs_settings': {
'VCCLCompilerTool': {
"AdditionalOptions": [
"/std:c++17"
],
'ExceptionHandling': 1,
'Optimization': 1,
'WholeProgramOptimization': 'true'
},
'VCLibrarianTool': {
'AdditionalOptions': [
'/LTCG:INCREMENTAL'
]
},
'VCLinkerTool': {
'ImageHasSafeExceptionHandlers': 'false',
'OptimizeReferences': 2,
'EnableCOMDATFolding': 2,
'LinkIncremental': 1,
'AdditionalOptions': [
'/LTCG:INCREMENTAL'
]
}
},
'msvs_disabled_warnings': [
4275
]
}]
]
}
},
}, {
'target_name': 'copy-dll',
'type': 'none',
'dependencies': [
'sharp-<(platform_and_arch)'
],
'conditions': [
['OS == "win"', {
'copies': [{
'destination': 'build/Release',
'files': [
'<(sharp_libvips_lib_dir)/libvips-42.dll'
]
}]
}]
]
}]
}

1125
src/common.cc Normal file

File diff suppressed because it is too large Load Diff

399
src/common.h Normal file
View File

@ -0,0 +1,399 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
#ifndef SRC_COMMON_H_
#define SRC_COMMON_H_
#include <string>
#include <tuple>
#include <vector>
#include <atomic>
#include <napi.h>
#include <vips/vips8>
// Verify platform and compiler compatibility
#if (VIPS_MAJOR_VERSION < 8) || \
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION < 17) || \
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION == 17 && VIPS_MICRO_VERSION < 1)
#error "libvips version 8.17.1+ is required - please see https://sharp.pixelplumbing.com/install"
#endif
#if defined(__has_include)
#if !__has_include(<filesystem>)
#error "C++17 compiler required - please see https://sharp.pixelplumbing.com/install"
#endif
#endif
using vips::VImage;
namespace sharp {
struct InputDescriptor { // NOLINT(runtime/indentation_namespace)
std::string name;
std::string file;
bool autoOrient;
char *buffer;
VipsFailOn failOn;
uint64_t limitInputPixels;
bool unlimited;
VipsAccess access;
size_t bufferLength;
bool isBuffer;
double density;
bool ignoreIcc;
VipsBandFormat rawDepth;
int rawChannels;
int rawWidth;
int rawHeight;
bool rawPremultiplied;
int rawPageHeight;
int pages;
int page;
int createChannels;
int createWidth;
int createHeight;
int createPageHeight;
std::vector<double> createBackground;
std::string createNoiseType;
double createNoiseMean;
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;
VipsTextWrap textWrap;
int textAutofitDpi;
bool joinAnimated;
int joinAcross;
int joinShim;
std::vector<double> joinBackground;
VipsAlign joinHalign;
VipsAlign joinValign;
std::string svgStylesheet;
bool svgHighBitdepth;
int tiffSubifd;
int openSlideLevel;
std::vector<double> pdfBackground;
bool jp2Oneshot;
InputDescriptor():
autoOrient(false),
buffer(nullptr),
failOn(VIPS_FAIL_ON_WARNING),
limitInputPixels(0x3FFF * 0x3FFF),
unlimited(false),
access(VIPS_ACCESS_SEQUENTIAL),
bufferLength(0),
isBuffer(false),
density(72.0),
ignoreIcc(false),
rawDepth(VIPS_FORMAT_UCHAR),
rawChannels(0),
rawWidth(0),
rawHeight(0),
rawPremultiplied(false),
rawPageHeight(0),
pages(1),
page(0),
createChannels(0),
createWidth(0),
createHeight(0),
createPageHeight(0),
createBackground{ 0.0, 0.0, 0.0, 255.0 },
createNoiseMean(0.0),
createNoiseSigma(0.0),
textWidth(0),
textHeight(0),
textAlign(VIPS_ALIGN_LOW),
textJustify(false),
textDpi(72),
textRgba(false),
textSpacing(0),
textWrap(VIPS_TEXT_WRAP_WORD),
textAutofitDpi(0),
joinAnimated(false),
joinAcross(1),
joinShim(0),
joinBackground{ 0.0, 0.0, 0.0, 255.0 },
joinHalign(VIPS_ALIGN_LOW),
joinValign(VIPS_ALIGN_LOW),
svgHighBitdepth(false),
tiffSubifd(-1),
openSlideLevel(0),
pdfBackground{ 255.0, 255.0, 255.0, 255.0 },
jp2Oneshot(false) {}
};
// Convenience methods to access the attributes of a Napi::Object
bool HasAttr(Napi::Object obj, std::string attr);
std::string AttrAsStr(Napi::Object obj, std::string attr);
std::string AttrAsStr(Napi::Object obj, unsigned int const attr);
uint32_t AttrAsUint32(Napi::Object obj, std::string attr);
int32_t AttrAsInt32(Napi::Object obj, std::string attr);
int32_t AttrAsInt32(Napi::Object obj, unsigned int const attr);
double AttrAsDouble(Napi::Object obj, std::string attr);
double AttrAsDouble(Napi::Object obj, unsigned int const attr);
bool AttrAsBool(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);
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()));
}
// Create an InputDescriptor instance from a Napi::Object describing an input image
InputDescriptor* CreateInputDescriptor(Napi::Object input);
enum class ImageType {
JPEG,
PNG,
WEBP,
JP2,
TIFF,
GIF,
SVG,
HEIF,
PDF,
MAGICK,
OPENSLIDE,
PPM,
FITS,
EXR,
JXL,
RAD,
DCRAW,
VIPS,
RAW,
UNKNOWN,
MISSING
};
enum class Canvas {
CROP,
EMBED,
MAX,
MIN,
IGNORE_ASPECT
};
// How many tasks are in the queue?
extern std::atomic<int> counterQueue;
// How many tasks are being processed?
extern std::atomic<int> counterProcess;
// Filename extension checkers
bool IsJpeg(std::string const &str);
bool IsPng(std::string const &str);
bool IsWebp(std::string const &str);
bool IsJp2(std::string const &str);
bool IsGif(std::string const &str);
bool IsTiff(std::string const &str);
bool IsHeic(std::string const &str);
bool IsHeif(std::string const &str);
bool IsAvif(std::string const &str);
bool IsJxl(std::string const &str);
bool IsDz(std::string const &str);
bool IsDzZip(std::string const &str);
bool IsV(std::string const &str);
/*
Trim space from end of string.
*/
std::string TrimEnd(std::string const &str);
/*
Provide a string identifier for the given image type.
*/
std::string ImageTypeId(ImageType const imageType);
/*
Determine image format of a buffer.
*/
ImageType DetermineImageType(void *buffer, size_t const length);
/*
Determine image format of a file.
*/
ImageType DetermineImageType(char const *file);
/*
Format-specific options builder
*/
vips::VOption* GetOptionsForImageType(ImageType imageType, InputDescriptor *descriptor);
/*
Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data)
*/
std::tuple<VImage, ImageType> OpenInput(InputDescriptor *descriptor);
/*
Does this image have an embedded profile?
*/
bool HasProfile(VImage image);
/*
Get copy of embedded profile.
*/
std::pair<char*, size_t> GetProfile(VImage image);
/*
Set embedded profile.
*/
VImage SetProfile(VImage image, std::pair<char*, size_t> icc);
/*
Remove all EXIF-related image fields.
*/
VImage RemoveExif(VImage image);
/*
Get EXIF Orientation of image, if any.
*/
int ExifOrientation(VImage image);
/*
Set EXIF Orientation of image.
*/
VImage SetExifOrientation(VImage image, int const orientation);
/*
Remove EXIF Orientation from image.
*/
VImage RemoveExifOrientation(VImage image);
/*
Set animation properties if necessary.
*/
VImage SetAnimationProperties(VImage image, int nPages, int pageHeight, std::vector<int> delay, int loop);
/*
Remove animation properties from image.
*/
VImage RemoveAnimationProperties(VImage image);
/*
Remove GIF palette from image.
*/
VImage RemoveGifPalette(VImage image);
/*
Does this image have a non-default density?
*/
bool HasDensity(VImage image);
/*
Get pixels/mm resolution as pixels/inch density.
*/
int GetDensity(VImage image);
/*
Set pixels/mm resolution based on a pixels/inch density.
*/
VImage SetDensity(VImage image, const double density);
/*
Multi-page images can have a page height. Fetch it, and sanity check it.
If page-height is not set, it defaults to the image height
*/
int GetPageHeight(VImage image);
/*
Check the proposed format supports the current dimensions.
*/
void AssertImageTypeDimensions(VImage image, ImageType const imageType);
/*
Called when a Buffer undergoes GC, required to support mixed runtime libraries in Windows
*/
extern std::function<void(void*, char*)> FreeCallback;
/*
Called with warnings from the glib-registered "VIPS" domain
*/
void VipsWarningCallback(char const* log_domain, GLogLevelFlags log_level, char const* message, void* ignore);
/*
Pop the oldest warning message from the queue
*/
std::string VipsWarningPop();
/*
Attach an event listener for progress updates, used to detect timeout
*/
void SetTimeout(VImage image, int const timeoutSeconds);
/*
Event listener for progress updates, used to detect timeout
*/
void VipsProgressCallBack(VipsImage *image, VipsProgress *progress, int *timeoutSeconds);
/*
Calculate the (left, top) coordinates of the output image
within the input image, applying the given gravity during an embed.
*/
std::tuple<int, int> CalculateEmbedPosition(int const inWidth, int const inHeight,
int const outWidth, int const outHeight, int const gravity);
/*
Calculate the (left, top) coordinates of the output image
within the input image, applying the given gravity.
*/
std::tuple<int, int> CalculateCrop(int const inWidth, int const inHeight,
int const outWidth, int const outHeight, int const gravity);
/*
Calculate the (left, top) coordinates of the output image
within the input image, applying the given x and y offsets of the output image.
*/
std::tuple<int, int> CalculateCrop(int const inWidth, int const inHeight,
int const outWidth, int const outHeight, int const x, int const y);
/*
Are pixel values in this image 16-bit integer?
*/
bool Is16Bit(VipsInterpretation const interpretation);
/*
Convert RGBA value to another colourspace
*/
std::vector<double> GetRgbaAsColourspace(std::vector<double> const rgba,
VipsInterpretation const interpretation, bool premultiply);
/*
Apply the alpha channel to a given colour
*/
std::tuple<VImage, std::vector<double>> ApplyAlpha(VImage image, std::vector<double> colour, bool premultiply);
/*
Removes alpha channels, if any.
*/
VImage RemoveAlpha(VImage image);
/*
Ensures alpha channel, if missing.
*/
VImage EnsureAlpha(VImage image, double const value);
/*
Calculate the horizontal and vertical shrink factors, taking the canvas mode into account.
*/
std::pair<double, double> ResolveShrink(int width, int height, int targetWidth, int targetHeight,
Canvas canvas, bool withoutEnlargement, bool withoutReduction);
/*
Ensure decoding remains sequential.
*/
VImage StaySequential(VImage image, bool condition = true);
} // namespace sharp
#endif // SRC_COMMON_H_

View File

@ -0,0 +1,40 @@
# Copyright 2013 Lovell Fuller and others.
# SPDX-License-Identifier: Apache-2.0
{
'variables': {
'OS': 'emscripten'
},
'target_defaults': {
'default_configuration': 'Release',
'type': 'executable',
'cflags': [
'-pthread'
],
'cflags_cc': [
'-pthread'
],
'ldflags': [
'--js-library=<!(node -p "require(\'emnapi\').js_library")',
'-sAUTO_JS_LIBRARIES=0',
'-sAUTO_NATIVE_LIBRARIES=0',
'-sDEFAULT_TO_CXX=0',
'-sNODEJS_CATCH_EXIT=0',
'-sNODEJS_CATCH_REJECTION=0'
],
'defines': [
'__STDC_FORMAT_MACROS',
'BUILDING_NODE_EXTENSION',
'EMNAPI_WORKER_POOL_SIZE=1'
],
'include_dirs': [
'<!(node -p "require(\'emnapi\').include_dir")'
],
'sources': [
'<!@(node -p "require(\'emnapi\').sources.map(x => JSON.stringify(path.relative(process.cwd(), x))).join(\' \')")'
],
'configurations': {
'Release': {}
}
}
}

19
src/emscripten/pre.js Normal file
View File

@ -0,0 +1,19 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
/* global Module, ENV, _vips_shutdown, _uv_library_shutdown */
Module.preRun = () => {
ENV.VIPS_CONCURRENCY = Number(process.env.VIPS_CONCURRENCY) || 1;
};
Module.onRuntimeInitialized = () => {
module.exports = Module.emnapiInit({
context: require('@emnapi/runtime').getDefaultContext()
});
process.once('exit', () => {
_vips_shutdown();
_uv_library_shutdown();
});
};

342
src/metadata.cc Normal file
View File

@ -0,0 +1,342 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
#include <numeric>
#include <vector>
#include <cmath>
#include <napi.h>
#include <vips/vips8>
#include "common.h"
#include "metadata.h"
static void* readPNGComment(VipsImage *image, const char *field, GValue *value, void *p);
class MetadataWorker : public Napi::AsyncWorker {
public:
MetadataWorker(Napi::Function callback, MetadataBaton *baton, Napi::Function debuglog) :
Napi::AsyncWorker(callback), baton(baton), debuglog(Napi::Persistent(debuglog)) {}
~MetadataWorker() {}
void Execute() {
// Decrement queued task counter
sharp::counterQueue--;
vips::VImage image;
sharp::ImageType imageType = sharp::ImageType::UNKNOWN;
try {
std::tie(image, imageType) = OpenInput(baton->input);
} catch (vips::VError const &err) {
(baton->err).append(err.what());
}
if (imageType != sharp::ImageType::UNKNOWN) {
// Image type
baton->format = sharp::ImageTypeId(imageType);
// VipsImage attributes
baton->width = image.width();
baton->height = image.height();
baton->space = vips_enum_nick(VIPS_TYPE_INTERPRETATION, image.interpretation());
baton->channels = image.bands();
baton->depth = vips_enum_nick(VIPS_TYPE_BAND_FORMAT, image.format());
if (sharp::HasDensity(image)) {
baton->density = sharp::GetDensity(image);
}
if (image.get_typeof("jpeg-chroma-subsample") == VIPS_TYPE_REF_STRING) {
baton->chromaSubsampling = image.get_string("jpeg-chroma-subsample");
}
if (image.get_typeof("interlaced") == G_TYPE_INT) {
baton->isProgressive = image.get_int("interlaced") == 1;
}
if (image.get_typeof(VIPS_META_PALETTE) == G_TYPE_INT) {
baton->isPalette = image.get_int(VIPS_META_PALETTE);
}
if (image.get_typeof(VIPS_META_BITS_PER_SAMPLE) == G_TYPE_INT) {
baton->bitsPerSample = image.get_int(VIPS_META_BITS_PER_SAMPLE);
}
if (image.get_typeof(VIPS_META_N_PAGES) == G_TYPE_INT) {
baton->pages = image.get_int(VIPS_META_N_PAGES);
}
if (image.get_typeof(VIPS_META_PAGE_HEIGHT) == G_TYPE_INT) {
baton->pageHeight = image.get_int(VIPS_META_PAGE_HEIGHT);
}
if (image.get_typeof("loop") == G_TYPE_INT) {
baton->loop = image.get_int("loop");
}
if (image.get_typeof("delay") == VIPS_TYPE_ARRAY_INT) {
baton->delay = image.get_array_int("delay");
}
if (image.get_typeof("heif-primary") == G_TYPE_INT) {
baton->pagePrimary = image.get_int("heif-primary");
}
if (image.get_typeof("heif-compression") == VIPS_TYPE_REF_STRING) {
baton->compression = image.get_string("heif-compression");
}
if (image.get_typeof(VIPS_META_RESOLUTION_UNIT) == VIPS_TYPE_REF_STRING) {
baton->resolutionUnit = image.get_string(VIPS_META_RESOLUTION_UNIT);
}
if (image.get_typeof("magick-format") == VIPS_TYPE_REF_STRING) {
baton->formatMagick = image.get_string("magick-format");
}
if (image.get_typeof("openslide.level-count") == VIPS_TYPE_REF_STRING) {
int const levels = std::stoi(image.get_string("openslide.level-count"));
for (int l = 0; l < levels; l++) {
std::string prefix = "openslide.level[" + std::to_string(l) + "].";
int const width = std::stoi(image.get_string((prefix + "width").data()));
int const height = std::stoi(image.get_string((prefix + "height").data()));
baton->levels.push_back(std::pair<int, int>(width, height));
}
}
if (image.get_typeof(VIPS_META_N_SUBIFDS) == G_TYPE_INT) {
baton->subifds = image.get_int(VIPS_META_N_SUBIFDS);
}
baton->hasProfile = sharp::HasProfile(image);
if (image.get_typeof("background") == VIPS_TYPE_ARRAY_DOUBLE) {
baton->background = image.get_array_double("background");
}
// Derived attributes
baton->hasAlpha = image.has_alpha();
baton->orientation = sharp::ExifOrientation(image);
// EXIF
if (image.get_typeof(VIPS_META_EXIF_NAME) == VIPS_TYPE_BLOB) {
size_t exifLength;
void const *exif = image.get_blob(VIPS_META_EXIF_NAME, &exifLength);
baton->exif = static_cast<char*>(g_malloc(exifLength));
memcpy(baton->exif, exif, exifLength);
baton->exifLength = exifLength;
}
// ICC profile
if (image.get_typeof(VIPS_META_ICC_NAME) == VIPS_TYPE_BLOB) {
size_t iccLength;
void const *icc = image.get_blob(VIPS_META_ICC_NAME, &iccLength);
baton->icc = static_cast<char*>(g_malloc(iccLength));
memcpy(baton->icc, icc, iccLength);
baton->iccLength = iccLength;
}
// IPTC
if (image.get_typeof(VIPS_META_IPTC_NAME) == VIPS_TYPE_BLOB) {
size_t iptcLength;
void const *iptc = image.get_blob(VIPS_META_IPTC_NAME, &iptcLength);
baton->iptc = static_cast<char *>(g_malloc(iptcLength));
memcpy(baton->iptc, iptc, iptcLength);
baton->iptcLength = iptcLength;
}
// XMP
if (image.get_typeof(VIPS_META_XMP_NAME) == VIPS_TYPE_BLOB) {
size_t xmpLength;
void const *xmp = image.get_blob(VIPS_META_XMP_NAME, &xmpLength);
baton->xmp = static_cast<char *>(g_malloc(xmpLength));
memcpy(baton->xmp, xmp, xmpLength);
baton->xmpLength = xmpLength;
}
// TIFFTAG_PHOTOSHOP
if (image.get_typeof(VIPS_META_PHOTOSHOP_NAME) == VIPS_TYPE_BLOB) {
size_t tifftagPhotoshopLength;
void const *tifftagPhotoshop = image.get_blob(VIPS_META_PHOTOSHOP_NAME, &tifftagPhotoshopLength);
baton->tifftagPhotoshop = static_cast<char *>(g_malloc(tifftagPhotoshopLength));
memcpy(baton->tifftagPhotoshop, tifftagPhotoshop, tifftagPhotoshopLength);
baton->tifftagPhotoshopLength = tifftagPhotoshopLength;
}
// PNG comments
vips_image_map(image.get_image(), readPNGComment, &baton->comments);
}
// Clean up
vips_error_clear();
vips_thread_shutdown();
}
void OnOK() {
Napi::Env env = Env();
Napi::HandleScope scope(env);
// Handle warnings
std::string warning = sharp::VipsWarningPop();
while (!warning.empty()) {
debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) });
warning = sharp::VipsWarningPop();
}
if (baton->err.empty()) {
Napi::Object info = Napi::Object::New(env);
info.Set("format", baton->format);
if (baton->input->bufferLength > 0) {
info.Set("size", baton->input->bufferLength);
}
info.Set("width", baton->width);
info.Set("height", baton->height);
info.Set("space", baton->space);
info.Set("channels", baton->channels);
info.Set("depth", baton->depth);
if (baton->density > 0) {
info.Set("density", baton->density);
}
if (!baton->chromaSubsampling.empty()) {
info.Set("chromaSubsampling", baton->chromaSubsampling);
}
info.Set("isProgressive", baton->isProgressive);
info.Set("isPalette", baton->isPalette);
if (baton->bitsPerSample > 0) {
info.Set("bitsPerSample", baton->bitsPerSample);
if (baton->isPalette) {
// Deprecated, remove with libvips 8.17.0
info.Set("paletteBitDepth", baton->bitsPerSample);
}
}
if (baton->pages > 0) {
info.Set("pages", baton->pages);
}
if (baton->pageHeight > 0) {
info.Set("pageHeight", baton->pageHeight);
}
if (baton->loop >= 0) {
info.Set("loop", baton->loop);
}
if (!baton->delay.empty()) {
int i = 0;
Napi::Array delay = Napi::Array::New(env, static_cast<size_t>(baton->delay.size()));
for (int const d : baton->delay) {
delay.Set(i++, d);
}
info.Set("delay", delay);
}
if (baton->pagePrimary > -1) {
info.Set("pagePrimary", baton->pagePrimary);
}
if (!baton->compression.empty()) {
info.Set("compression", baton->compression);
}
if (!baton->resolutionUnit.empty()) {
info.Set("resolutionUnit", baton->resolutionUnit == "in" ? "inch" : baton->resolutionUnit);
}
if (!baton->formatMagick.empty()) {
info.Set("formatMagick", baton->formatMagick);
}
if (!baton->levels.empty()) {
int i = 0;
Napi::Array levels = Napi::Array::New(env, static_cast<size_t>(baton->levels.size()));
for (std::pair<int, int> const &l : baton->levels) {
Napi::Object level = Napi::Object::New(env);
level.Set("width", l.first);
level.Set("height", l.second);
levels.Set(i++, level);
}
info.Set("levels", levels);
}
if (baton->subifds > 0) {
info.Set("subifds", baton->subifds);
}
if (!baton->background.empty()) {
Napi::Object background = Napi::Object::New(env);
if (baton->background.size() == 3) {
background.Set("r", baton->background[0]);
background.Set("g", baton->background[1]);
background.Set("b", baton->background[2]);
} else {
background.Set("gray", round(baton->background[0] * 100 / 255));
}
info.Set("background", background);
}
info.Set("hasProfile", baton->hasProfile);
info.Set("hasAlpha", baton->hasAlpha);
if (baton->orientation > 0) {
info.Set("orientation", baton->orientation);
}
Napi::Object autoOrient = Napi::Object::New(env);
info.Set("autoOrient", autoOrient);
if (baton->orientation >= 5) {
autoOrient.Set("width", baton->height);
autoOrient.Set("height", baton->width);
} else {
autoOrient.Set("width", baton->width);
autoOrient.Set("height", baton->height);
}
if (baton->exifLength > 0) {
info.Set("exif", Napi::Buffer<char>::NewOrCopy(env, baton->exif, baton->exifLength, sharp::FreeCallback));
}
if (baton->iccLength > 0) {
info.Set("icc", Napi::Buffer<char>::NewOrCopy(env, baton->icc, baton->iccLength, sharp::FreeCallback));
}
if (baton->iptcLength > 0) {
info.Set("iptc", Napi::Buffer<char>::NewOrCopy(env, baton->iptc, baton->iptcLength, sharp::FreeCallback));
}
if (baton->xmpLength > 0) {
info.Set("xmp", Napi::Buffer<char>::NewOrCopy(env, baton->xmp, baton->xmpLength, sharp::FreeCallback));
if (g_utf8_validate(static_cast<char const *>(baton->xmp), baton->xmpLength, nullptr)) {
info.Set("xmpAsString",
Napi::String::New(env, static_cast<char const *>(baton->xmp), baton->xmpLength));
}
}
if (baton->tifftagPhotoshopLength > 0) {
info.Set("tifftagPhotoshop",
Napi::Buffer<char>::NewOrCopy(env, baton->tifftagPhotoshop,
baton->tifftagPhotoshopLength, sharp::FreeCallback));
}
if (baton->comments.size() > 0) {
int i = 0;
Napi::Array comments = Napi::Array::New(env, baton->comments.size());
for (auto &c : baton->comments) {
Napi::Object comment = Napi::Object::New(env);
comment.Set("keyword", c.first);
comment.Set("text", c.second);
comments.Set(i++, comment);
}
info.Set("comments", comments);
}
Callback().Call(Receiver().Value(), { env.Null(), info });
} else {
Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() });
}
delete baton->input;
delete baton;
}
private:
MetadataBaton* baton;
Napi::FunctionReference debuglog;
};
/*
metadata(options, callback)
*/
Napi::Value metadata(const Napi::CallbackInfo& info) {
// V8 objects are converted to non-V8 types held in the baton struct
MetadataBaton *baton = new MetadataBaton;
Napi::Object options = info[size_t(0)].As<Napi::Object>();
// Input
baton->input = sharp::CreateInputDescriptor(options.Get("input").As<Napi::Object>());
// Function to notify of libvips warnings
Napi::Function debuglog = options.Get("debuglog").As<Napi::Function>();
// Join queue for worker thread
Napi::Function callback = info[size_t(1)].As<Napi::Function>();
MetadataWorker *worker = new MetadataWorker(callback, baton, debuglog);
worker->Receiver().Set("options", options);
worker->Queue();
// Increment queued task counter
sharp::counterQueue++;
return info.Env().Undefined();
}
const char *PNG_COMMENT_START = "png-comment-";
const int PNG_COMMENT_START_LEN = strlen(PNG_COMMENT_START);
static void* readPNGComment(VipsImage *image, const char *field, GValue *value, void *p) {
MetadataComments *comments = static_cast<MetadataComments *>(p);
if (vips_isprefix(PNG_COMMENT_START, field)) {
const char *keyword = strchr(field + PNG_COMMENT_START_LEN, '-');
const char *str;
if (keyword != NULL && !vips_image_get_string(image, field, &str)) {
keyword++; // Skip the hyphen
comments->push_back(std::make_pair(keyword, str));
}
}
return NULL;
}

87
src/metadata.h Normal file
View File

@ -0,0 +1,87 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
#ifndef SRC_METADATA_H_
#define SRC_METADATA_H_
#include <string>
#include <napi.h>
#include "./common.h"
typedef std::vector<std::pair<std::string, std::string>> MetadataComments;
struct MetadataBaton {
// Input
sharp::InputDescriptor *input;
// Output
std::string format;
int width;
int height;
std::string space;
int channels;
std::string depth;
int density;
std::string chromaSubsampling;
bool isProgressive;
bool isPalette;
int bitsPerSample;
int pages;
int pageHeight;
int loop;
std::vector<int> delay;
int pagePrimary;
std::string compression;
std::string resolutionUnit;
std::string formatMagick;
std::vector<std::pair<int, int>> levels;
int subifds;
std::vector<double> background;
bool hasProfile;
bool hasAlpha;
int orientation;
char *exif;
size_t exifLength;
char *icc;
size_t iccLength;
char *iptc;
size_t iptcLength;
char *xmp;
size_t xmpLength;
char *tifftagPhotoshop;
size_t tifftagPhotoshopLength;
MetadataComments comments;
std::string err;
MetadataBaton():
input(nullptr),
width(0),
height(0),
channels(0),
density(0),
isProgressive(false),
isPalette(false),
bitsPerSample(0),
pages(0),
pageHeight(0),
loop(-1),
pagePrimary(-1),
subifds(0),
hasProfile(false),
hasAlpha(false),
orientation(0),
exif(nullptr),
exifLength(0),
icc(nullptr),
iccLength(0),
iptc(nullptr),
iptcLength(0),
xmp(nullptr),
xmpLength(0),
tifftagPhotoshop(nullptr),
tifftagPhotoshopLength(0) {}
};
Napi::Value metadata(const Napi::CallbackInfo& info);
#endif // SRC_METADATA_H_

497
src/operations.cc Normal file
View File

@ -0,0 +1,497 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
#include <algorithm>
#include <functional>
#include <memory>
#include <tuple>
#include <vector>
#include <vips/vips8>
#include "common.h"
#include "operations.h"
using vips::VImage;
using vips::VError;
namespace sharp {
/*
* Tint an image using the provided RGB.
*/
VImage Tint(VImage image, std::vector<double> const tint) {
std::vector<double> const tintLab = (VImage::black(1, 1) + tint)
.colourspace(VIPS_INTERPRETATION_LAB, VImage::option()->set("source_space", VIPS_INTERPRETATION_sRGB))
.getpoint(0, 0);
// LAB identity function
VImage identityLab = VImage::identity(VImage::option()->set("bands", 3))
.colourspace(VIPS_INTERPRETATION_LAB, VImage::option()->set("source_space", VIPS_INTERPRETATION_sRGB));
// Scale luminance range, 0.0 to 1.0
VImage l = identityLab[0] / 100;
// Weighting functions
VImage weightL = 1.0 - 4.0 * ((l - 0.5) * (l - 0.5));
VImage weightAB = (weightL * tintLab).extract_band(1, VImage::option()->set("n", 2));
identityLab = identityLab[0].bandjoin(weightAB);
// Convert lookup table to sRGB
VImage lut = identityLab.colourspace(VIPS_INTERPRETATION_sRGB,
VImage::option()->set("source_space", VIPS_INTERPRETATION_LAB));
// Original colourspace
VipsInterpretation typeBeforeTint = image.interpretation();
if (typeBeforeTint == VIPS_INTERPRETATION_RGB) {
typeBeforeTint = VIPS_INTERPRETATION_sRGB;
}
// Apply lookup table
if (image.has_alpha()) {
VImage alpha = image[image.bands() - 1];
image = RemoveAlpha(image)
.colourspace(VIPS_INTERPRETATION_B_W)
.maplut(lut)
.colourspace(typeBeforeTint)
.bandjoin(alpha);
} else {
image = image
.colourspace(VIPS_INTERPRETATION_B_W)
.maplut(lut)
.colourspace(typeBeforeTint);
}
return image;
}
/*
* Stretch luminance to cover full dynamic range.
*/
VImage Normalise(VImage image, int const lower, int const upper) {
// Get original colourspace
VipsInterpretation typeBeforeNormalize = image.interpretation();
if (typeBeforeNormalize == VIPS_INTERPRETATION_RGB) {
typeBeforeNormalize = VIPS_INTERPRETATION_sRGB;
}
// Convert to LAB colourspace
VImage lab = image.colourspace(VIPS_INTERPRETATION_LAB);
// Extract luminance
VImage luminance = lab[0];
// Find luminance range
int const min = lower == 0 ? luminance.min() : luminance.percent(lower);
int const max = upper == 100 ? luminance.max() : luminance.percent(upper);
if (std::abs(max - min) > 1) {
// Extract chroma
VImage chroma = lab.extract_band(1, VImage::option()->set("n", 2));
// Calculate multiplication factor and addition
double f = 100.0 / (max - min);
double a = -(min * f);
// Scale luminance, join to chroma, convert back to original colourspace
VImage normalized = luminance.linear(f, a).bandjoin(chroma).colourspace(typeBeforeNormalize);
// Attach original alpha channel, if any
if (image.has_alpha()) {
// Extract original alpha channel
VImage alpha = image[image.bands() - 1];
// Join alpha channel to normalised image
return normalized.bandjoin(alpha);
} else {
return normalized;
}
}
return image;
}
/*
* Contrast limiting adapative histogram equalization (CLAHE)
*/
VImage Clahe(VImage image, int const width, int const height, int const maxSlope) {
return image.hist_local(width, height, VImage::option()->set("max_slope", maxSlope));
}
/*
* Gamma encoding/decoding
*/
VImage Gamma(VImage image, double const exponent) {
if (image.has_alpha()) {
// Separate alpha channel
VImage alpha = image[image.bands() - 1];
return RemoveAlpha(image).gamma(VImage::option()->set("exponent", exponent)).bandjoin(alpha);
} else {
return image.gamma(VImage::option()->set("exponent", exponent));
}
}
/*
* 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.
*/
VImage Negate(VImage image, bool const negateAlpha) {
if (image.has_alpha() && !negateAlpha) {
// Separate alpha channel
VImage alpha = image[image.bands() - 1];
return RemoveAlpha(image).invert().bandjoin(alpha);
} else {
return image.invert();
}
}
/*
* Gaussian blur. Use sigma of -1.0 for fast blur.
*/
VImage Blur(VImage image, double const sigma, VipsPrecision precision, double const minAmpl) {
if (sigma == -1.0) {
// Fast, mild blur - averages neighbouring pixels
VImage blur = VImage::new_matrixv(3, 3,
1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
1.0, 1.0, 1.0);
blur.set("scale", 9.0);
return image.conv(blur);
} else {
// Slower, accurate Gaussian blur
return StaySequential(image).gaussblur(sigma, VImage::option()
->set("precision", precision)
->set("min_ampl", minAmpl));
}
}
/*
* Convolution with a kernel.
*/
VImage Convolve(VImage image, int const width, int const height,
double const scale, double const offset,
std::vector<double> const &kernel_v
) {
VImage kernel = VImage::new_from_memory(
static_cast<void*>(const_cast<double*>(kernel_v.data())),
width * height * sizeof(double),
width,
height,
1,
VIPS_FORMAT_DOUBLE);
kernel.set("scale", scale);
kernel.set("offset", offset);
return image.conv(kernel);
}
/*
* Recomb with a Matrix of the given bands/channel size.
* Eg. RGB will be a 3x3 matrix.
*/
VImage Recomb(VImage image, std::vector<double> const& matrix) {
double* m = const_cast<double*>(matrix.data());
image = image.colourspace(VIPS_INTERPRETATION_sRGB);
if (matrix.size() == 9) {
return image
.recomb(image.bands() == 3
? VImage::new_matrix(3, 3, m, 9)
: VImage::new_matrixv(4, 4,
m[0], m[1], m[2], 0.0,
m[3], m[4], m[5], 0.0,
m[6], m[7], m[8], 0.0,
0.0, 0.0, 0.0, 1.0));
} else {
return image.recomb(VImage::new_matrix(4, 4, m, 16));
}
}
VImage Modulate(VImage image, double const brightness, double const saturation,
int const hue, double const lightness) {
VipsInterpretation colourspaceBeforeModulate = image.interpretation();
if (image.has_alpha()) {
// Separate alpha channel
VImage alpha = image[image.bands() - 1];
return RemoveAlpha(image)
.colourspace(VIPS_INTERPRETATION_LCH)
.linear(
{ brightness, saturation, 1},
{ lightness, 0.0, static_cast<double>(hue) }
)
.colourspace(colourspaceBeforeModulate)
.bandjoin(alpha);
} else {
return image
.colourspace(VIPS_INTERPRETATION_LCH)
.linear(
{ brightness, saturation, 1 },
{ lightness, 0.0, static_cast<double>(hue) }
)
.colourspace(colourspaceBeforeModulate);
}
}
/*
* Sharpen flat and jagged areas. Use sigma of -1.0 for fast sharpen.
*/
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) {
// Fast, mild sharpen
VImage sharpen = VImage::new_matrixv(3, 3,
-1.0, -1.0, -1.0,
-1.0, 32.0, -1.0,
-1.0, -1.0, -1.0);
sharpen.set("scale", 24.0);
return image.conv(sharpen);
} else {
// Slow, accurate sharpen in LAB colour space, with control over flat vs jagged areas
VipsInterpretation colourspaceBeforeSharpen = image.interpretation();
if (colourspaceBeforeSharpen == VIPS_INTERPRETATION_RGB) {
colourspaceBeforeSharpen = VIPS_INTERPRETATION_sRGB;
}
return image
.sharpen(VImage::option()
->set("sigma", sigma)
->set("m1", m1)
->set("m2", m2)
->set("x1", x1)
->set("y2", y2)
->set("y3", y3))
.colourspace(colourspaceBeforeSharpen);
}
}
VImage Threshold(VImage image, double const threshold, bool const thresholdGrayscale) {
if (!thresholdGrayscale) {
return image >= threshold;
}
return image.colourspace(VIPS_INTERPRETATION_B_W) >= threshold;
}
/*
Perform boolean/bitwise operation on image color channels - results in one channel image
*/
VImage Bandbool(VImage image, VipsOperationBoolean const boolean) {
image = image.bandbool(boolean);
return image.copy(VImage::option()->set("interpretation", VIPS_INTERPRETATION_B_W));
}
/*
Perform bitwise boolean operation between images
*/
VImage Boolean(VImage image, VImage imageR, VipsOperationBoolean const boolean) {
return image.boolean(imageR, boolean);
}
/*
Trim an image
*/
VImage Trim(VImage image, std::vector<double> background, double threshold, bool const lineArt) {
if (image.width() < 3 && image.height() < 3) {
throw VError("Image to trim must be at least 3x3 pixels");
}
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);
} else if (sharp::Is16Bit(image.interpretation())) {
for (size_t i = 0; i < background.size(); i++) {
background[i] *= 256.0;
}
threshold *= 256.0;
}
std::vector<double> backgroundAlpha({ background.back() });
if (image.has_alpha()) {
background.pop_back();
} else {
background.resize(image.bands());
}
int left, top, width, height;
left = image.find_trim(&top, &width, &height, VImage::option()
->set("background", background)
->set("line_art", lineArt)
->set("threshold", threshold));
if (image.has_alpha()) {
// Search alpha channel (A)
int leftA, topA, widthA, heightA;
VImage alpha = image[image.bands() - 1];
leftA = alpha.find_trim(&topA, &widthA, &heightA, VImage::option()
->set("background", backgroundAlpha)
->set("line_art", lineArt)
->set("threshold", threshold));
if (widthA > 0 && heightA > 0) {
if (width > 0 && height > 0) {
// Combined bounding box (B)
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);
}
}
}
if (width > 0 && height > 0) {
return image.extract_area(left, top, width, height);
}
return image;
}
/*
* Calculate (a * in + b)
*/
VImage Linear(VImage image, std::vector<double> const a, std::vector<double> const b) {
size_t const bands = static_cast<size_t>(image.bands());
if (a.size() > bands) {
throw VError("Band expansion using linear is unsupported");
}
bool const uchar = !Is16Bit(image.interpretation());
if (image.has_alpha() && a.size() != bands && (a.size() == 1 || a.size() == bands - 1 || bands - 1 == 1)) {
// Separate alpha channel
VImage alpha = image[bands - 1];
return RemoveAlpha(image).linear(a, b, VImage::option()->set("uchar", uchar)).bandjoin(alpha);
} else {
return image.linear(a, b, VImage::option()->set("uchar", uchar));
}
}
/*
* Unflatten
*/
VImage Unflatten(VImage image) {
if (image.has_alpha()) {
VImage alpha = image[image.bands() - 1];
VImage noAlpha = RemoveAlpha(image);
return noAlpha.bandjoin(alpha & (noAlpha.colourspace(VIPS_INTERPRETATION_B_W) < 255));
} else {
return image.bandjoin(image.colourspace(VIPS_INTERPRETATION_B_W) < 255);
}
}
/*
* Ensure the image is in a given colourspace
*/
VImage EnsureColourspace(VImage image, VipsInterpretation colourspace) {
if (colourspace != VIPS_INTERPRETATION_LAST && image.interpretation() != colourspace) {
image = image.colourspace(colourspace,
VImage::option()->set("source_space", image.interpretation()));
}
return image;
}
/*
* Split and crop each frame, reassemble, and update pageHeight.
*/
VImage CropMultiPage(VImage image, int left, int top, int width, int height,
int nPages, int *pageHeight) {
if (top == 0 && height == *pageHeight) {
// Fast path; no need to adjust the height of the multi-page image
return image.extract_area(left, 0, width, image.height());
} else {
std::vector<VImage> pages;
pages.reserve(nPages);
// Split the image into cropped frames
image = StaySequential(image);
for (int i = 0; i < nPages; i++) {
pages.push_back(
image.extract_area(left, *pageHeight * i + top, width, height));
}
// Reassemble the frames into a tall, thin image
VImage assembled = VImage::arrayjoin(pages,
VImage::option()->set("across", 1));
// Update the page height
*pageHeight = height;
return assembled;
}
}
/*
* Split into frames, embed each frame, reassemble, and update pageHeight.
*/
VImage EmbedMultiPage(VImage image, int left, int top, int width, int height,
VipsExtend extendWith, std::vector<double> background, int nPages, int *pageHeight) {
if (top == 0 && height == *pageHeight) {
// Fast path; no need to adjust the height of the multi-page image
return image.embed(left, 0, width, image.height(), VImage::option()
->set("extend", extendWith)
->set("background", background));
} else if (left == 0 && width == image.width()) {
// Fast path; no need to adjust the width of the multi-page image
std::vector<VImage> pages;
pages.reserve(nPages);
// Rearrange the tall image into a vertical grid
image = image.grid(*pageHeight, nPages, 1);
// Do the embed on the wide image
image = image.embed(0, top, image.width(), height, VImage::option()
->set("extend", extendWith)
->set("background", background));
// Split the wide image into frames
for (int i = 0; i < nPages; i++) {
pages.push_back(
image.extract_area(width * i, 0, width, height));
}
// Reassemble the frames into a tall, thin image
VImage assembled = VImage::arrayjoin(pages,
VImage::option()->set("across", 1));
// Update the page height
*pageHeight = height;
return assembled;
} else {
std::vector<VImage> pages;
pages.reserve(nPages);
// Split the image into frames
for (int i = 0; i < nPages; i++) {
pages.push_back(
image.extract_area(0, *pageHeight * i, image.width(), *pageHeight));
}
// Embed each frame in the target size
for (int i = 0; i < nPages; i++) {
pages[i] = pages[i].embed(left, top, width, height, VImage::option()
->set("extend", extendWith)
->set("background", background));
}
// Reassemble the frames into a tall, thin image
VImage assembled = VImage::arrayjoin(pages,
VImage::option()->set("across", 1));
// Update the page height
*pageHeight = height;
return assembled;
}
}
/*
* Dilate an image
*/
VImage Dilate(VImage image, int const width) {
int const maskWidth = 2 * width + 1;
VImage mask = VImage::new_matrix(maskWidth, maskWidth);
return image.morph(
mask,
VIPS_OPERATION_MORPHOLOGY_DILATE).invert();
}
/*
* Erode an image
*/
VImage Erode(VImage image, int const width) {
int const maskWidth = 2 * width + 1;
VImage mask = VImage::new_matrix(maskWidth, maskWidth);
return image.morph(
mask,
VIPS_OPERATION_MORPHOLOGY_ERODE).invert();
}
} // namespace sharp

134
src/operations.h Normal file
View File

@ -0,0 +1,134 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
#ifndef SRC_OPERATIONS_H_
#define SRC_OPERATIONS_H_
#include <algorithm>
#include <functional>
#include <memory>
#include <tuple>
#include <vips/vips8>
using vips::VImage;
namespace sharp {
/*
* Tint an image using the provided RGB.
*/
VImage Tint(VImage image, std::vector<double> const tint);
/*
* Stretch luminance to cover full dynamic range.
*/
VImage Normalise(VImage image, int const lower, int const upper);
/*
* Contrast limiting adapative histogram equalization (CLAHE)
*/
VImage Clahe(VImage image, int const width, int const height, int const maxSlope);
/*
* Gamma encoding/decoding
*/
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.
*/
VImage Negate(VImage image, bool const negateAlpha);
/*
* Gaussian blur. Use sigma of -1.0 for fast blur.
*/
VImage Blur(VImage image, double const sigma, VipsPrecision precision, double const minAmpl);
/*
* Convolution with a kernel.
*/
VImage Convolve(VImage image, int const width, int const height,
double const scale, double const offset, std::vector<double> const &kernel_v);
/*
* Sharpen flat and jagged areas. Use sigma of -1.0 for fast sharpen.
*/
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
*/
VImage Threshold(VImage image, double const threshold, bool const thresholdColor);
/*
Perform boolean/bitwise operation on image color channels - results in one channel image
*/
VImage Bandbool(VImage image, VipsOperationBoolean const boolean);
/*
Perform bitwise boolean operation between images
*/
VImage Boolean(VImage image, VImage imageR, VipsOperationBoolean const boolean);
/*
Trim an image
*/
VImage Trim(VImage image, std::vector<double> background, double threshold, bool const lineArt);
/*
* Linear adjustment (a * in + b)
*/
VImage Linear(VImage image, std::vector<double> const a, std::vector<double> const b);
/*
* Unflatten
*/
VImage Unflatten(VImage image);
/*
* Recomb with a Matrix of the given bands/channel size.
* Eg. RGB will be a 3x3 matrix.
*/
VImage Recomb(VImage image, std::vector<double> const &matrix);
/*
* Modulate brightness, saturation, hue and lightness
*/
VImage Modulate(VImage image, double const brightness, double const saturation,
int const hue, double const lightness);
/*
* Ensure the image is in a given colourspace
*/
VImage EnsureColourspace(VImage image, VipsInterpretation colourspace);
/*
* Split and crop each frame, reassemble, and update pageHeight.
*/
VImage CropMultiPage(VImage image, int left, int top, int width, int height,
int nPages, int *pageHeight);
/*
* Split into frames, embed each frame, reassemble, and update pageHeight.
*/
VImage EmbedMultiPage(VImage image, int left, int top, int width, int height,
VipsExtend extendWith, std::vector<double> background, int nPages, int *pageHeight);
/*
* Dilate an image
*/
VImage Dilate(VImage image, int const maskWidth);
/*
* Erode an image
*/
VImage Erode(VImage image, int const maskWidth);
} // namespace sharp
#endif // SRC_OPERATIONS_H_

1819
src/pipeline.cc Normal file

File diff suppressed because it is too large Load Diff

401
src/pipeline.h Normal file
View File

@ -0,0 +1,401 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
#ifndef SRC_PIPELINE_H_
#define SRC_PIPELINE_H_
#include <memory>
#include <string>
#include <vector>
#include <unordered_map>
#include <napi.h>
#include <vips/vips8>
#include "./common.h"
Napi::Value pipeline(const Napi::CallbackInfo& info);
struct Composite {
sharp::InputDescriptor *input;
VipsBlendMode mode;
int gravity;
int left;
int top;
bool hasOffset;
bool tile;
bool premultiplied;
Composite():
input(nullptr),
mode(VIPS_BLEND_MODE_OVER),
gravity(0),
left(0),
top(0),
hasOffset(false),
tile(false),
premultiplied(false) {}
};
struct PipelineBaton {
sharp::InputDescriptor *input;
std::vector<sharp::InputDescriptor *> join;
std::string formatOut;
std::string fileOut;
void *bufferOut;
size_t bufferOutLength;
int pageHeightOut;
int pagesOut;
std::vector<Composite *> composite;
std::vector<sharp::InputDescriptor *> joinChannelIn;
int topOffsetPre;
int leftOffsetPre;
int widthPre;
int heightPre;
int topOffsetPost;
int leftOffsetPost;
int widthPost;
int heightPost;
int width;
int height;
int channels;
VipsKernel kernel;
sharp::Canvas canvas;
int position;
std::vector<double> resizeBackground;
bool hasCropOffset;
int cropOffsetLeft;
int cropOffsetTop;
bool hasAttentionCenter;
int attentionX;
int attentionY;
bool premultiplied;
bool tileCentre;
bool fastShrinkOnLoad;
std::vector<double> tint;
bool flatten;
std::vector<double> flattenBackground;
bool unflatten;
bool negate;
bool negateAlpha;
double blurSigma;
VipsPrecision precision;
double minAmpl;
double brightness;
double saturation;
int hue;
double lightness;
int medianSize;
double sharpenSigma;
double sharpenM1;
double sharpenM2;
double sharpenX1;
double sharpenY2;
double sharpenY3;
int threshold;
bool thresholdGrayscale;
std::vector<double> trimBackground;
double trimThreshold;
bool trimLineArt;
int trimOffsetLeft;
int trimOffsetTop;
std::vector<double> linearA;
std::vector<double> linearB;
int dilateWidth;
int erodeWidth;
double gamma;
double gammaOut;
bool greyscale;
bool normalise;
int normaliseLower;
int normaliseUpper;
int claheWidth;
int claheHeight;
int claheMaxSlope;
int angle;
double rotationAngle;
std::vector<double> rotationBackground;
bool rotateBeforePreExtract;
bool flip;
bool flop;
int extendTop;
int extendBottom;
int extendLeft;
int extendRight;
std::vector<double> extendBackground;
VipsExtend extendWith;
bool withoutEnlargement;
bool withoutReduction;
std::vector<double> affineMatrix;
std::vector<double> affineBackground;
double affineIdx;
double affineIdy;
double affineOdx;
double affineOdy;
std::string affineInterpolator;
int jpegQuality;
bool jpegProgressive;
std::string jpegChromaSubsampling;
bool jpegTrellisQuantisation;
int jpegQuantisationTable;
bool jpegOvershootDeringing;
bool jpegOptimiseScans;
bool jpegOptimiseCoding;
bool pngProgressive;
int pngCompressionLevel;
bool pngAdaptiveFiltering;
bool pngPalette;
int pngQuality;
int pngEffort;
int pngBitdepth;
double pngDither;
int jp2Quality;
bool jp2Lossless;
int jp2TileHeight;
int jp2TileWidth;
std::string jp2ChromaSubsampling;
int webpQuality;
int webpAlphaQuality;
bool webpNearLossless;
bool webpLossless;
bool webpSmartSubsample;
bool webpSmartDeblock;
VipsForeignWebpPreset webpPreset;
int webpEffort;
bool webpMinSize;
bool webpMixed;
int gifBitdepth;
int gifEffort;
double gifDither;
double gifInterFrameMaxError;
double gifInterPaletteMaxError;
bool gifKeepDuplicateFrames;
bool gifReuse;
bool gifProgressive;
int tiffQuality;
VipsForeignTiffCompression tiffCompression;
VipsForeignTiffPredictor tiffPredictor;
bool tiffPyramid;
int tiffBitdepth;
bool tiffMiniswhite;
bool tiffTile;
int tiffTileHeight;
int tiffTileWidth;
double tiffXres;
double tiffYres;
VipsForeignTiffResunit tiffResolutionUnit;
int heifQuality;
VipsForeignHeifCompression heifCompression;
int heifEffort;
std::string heifChromaSubsampling;
bool heifLossless;
int heifBitdepth;
double jxlDistance;
int jxlDecodingTier;
int jxlEffort;
bool jxlLossless;
VipsBandFormat rawDepth;
std::string err;
int keepMetadata;
int withMetadataOrientation;
double withMetadataDensity;
std::string withIccProfile;
std::unordered_map<std::string, std::string> withExif;
bool withExifMerge;
std::string withXmp;
int timeoutSeconds;
std::vector<double> convKernel;
int convKernelWidth;
int convKernelHeight;
double convKernelScale;
double convKernelOffset;
sharp::InputDescriptor *boolean;
VipsOperationBoolean booleanOp;
VipsOperationBoolean bandBoolOp;
int extractChannel;
bool removeAlpha;
double ensureAlpha;
VipsInterpretation colourspacePipeline;
VipsInterpretation colourspace;
std::vector<int> delay;
int loop;
int tileSize;
int tileOverlap;
VipsForeignDzContainer tileContainer;
VipsForeignDzLayout tileLayout;
std::string tileFormat;
int tileAngle;
std::vector<double> tileBackground;
int tileSkipBlanks;
VipsForeignDzDepth tileDepth;
std::string tileId;
std::string tileBasename;
std::vector<double> recombMatrix;
PipelineBaton():
input(nullptr),
bufferOutLength(0),
pageHeightOut(0),
pagesOut(0),
topOffsetPre(-1),
topOffsetPost(-1),
channels(0),
kernel(VIPS_KERNEL_LANCZOS3),
canvas(sharp::Canvas::CROP),
position(0),
resizeBackground{ 0.0, 0.0, 0.0, 255.0 },
hasCropOffset(false),
cropOffsetLeft(0),
cropOffsetTop(0),
hasAttentionCenter(false),
attentionX(0),
attentionY(0),
premultiplied(false),
tint{ -1.0, 0.0, 0.0, 0.0 },
flatten(false),
flattenBackground{ 0.0, 0.0, 0.0 },
unflatten(false),
negate(false),
negateAlpha(true),
blurSigma(0.0),
brightness(1.0),
saturation(1.0),
hue(0),
lightness(0),
medianSize(0),
sharpenSigma(0.0),
sharpenM1(1.0),
sharpenM2(2.0),
sharpenX1(2.0),
sharpenY2(10.0),
sharpenY3(20.0),
threshold(0),
thresholdGrayscale(true),
trimBackground{},
trimThreshold(-1.0),
trimLineArt(false),
trimOffsetLeft(0),
trimOffsetTop(0),
linearA{},
linearB{},
dilateWidth(0),
erodeWidth(0),
gamma(0.0),
greyscale(false),
normalise(false),
normaliseLower(1),
normaliseUpper(99),
claheWidth(0),
claheHeight(0),
claheMaxSlope(3),
angle(0),
rotationAngle(0.0),
rotationBackground{ 0.0, 0.0, 0.0, 255.0 },
flip(false),
flop(false),
extendTop(0),
extendBottom(0),
extendLeft(0),
extendRight(0),
extendBackground{ 0.0, 0.0, 0.0, 255.0 },
extendWith(VIPS_EXTEND_BACKGROUND),
withoutEnlargement(false),
withoutReduction(false),
affineMatrix{ 1.0, 0.0, 0.0, 1.0 },
affineBackground{ 0.0, 0.0, 0.0, 255.0 },
affineIdx(0),
affineIdy(0),
affineOdx(0),
affineOdy(0),
affineInterpolator("bicubic"),
jpegQuality(80),
jpegProgressive(false),
jpegChromaSubsampling("4:2:0"),
jpegTrellisQuantisation(false),
jpegQuantisationTable(0),
jpegOvershootDeringing(false),
jpegOptimiseScans(false),
jpegOptimiseCoding(true),
pngProgressive(false),
pngCompressionLevel(6),
pngAdaptiveFiltering(false),
pngPalette(false),
pngQuality(100),
pngEffort(7),
pngBitdepth(8),
pngDither(1.0),
jp2Quality(80),
jp2Lossless(false),
jp2TileHeight(512),
jp2TileWidth(512),
jp2ChromaSubsampling("4:4:4"),
webpQuality(80),
webpAlphaQuality(100),
webpNearLossless(false),
webpLossless(false),
webpSmartSubsample(false),
webpSmartDeblock(false),
webpPreset(VIPS_FOREIGN_WEBP_PRESET_DEFAULT),
webpEffort(4),
webpMinSize(false),
webpMixed(false),
gifBitdepth(8),
gifEffort(7),
gifDither(1.0),
gifInterFrameMaxError(0.0),
gifInterPaletteMaxError(3.0),
gifKeepDuplicateFrames(false),
gifReuse(true),
gifProgressive(false),
tiffQuality(80),
tiffCompression(VIPS_FOREIGN_TIFF_COMPRESSION_JPEG),
tiffPredictor(VIPS_FOREIGN_TIFF_PREDICTOR_HORIZONTAL),
tiffPyramid(false),
tiffBitdepth(8),
tiffMiniswhite(false),
tiffTile(false),
tiffTileHeight(256),
tiffTileWidth(256),
tiffXres(1.0),
tiffYres(1.0),
tiffResolutionUnit(VIPS_FOREIGN_TIFF_RESUNIT_INCH),
heifQuality(50),
heifCompression(VIPS_FOREIGN_HEIF_COMPRESSION_AV1),
heifEffort(4),
heifChromaSubsampling("4:4:4"),
heifLossless(false),
heifBitdepth(8),
jxlDistance(1.0),
jxlDecodingTier(0),
jxlEffort(7),
jxlLossless(false),
rawDepth(VIPS_FORMAT_UCHAR),
keepMetadata(0),
withMetadataOrientation(-1),
withMetadataDensity(0.0),
withExifMerge(true),
timeoutSeconds(0),
convKernelWidth(0),
convKernelHeight(0),
convKernelScale(0.0),
convKernelOffset(0.0),
boolean(nullptr),
booleanOp(VIPS_OPERATION_BOOLEAN_LAST),
bandBoolOp(VIPS_OPERATION_BOOLEAN_LAST),
extractChannel(-1),
removeAlpha(false),
ensureAlpha(-1.0),
colourspacePipeline(VIPS_INTERPRETATION_LAST),
colourspace(VIPS_INTERPRETATION_LAST),
loop(-1),
tileSize(256),
tileOverlap(0),
tileContainer(VIPS_FOREIGN_DZ_CONTAINER_FS),
tileLayout(VIPS_FOREIGN_DZ_LAYOUT_DZ),
tileAngle(0),
tileBackground{ 255.0, 255.0, 255.0, 255.0 },
tileSkipBlanks(-1),
tileDepth(VIPS_FOREIGN_DZ_DEPTH_LAST) {}
};
#endif // SRC_PIPELINE_H_

198
src/sharp.cc Executable file → Normal file
View File

@ -1,173 +1,43 @@
#include <node.h> // Copyright 2013 Lovell Fuller and others.
#include <math.h> // SPDX-License-Identifier: Apache-2.0
#include <string>
#include <vector>
#include <vips/vips.h>
using namespace v8; #include <mutex> // NOLINT(build/c++11)
// Free VipsImage children when object goes out of scope #include <napi.h>
// Thanks due to https://github.com/dosx/node-vips #include <vips/vips8>
class ImageFreer {
public:
ImageFreer() {}
~ImageFreer() {
for (uint16_t i = 0; i < v_.size(); i++) {
if (v_[i] != NULL) {
g_object_unref(v_[i]);
}
}
v_.clear();
}
void add(VipsImage* i) { v_.push_back(i); }
private:
std::vector<VipsImage*> v_;
};
struct ResizeBaton { #include "common.h"
std::string src; #include "metadata.h"
std::string dst; #include "pipeline.h"
int cols; #include "utilities.h"
int rows; #include "stats.h"
bool crop;
int embed;
std::string err;
Persistent<Function> callback;
};
void ResizeAsync(uv_work_t *work) { Napi::Object init(Napi::Env env, Napi::Object exports) {
ResizeBaton* baton = static_cast<ResizeBaton*>(work->data); static std::once_flag sharp_vips_init_once;
std::call_once(sharp_vips_init_once, []() {
vips_init("sharp");
});
VipsImage *in = vips_image_new_mode((baton->src).c_str(), "p"); for (auto domain : { "VIPS", "vips2tiff" }) {
im_jpeg2vips((baton->src).c_str(), in); g_log_set_handler(domain, static_cast<GLogLevelFlags>(G_LOG_LEVEL_WARNING),
if (in == NULL) { static_cast<GLogFunc>(sharp::VipsWarningCallback), nullptr);
(baton->err).append(vips_error_buffer());
vips_error_clear();
return;
}
ImageFreer freer;
freer.add(in);
VipsImage* img = in;
VipsImage* t[4];
if (im_open_local_array(img, t, 4, "temp", "p")) {
(baton->err).append(vips_error_buffer());
vips_error_clear();
return;
} }
double xfactor = static_cast<double>(img->Xsize) / std::max(baton->cols, 1); // Methods available to JavaScript
double yfactor = static_cast<double>(img->Ysize) / std::max(baton->rows, 1); exports.Set("metadata", Napi::Function::New(env, metadata));
double factor = baton->crop ? std::min(xfactor, yfactor) : std::max(xfactor, yfactor); exports.Set("pipeline", Napi::Function::New(env, pipeline));
factor = std::max(factor, 1.0); exports.Set("cache", Napi::Function::New(env, cache));
int shrink = floor(factor); exports.Set("concurrency", Napi::Function::New(env, concurrency));
double residual = shrink / factor; exports.Set("counters", Napi::Function::New(env, counters));
exports.Set("simd", Napi::Function::New(env, simd));
// Use im_shrink with the integral reduction exports.Set("libvipsVersion", Napi::Function::New(env, libvipsVersion));
if (im_shrink(img, t[0], shrink, shrink)) { exports.Set("format", Napi::Function::New(env, format));
(baton->err).append(vips_error_buffer()); exports.Set("block", Napi::Function::New(env, block));
vips_error_clear(); exports.Set("_maxColourDistance", Napi::Function::New(env, _maxColourDistance));
return; exports.Set("_isUsingJemalloc", Napi::Function::New(env, _isUsingJemalloc));
} exports.Set("_isUsingX64V2", Napi::Function::New(env, _isUsingX64V2));
exports.Set("stats", Napi::Function::New(env, stats));
// Use im_affinei with the remaining float part using bilinear interpolation return exports;
if (im_affinei_all(t[0], t[1], vips_interpolate_bilinear_static(), residual, 0, 0, residual, 0, 0)) {
(baton->err).append(vips_error_buffer());
vips_error_clear();
return;
}
img = t[1];
if (baton->crop) {
int width = std::min(img->Xsize, baton->cols);
int height = std::min(img->Ysize, baton->rows);
int left = (img->Xsize - width + 1) / 2;
int top = (img->Ysize - height + 1) / 2;
if (im_extract_area(img, t[2], left, top, width, height)) {
(baton->err).append(vips_error_buffer());
vips_error_clear();
return;
}
img = t[2];
} else {
int left = (baton->cols - img->Xsize) / 2;
int top = (baton->rows - img->Ysize) / 2;
if (im_embed(img, t[2], baton->embed, left, top, baton->cols, baton->rows)) {
(baton->err).append(vips_error_buffer());
vips_error_clear();
return;
}
img = t[2];
}
// Mild sharpen
INTMASK* sharpen = im_create_imaskv("sharpen", 3, 3,
-1, -1, -1,
-1, 32, -1,
-1, -1, -1);
sharpen->scale = 24;
if (im_conv(img, t[3], sharpen)) {
(baton->err).append(vips_error_buffer());
vips_error_clear();
return;
}
img = t[3];
if (im_vips2jpeg(img, baton->dst.c_str())) {
(baton->err).append(vips_error_buffer());
vips_error_clear();
}
} }
void ResizeAsyncAfter(uv_work_t *work, int status) { NODE_API_MODULE(sharp, init)
HandleScope scope;
ResizeBaton *baton = static_cast<ResizeBaton*>(work->data);
Local<Value> argv[1];
if (!baton->err.empty()) {
argv[0] = String::New(baton->err.data(), baton->err.size());
} else {
argv[0] = Local<Value>::New(Null());
}
baton->callback->Call(Context::GetCurrent()->Global(), 1, argv);
baton->callback.Dispose();
delete baton;
delete work;
}
Handle<Value> Resize(const Arguments& args) {
HandleScope scope;
ResizeBaton *baton = new ResizeBaton;
baton->src = *String::Utf8Value(args[0]->ToString());
baton->dst = *String::Utf8Value(args[1]->ToString());
baton->cols = args[2]->Int32Value();
baton->rows = args[3]->Int32Value();
Local<String> canvas = args[4]->ToString();
if (canvas->Equals(String::NewSymbol("c"))) {
baton->crop = true;
} else if (canvas->Equals(String::NewSymbol("w"))) {
baton->crop = false;
baton->embed = 4;
} else if (canvas->Equals(String::NewSymbol("b"))) {
baton->crop = false;
baton->embed = 0;
}
baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[5]));
uv_work_t *work = new uv_work_t;
work->data = baton;
uv_queue_work(uv_default_loop(), work, ResizeAsync, (uv_after_work_cb)ResizeAsyncAfter);
return Undefined();
}
extern "C" void init(Handle<Object> target) {
HandleScope scope;
vips_init("");
NODE_SET_METHOD(target, "resize", Resize);
};
NODE_MODULE(sharp, init)

183
src/stats.cc Normal file
View File

@ -0,0 +1,183 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
#include <numeric>
#include <vector>
#include <iostream>
#include <napi.h>
#include <vips/vips8>
#include "common.h"
#include "stats.h"
class StatsWorker : public Napi::AsyncWorker {
public:
StatsWorker(Napi::Function callback, StatsBaton *baton, Napi::Function debuglog) :
Napi::AsyncWorker(callback), baton(baton), debuglog(Napi::Persistent(debuglog)) {}
~StatsWorker() {}
const int STAT_MIN_INDEX = 0;
const int STAT_MAX_INDEX = 1;
const int STAT_SUM_INDEX = 2;
const int STAT_SQ_SUM_INDEX = 3;
const int STAT_MEAN_INDEX = 4;
const int STAT_STDEV_INDEX = 5;
const int STAT_MINX_INDEX = 6;
const int STAT_MINY_INDEX = 7;
const int STAT_MAXX_INDEX = 8;
const int STAT_MAXY_INDEX = 9;
void Execute() {
// Decrement queued task counter
sharp::counterQueue--;
vips::VImage image;
sharp::ImageType imageType = sharp::ImageType::UNKNOWN;
try {
std::tie(image, imageType) = OpenInput(baton->input);
} catch (vips::VError const &err) {
(baton->err).append(err.what());
}
if (imageType != sharp::ImageType::UNKNOWN) {
try {
vips::VImage stats = image.stats();
int const bands = image.bands();
for (int b = 1; b <= bands; b++) {
ChannelStats cStats(
static_cast<int>(stats.getpoint(STAT_MIN_INDEX, b).front()),
static_cast<int>(stats.getpoint(STAT_MAX_INDEX, b).front()),
stats.getpoint(STAT_SUM_INDEX, b).front(),
stats.getpoint(STAT_SQ_SUM_INDEX, b).front(),
stats.getpoint(STAT_MEAN_INDEX, b).front(),
stats.getpoint(STAT_STDEV_INDEX, b).front(),
static_cast<int>(stats.getpoint(STAT_MINX_INDEX, b).front()),
static_cast<int>(stats.getpoint(STAT_MINY_INDEX, b).front()),
static_cast<int>(stats.getpoint(STAT_MAXX_INDEX, b).front()),
static_cast<int>(stats.getpoint(STAT_MAXY_INDEX, b).front()));
baton->channelStats.push_back(cStats);
}
// Image is not opaque when alpha layer is present and contains a non-mamixa value
if (image.has_alpha()) {
double const minAlpha = static_cast<double>(stats.getpoint(STAT_MIN_INDEX, bands).front());
if (minAlpha != vips_interpretation_max_alpha(image.interpretation())) {
baton->isOpaque = false;
}
}
// Convert to greyscale
vips::VImage greyscale = image.colourspace(VIPS_INTERPRETATION_B_W)[0];
// Estimate entropy via histogram of greyscale value frequency
baton->entropy = std::abs(greyscale.hist_find().hist_entropy());
// Estimate sharpness via standard deviation of greyscale laplacian
if (image.width() > 1 || image.height() > 1) {
VImage laplacian = VImage::new_matrixv(3, 3,
0.0, 1.0, 0.0,
1.0, -4.0, 1.0,
0.0, 1.0, 0.0);
laplacian.set("scale", 9.0);
baton->sharpness = greyscale.conv(laplacian).deviate();
}
// Most dominant sRGB colour via 4096-bin 3D histogram
vips::VImage hist = sharp::RemoveAlpha(image)
.colourspace(VIPS_INTERPRETATION_sRGB)
.hist_find_ndim(VImage::option()->set("bins", 16));
std::complex<double> maxpos = hist.maxpos();
int const dx = static_cast<int>(std::real(maxpos));
int const dy = static_cast<int>(std::imag(maxpos));
std::vector<double> pel = hist(dx, dy);
int const dz = std::distance(pel.begin(), std::find(pel.begin(), pel.end(), hist.max()));
baton->dominantRed = dx * 16 + 8;
baton->dominantGreen = dy * 16 + 8;
baton->dominantBlue = dz * 16 + 8;
} catch (vips::VError const &err) {
(baton->err).append(err.what());
}
}
// Clean up
vips_error_clear();
vips_thread_shutdown();
}
void OnOK() {
Napi::Env env = Env();
Napi::HandleScope scope(env);
// Handle warnings
std::string warning = sharp::VipsWarningPop();
while (!warning.empty()) {
debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) });
warning = sharp::VipsWarningPop();
}
if (baton->err.empty()) {
// Stats Object
Napi::Object info = Napi::Object::New(env);
Napi::Array channels = Napi::Array::New(env);
std::vector<ChannelStats>::iterator it;
int i = 0;
for (it = baton->channelStats.begin(); it < baton->channelStats.end(); it++, i++) {
Napi::Object channelStat = Napi::Object::New(env);
channelStat.Set("min", it->min);
channelStat.Set("max", it->max);
channelStat.Set("sum", it->sum);
channelStat.Set("squaresSum", it->squaresSum);
channelStat.Set("mean", it->mean);
channelStat.Set("stdev", it->stdev);
channelStat.Set("minX", it->minX);
channelStat.Set("minY", it->minY);
channelStat.Set("maxX", it->maxX);
channelStat.Set("maxY", it->maxY);
channels.Set(i, channelStat);
}
info.Set("channels", channels);
info.Set("isOpaque", baton->isOpaque);
info.Set("entropy", baton->entropy);
info.Set("sharpness", baton->sharpness);
Napi::Object dominant = Napi::Object::New(env);
dominant.Set("r", baton->dominantRed);
dominant.Set("g", baton->dominantGreen);
dominant.Set("b", baton->dominantBlue);
info.Set("dominant", dominant);
Callback().Call(Receiver().Value(), { env.Null(), info });
} else {
Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() });
}
delete baton->input;
delete baton;
}
private:
StatsBaton* baton;
Napi::FunctionReference debuglog;
};
/*
stats(options, callback)
*/
Napi::Value stats(const Napi::CallbackInfo& info) {
// V8 objects are converted to non-V8 types held in the baton struct
StatsBaton *baton = new StatsBaton;
Napi::Object options = info[size_t(0)].As<Napi::Object>();
// Input
baton->input = sharp::CreateInputDescriptor(options.Get("input").As<Napi::Object>());
baton->input->access = VIPS_ACCESS_RANDOM;
// Function to notify of libvips warnings
Napi::Function debuglog = options.Get("debuglog").As<Napi::Function>();
// Join queue for worker thread
Napi::Function callback = info[size_t(1)].As<Napi::Function>();
StatsWorker *worker = new StatsWorker(callback, baton, debuglog);
worker->Receiver().Set("options", options);
worker->Queue();
// Increment queued task counter
sharp::counterQueue++;
return info.Env().Undefined();
}

59
src/stats.h Normal file
View File

@ -0,0 +1,59 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
#ifndef SRC_STATS_H_
#define SRC_STATS_H_
#include <string>
#include <napi.h>
#include "./common.h"
struct ChannelStats {
// stats per channel
int min;
int max;
double sum;
double squaresSum;
double mean;
double stdev;
int minX;
int minY;
int maxX;
int maxY;
ChannelStats(int minVal, int maxVal, double sumVal, double squaresSumVal,
double meanVal, double stdevVal, int minXVal, int minYVal, int maxXVal, int maxYVal):
min(minVal), max(maxVal), sum(sumVal), squaresSum(squaresSumVal),
mean(meanVal), stdev(stdevVal), minX(minXVal), minY(minYVal), maxX(maxXVal), maxY(maxYVal) {}
};
struct StatsBaton {
// Input
sharp::InputDescriptor *input;
// Output
std::vector<ChannelStats> channelStats;
bool isOpaque;
double entropy;
double sharpness;
int dominantRed;
int dominantGreen;
int dominantBlue;
std::string err;
StatsBaton():
input(nullptr),
isOpaque(true),
entropy(0.0),
sharpness(0.0),
dominantRed(0),
dominantGreen(0),
dominantBlue(0)
{}
};
Napi::Value stats(const Napi::CallbackInfo& info);
#endif // SRC_STATS_H_

286
src/utilities.cc Normal file
View File

@ -0,0 +1,286 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
#include <cmath>
#include <string>
#include <cstdio>
#include <napi.h>
#include <vips/vips8>
#include <vips/vector.h>
#include "common.h"
#include "operations.h"
#include "utilities.h"
/*
Get and set cache limits
*/
Napi::Value cache(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
// Set memory limit
if (info[size_t(0)].IsNumber()) {
vips_cache_set_max_mem(info[size_t(0)].As<Napi::Number>().Int32Value() * 1048576);
}
// Set file limit
if (info[size_t(1)].IsNumber()) {
vips_cache_set_max_files(info[size_t(1)].As<Napi::Number>().Int32Value());
}
// Set items limit
if (info[size_t(2)].IsNumber()) {
vips_cache_set_max(info[size_t(2)].As<Napi::Number>().Int32Value());
}
// Get memory stats
Napi::Object memory = Napi::Object::New(env);
memory.Set("current", round(vips_tracked_get_mem() / 1048576));
memory.Set("high", round(vips_tracked_get_mem_highwater() / 1048576));
memory.Set("max", round(vips_cache_get_max_mem() / 1048576));
// Get file stats
Napi::Object files = Napi::Object::New(env);
files.Set("current", vips_tracked_get_files());
files.Set("max", vips_cache_get_max_files());
// Get item stats
Napi::Object items = Napi::Object::New(env);
items.Set("current", vips_cache_get_size());
items.Set("max", vips_cache_get_max());
Napi::Object cache = Napi::Object::New(env);
cache.Set("memory", memory);
cache.Set("files", files);
cache.Set("items", items);
return cache;
}
/*
Get and set size of thread pool
*/
Napi::Value concurrency(const Napi::CallbackInfo& info) {
// Set concurrency
if (info[size_t(0)].IsNumber()) {
vips_concurrency_set(info[size_t(0)].As<Napi::Number>().Int32Value());
}
// Get concurrency
return Napi::Number::New(info.Env(), vips_concurrency_get());
}
/*
Get internal counters (queued tasks, processing tasks)
*/
Napi::Value counters(const Napi::CallbackInfo& info) {
Napi::Object counters = Napi::Object::New(info.Env());
counters.Set("queue", static_cast<int>(sharp::counterQueue));
counters.Set("process", static_cast<int>(sharp::counterProcess));
return counters;
}
/*
Get and set use of SIMD vector unit instructions
*/
Napi::Value simd(const Napi::CallbackInfo& info) {
// Set state
if (info[size_t(0)].IsBoolean()) {
vips_vector_set_enabled(info[size_t(0)].As<Napi::Boolean>().Value());
}
// Get state
return Napi::Boolean::New(info.Env(), vips_vector_isenabled());
}
/*
Get libvips version
*/
Napi::Value libvipsVersion(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::Object version = Napi::Object::New(env);
char semver[9];
std::snprintf(semver, sizeof(semver), "%d.%d.%d", vips_version(0), vips_version(1), vips_version(2));
version.Set("semver", Napi::String::New(env, semver));
#ifdef SHARP_USE_GLOBAL_LIBVIPS
version.Set("isGlobal", Napi::Boolean::New(env, true));
#else
version.Set("isGlobal", Napi::Boolean::New(env, false));
#endif
#ifdef __EMSCRIPTEN__
version.Set("isWasm", Napi::Boolean::New(env, true));
#else
version.Set("isWasm", Napi::Boolean::New(env, false));
#endif
return version;
}
/*
Get available input/output file/buffer/stream formats
*/
Napi::Value format(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::Object format = Napi::Object::New(env);
for (std::string const f : {
"jpeg", "png", "webp", "tiff", "magick", "openslide", "dz",
"ppm", "fits", "gif", "svg", "heif", "pdf", "vips", "jp2k", "jxl", "rad", "dcraw"
}) {
// Input
const VipsObjectClass *oc = vips_class_find("VipsOperation", (f + "load").c_str());
Napi::Boolean hasInputFile = Napi::Boolean::New(env, oc);
Napi::Boolean hasInputBuffer =
Napi::Boolean::New(env, vips_type_find("VipsOperation", (f + "load_buffer").c_str()));
Napi::Object input = Napi::Object::New(env);
input.Set("file", hasInputFile);
input.Set("buffer", 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
Napi::Boolean hasOutputFile =
Napi::Boolean::New(env, vips_type_find("VipsOperation", (f + "save").c_str()));
Napi::Boolean hasOutputBuffer =
Napi::Boolean::New(env, vips_type_find("VipsOperation", (f + "save_buffer").c_str()));
Napi::Object output = Napi::Object::New(env);
output.Set("file", hasOutputFile);
output.Set("buffer", hasOutputBuffer);
output.Set("stream", hasOutputBuffer);
// Other attributes
Napi::Object container = Napi::Object::New(env);
container.Set("id", f);
container.Set("input", input);
container.Set("output", output);
// Add to set of formats
format.Set(f, container);
}
// Raw, uncompressed data
Napi::Boolean supported = Napi::Boolean::New(env, true);
Napi::Boolean unsupported = Napi::Boolean::New(env, false);
Napi::Object rawInput = Napi::Object::New(env);
rawInput.Set("file", unsupported);
rawInput.Set("buffer", supported);
rawInput.Set("stream", supported);
Napi::Object rawOutput = Napi::Object::New(env);
rawOutput.Set("file", unsupported);
rawOutput.Set("buffer", supported);
rawOutput.Set("stream", supported);
Napi::Object raw = Napi::Object::New(env);
raw.Set("id", "raw");
raw.Set("input", rawInput);
raw.Set("output", rawOutput);
format.Set("raw", raw);
return format;
}
/*
(Un)block libvips operations at runtime.
*/
void block(const Napi::CallbackInfo& info) {
Napi::Array ops = info[size_t(0)].As<Napi::Array>();
bool const state = info[size_t(1)].As<Napi::Boolean>().Value();
for (unsigned int i = 0; i < ops.Length(); i++) {
vips_operation_block_set(ops.Get(i).As<Napi::String>().Utf8Value().c_str(), state);
}
}
/*
Synchronous, internal-only method used by some of the functional tests.
Calculates the maximum colour distance using the DE2000 algorithm
between two images of the same dimensions and number of channels.
*/
Napi::Value _maxColourDistance(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
// Open input files
VImage image1;
sharp::ImageType imageType1 = sharp::DetermineImageType(info[size_t(0)].As<Napi::String>().Utf8Value().data());
if (imageType1 != sharp::ImageType::UNKNOWN) {
try {
image1 = VImage::new_from_file(info[size_t(0)].As<Napi::String>().Utf8Value().c_str());
} catch (...) {
throw Napi::Error::New(env, "Input file 1 has corrupt header");
}
} else {
throw Napi::Error::New(env, "Input file 1 is of an unsupported image format");
}
VImage image2;
sharp::ImageType imageType2 = sharp::DetermineImageType(info[size_t(1)].As<Napi::String>().Utf8Value().data());
if (imageType2 != sharp::ImageType::UNKNOWN) {
try {
image2 = VImage::new_from_file(info[size_t(1)].As<Napi::String>().Utf8Value().c_str());
} catch (...) {
throw Napi::Error::New(env, "Input file 2 has corrupt header");
}
} else {
throw Napi::Error::New(env, "Input file 2 is of an unsupported image format");
}
// Ensure same number of channels
if (image1.bands() != image2.bands()) {
throw Napi::Error::New(env, "mismatchedBands");
}
// Ensure same dimensions
if (image1.width() != image2.width() || image1.height() != image2.height()) {
throw Napi::Error::New(env, "mismatchedDimensions");
}
double maxColourDistance;
try {
// Premultiply and remove alpha
if (image1.has_alpha()) {
image1 = image1.premultiply().extract_band(1, VImage::option()->set("n", image1.bands() - 1));
}
if (image2.has_alpha()) {
image2 = image2.premultiply().extract_band(1, VImage::option()->set("n", image2.bands() - 1));
}
// Calculate colour distance
maxColourDistance = image1.dE00(image2).max();
} catch (vips::VError const &err) {
throw Napi::Error::New(env, err.what());
}
// Clean up libvips' per-request data and threads
vips_error_clear();
vips_thread_shutdown();
return Napi::Number::New(env, maxColourDistance);
}
#if defined(__GNUC__)
// mallctl will be resolved by the runtime linker when jemalloc is being used
extern "C" {
int mallctl(const char *name, void *oldp, size_t *oldlenp, void *newp, size_t newlen) __attribute__((weak));
}
Napi::Value _isUsingJemalloc(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
return Napi::Boolean::New(env, mallctl != nullptr);
}
#else
Napi::Value _isUsingJemalloc(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
return Napi::Boolean::New(env, false);
}
#endif
#if defined(__GNUC__) && defined(__x86_64__)
// Are SSE 4.2 intrinsics available at runtime?
Napi::Value _isUsingX64V2(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
unsigned int eax, ebx, ecx, edx;
__asm__ __volatile__("cpuid"
: "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx)
: "a"(1));
return Napi::Boolean::New(env, (ecx & 1U << 20) != 0);
}
#else
Napi::Value _isUsingX64V2(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
return Napi::Boolean::New(env, false);
}
#endif

20
src/utilities.h Normal file
View File

@ -0,0 +1,20 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
#ifndef SRC_UTILITIES_H_
#define SRC_UTILITIES_H_
#include <napi.h>
Napi::Value cache(const Napi::CallbackInfo& info);
Napi::Value concurrency(const Napi::CallbackInfo& info);
Napi::Value counters(const Napi::CallbackInfo& info);
Napi::Value simd(const Napi::CallbackInfo& info);
Napi::Value libvipsVersion(const Napi::CallbackInfo& info);
Napi::Value format(const Napi::CallbackInfo& info);
void block(const Napi::CallbackInfo& info);
Napi::Value _maxColourDistance(const Napi::CallbackInfo& info);
Napi::Value _isUsingJemalloc(const Napi::CallbackInfo& info);
Napi::Value _isUsingX64V2(const Napi::CallbackInfo& info);
#endif // SRC_UTILITIES_H_

24
test/beforeEach.js Normal file
View File

@ -0,0 +1,24 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'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();
}
}
};

28
test/bench/Dockerfile Normal file
View File

@ -0,0 +1,28 @@
FROM ubuntu:25.04
ARG BRANCH=main
# Install basic dependencies
RUN apt-get -y update && apt-get install -y build-essential curl git ca-certificates gnupg
# Install latest Node.js LTS
RUN curl -fsSL https://deb.nodesource.com/setup_24.x -o nodesource_setup.sh
RUN bash nodesource_setup.sh
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" ]

22
test/bench/package.json Normal file
View File

@ -0,0 +1,22 @@
{
"name": "sharp-benchmark",
"version": "0.0.1",
"private": true,
"author": "Lovell Fuller <npm@lovell.info>",
"description": "Benchmark and performance tests for sharp",
"scripts": {
"test": "node perf && node random && node parallel"
},
"dependencies": {
"async": "3.2.6",
"benchmark": "2.1.4",
"gm": "1.25.1",
"imagemagick": "0.1.3",
"jimp": "1.6.0"
},
"optionalDependencies": {
"@tensorflow/tfjs-node": "4.22.0",
"mapnik": "4.5.9"
},
"license": "Apache-2.0"
}

47
test/bench/parallel.js Normal file
View File

@ -0,0 +1,47 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
process.env.UV_THREADPOOL_SIZE = 64;
const assert = require('assert');
const async = require('async');
const sharp = require('../../');
const fixtures = require('../fixtures');
const width = 720;
const height = 480;
sharp.concurrency(1);
const timer = setInterval(function () {
console.dir(sharp.counters());
}, 100);
async.mapSeries([1, 1, 2, 4, 8, 16, 32, 64], function (parallelism, next) {
const start = new Date().getTime();
async.times(parallelism,
function (id, callback) {
/* jslint unused: false */
sharp(fixtures.inputJpg).resize(width, height).toBuffer(function (err, buffer) {
buffer = null;
callback(err, new Date().getTime() - start);
});
},
function (err, ids) {
assert(!err);
assert(ids.length === parallelism);
ids.sort();
const mean = ids.reduce(function (a, b) {
return a + b;
}) / ids.length;
console.log(parallelism + ' parallel calls: fastest=' + ids[0] + 'ms slowest=' + ids[ids.length - 1] + 'ms mean=' + mean + 'ms');
next();
}
);
}, function () {
clearInterval(timer);
console.dir(sharp.counters());
});

899
test/bench/perf.js Normal file
View File

@ -0,0 +1,899 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
const fs = require('fs');
const { execSync } = require('child_process');
const async = require('async');
const Benchmark = require('benchmark');
const safeRequire = (name) => {
try {
return require(name);
} catch (err) {}
return null;
};
// Contenders
const sharp = require('../../');
const gm = require('gm');
const imagemagick = require('imagemagick');
const mapnik = safeRequire('mapnik');
const { Jimp, JimpMime } = require('jimp');
process.env.TF_CPP_MIN_LOG_LEVEL = 1;
const tfjs = safeRequire('@tensorflow/tfjs-node');
const fixtures = require('../fixtures');
const outputJpg = fixtures.path('output.jpg');
const outputPng = fixtures.path('output.png');
const outputWebP = fixtures.path('output.webp');
const width = 720;
const height = 588;
const heightPng = 540;
// Disable libvips cache to ensure tests are as fair as they can be
sharp.cache(false);
// Spawn one thread per physical CPU core
const physicalCores = Number(execSync('lscpu -p | egrep -v "^#" | sort -u -t, -k 2,4 | wc -l', { encoding: 'utf-8' }).trim());
console.log(`Detected ${physicalCores} physical cores`);
sharp.concurrency(physicalCores);
async.series({
jpeg: function (callback) {
const inputJpgBuffer = fs.readFileSync(fixtures.inputJpg);
const jpegSuite = new Benchmark.Suite('jpeg');
// jimp
jpegSuite.add('jimp-buffer-buffer', {
defer: true,
fn: async function (deferred) {
const image = await Jimp.read(inputJpgBuffer);
await image
.resize({ w: width, h: height, mode: Jimp.RESIZE_BICUBIC })
.getBuffer(JimpMime.jpeg, { quality: 80 });
deferred.resolve();
}
}).add('jimp-file-file', {
defer: true,
fn: async function (deferred) {
const image = await Jimp.read(fixtures.inputJpg);
await image
.resize({ w: width, h: height, mode: Jimp.RESIZE_BICUBIC })
.getBuffer(JimpMime.jpeg, { quality: 80 });
deferred.resolve();
}
});
// mapnik
mapnik && jpegSuite.add('mapnik-file-file', {
defer: true,
fn: function (deferred) {
mapnik.Image.open(fixtures.inputJpg, function (err, img) {
if (err) throw err;
img
.resize(width, height, {
scaling_method: mapnik.imageScaling.lanczos
})
.save(outputJpg, 'jpeg:quality=80', function (err) {
if (err) throw err;
deferred.resolve();
});
});
}
}).add('mapnik-buffer-buffer', {
defer: true,
fn: function (deferred) {
mapnik.Image.fromBytes(inputJpgBuffer, { max_size: 3000 }, function (err, img) {
if (err) throw err;
img
.resize(width, height, {
scaling_method: mapnik.imageScaling.lanczos
})
.encode('jpeg:quality=80', function (err) {
if (err) throw err;
deferred.resolve();
});
});
}
});
// imagemagick
jpegSuite.add('imagemagick-file-file', {
defer: true,
fn: function (deferred) {
imagemagick.resize({
srcPath: fixtures.inputJpg,
dstPath: outputJpg,
quality: 0.8,
width,
height,
format: 'jpg',
filter: 'Lanczos'
}, function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
});
// gm
jpegSuite.add('gm-buffer-file', {
defer: true,
fn: function (deferred) {
gm(inputJpgBuffer)
.filter('Lanczos')
.resize(width, height)
.quality(80)
.write(outputJpg, function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('gm-buffer-buffer', {
defer: true,
fn: function (deferred) {
gm(inputJpgBuffer)
.filter('Lanczos')
.resize(width, height)
.quality(80)
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('gm-file-file', {
defer: true,
fn: function (deferred) {
gm(fixtures.inputJpg)
.filter('Lanczos')
.resize(width, height)
.quality(80)
.write(outputJpg, function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('gm-file-buffer', {
defer: true,
fn: function (deferred) {
gm(fixtures.inputJpg)
.filter('Lanczos')
.resize(width, height)
.quality(80)
.toBuffer(function (err) {
if (err) {
throw err;
} else {
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
jpegSuite.add('sharp-buffer-file', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height)
.toFile(outputJpg, function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-buffer-buffer', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height)
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-file-file', {
defer: true,
fn: function (deferred) {
sharp(fixtures.inputJpg)
.resize(width, height)
.toFile(outputJpg, function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-stream-stream', {
defer: true,
fn: function (deferred) {
const readable = fs.createReadStream(fixtures.inputJpg);
const writable = fs.createWriteStream(outputJpg);
writable.on('finish', function () {
deferred.resolve();
});
const pipeline = sharp()
.resize(width, height);
readable.pipe(pipeline).pipe(writable);
}
}).add('sharp-file-buffer', {
defer: true,
fn: function (deferred) {
sharp(fixtures.inputJpg)
.resize(width, height)
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-promise', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height)
.toBuffer()
.then(function () {
deferred.resolve();
})
.catch(function (err) {
throw err;
});
}
}).on('cycle', function (event) {
console.log('jpeg ' + String(event.target));
}).on('complete', function () {
callback(null, this.filter('fastest').map('name'));
}).run();
},
// Effect of applying operations
operations: function (callback) {
const inputJpgBuffer = fs.readFileSync(fixtures.inputJpg);
const operationsSuite = new Benchmark.Suite('operations');
operationsSuite.add('sharp-sharpen-mild', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height)
.sharpen()
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-sharpen-radius', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height)
.sharpen(3, 1, 3)
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-blur-mild', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height)
.blur()
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-blur-radius', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height)
.blur(3)
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-gamma', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height)
.gamma()
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-normalise', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height)
.normalise()
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-greyscale', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height)
.greyscale()
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-greyscale-gamma', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height)
.gamma()
.greyscale()
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-progressive', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height)
.jpeg({ progressive: true })
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-without-chroma-subsampling', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height)
.jpeg({ chromaSubsampling: '4:4:4' })
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-rotate', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.rotate(90)
.resize(width, height)
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-without-simd', {
defer: true,
fn: function (deferred) {
sharp.simd(false);
sharp(inputJpgBuffer)
.resize(width, height)
.toBuffer(function (err) {
sharp.simd(true);
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-random-access-read', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer, { sequentialRead: false })
.resize(width, height)
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-crop-entropy', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height, {
fit: 'cover',
position: sharp.strategy.entropy
})
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-crop-attention', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height, {
fit: 'cover',
position: sharp.strategy.attention
})
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).on('cycle', function (event) {
console.log('operations ' + String(event.target));
}).on('complete', function () {
callback(null, this.filter('fastest').map('name'));
}).run();
},
// Comparative speed of kernels
kernels: function (callback) {
const inputJpgBuffer = fs.readFileSync(fixtures.inputJpg);
(new Benchmark.Suite('kernels')).add('sharp-cubic', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height, { kernel: 'cubic' })
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-lanczos2', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height, { kernel: 'lanczos2' })
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-lanczos3', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height, { kernel: 'lanczos3' })
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-mks2013', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height, { kernel: 'mks2013' })
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-mks2021', {
defer: true,
fn: function (deferred) {
sharp(inputJpgBuffer)
.resize(width, height, { kernel: 'mks2021' })
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).on('cycle', function (event) {
console.log('kernels ' + String(event.target));
}).on('complete', function () {
callback(null, this.filter('fastest').map('name'));
}).run();
},
// PNG
png: function (callback) {
const inputPngBuffer = fs.readFileSync(fixtures.inputPngAlphaPremultiplicationLarge);
const pngSuite = new Benchmark.Suite('png');
const minSamples = 64;
// jimp
pngSuite.add('jimp-buffer-buffer', {
defer: true,
fn: async function (deferred) {
const image = await Jimp.read(inputPngBuffer);
await image
.resize({ w: width, h: heightPng, mode: Jimp.RESIZE_BICUBIC })
.getBuffer(JimpMime.png, { deflateLevel: 6, filterType: 0 });
deferred.resolve();
}
}).add('jimp-file-file', {
defer: true,
fn: async function (deferred) {
const image = await Jimp.read(fixtures.inputPngAlphaPremultiplicationLarge);
await image
.resize({ w: width, h: heightPng, mode: Jimp.RESIZE_BICUBIC })
.write(outputPng, { deflateLevel: 6, filterType: 0 });
deferred.resolve();
}
});
// mapnik
mapnik && pngSuite.add('mapnik-file-file', {
defer: true,
fn: function (deferred) {
mapnik.Image.open(fixtures.inputPngAlphaPremultiplicationLarge, function (err, img) {
if (err) throw err;
img.premultiply(function (err, img) {
if (err) throw err;
img.resize(width, heightPng, {
scaling_method: mapnik.imageScaling.lanczos
}, function (err, img) {
if (err) throw err;
img.demultiply(function (err, img) {
if (err) throw err;
img.save(outputPng, 'png32:f=no:z=6', function (err) {
if (err) throw err;
deferred.resolve();
});
});
});
});
});
}
}).add('mapnik-buffer-buffer', {
defer: true,
fn: function (deferred) {
mapnik.Image.fromBytes(inputPngBuffer, { max_size: 3000 }, function (err, img) {
if (err) throw err;
img.premultiply(function (err, img) {
if (err) throw err;
img.resize(width, heightPng, {
scaling_method: mapnik.imageScaling.lanczos
}, function (err, img) {
if (err) throw err;
img.demultiply(function (err, img) {
if (err) throw err;
img.encode('png32:f=no:z=6', function (err) {
if (err) throw err;
deferred.resolve();
});
});
});
});
});
}
});
// imagemagick
pngSuite.add('imagemagick-file-file', {
defer: true,
fn: function (deferred) {
imagemagick.resize({
srcPath: fixtures.inputPngAlphaPremultiplicationLarge,
dstPath: outputPng,
width,
height: heightPng,
filter: 'Lanczos',
customArgs: [
'-define', 'PNG:compression-level=6',
'-define', 'PNG:compression-filter=0'
]
}, function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
});
// gm
pngSuite.add('gm-file-file', {
defer: true,
fn: function (deferred) {
gm(fixtures.inputPngAlphaPremultiplicationLarge)
.filter('Lanczos')
.resize(width, heightPng)
.define('PNG:compression-level=6')
.define('PNG:compression-filter=0')
.write(outputPng, function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('gm-file-buffer', {
defer: true,
fn: function (deferred) {
gm(fixtures.inputPngAlphaPremultiplicationLarge)
.filter('Lanczos')
.resize(width, heightPng)
.define('PNG:compression-level=6')
.define('PNG:compression-filter=0')
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
});
// sharp
pngSuite.add('sharp-buffer-file', {
defer: true,
minSamples,
fn: function (deferred) {
sharp(inputPngBuffer)
.resize(width, heightPng)
.png({ compressionLevel: 6 })
.toFile(outputPng, function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-buffer-buffer', {
defer: true,
minSamples,
fn: function (deferred) {
sharp(inputPngBuffer)
.resize(width, heightPng)
.png({ compressionLevel: 6 })
.toBuffer(function (err, data) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-file-file', {
defer: true,
minSamples,
fn: function (deferred) {
sharp(fixtures.inputPngAlphaPremultiplicationLarge)
.resize(width, heightPng)
.png({ compressionLevel: 6 })
.toFile(outputPng, function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-file-buffer', {
defer: true,
minSamples,
fn: function (deferred) {
sharp(fixtures.inputPngAlphaPremultiplicationLarge)
.resize(width, heightPng)
.png({ compressionLevel: 6 })
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-progressive', {
defer: true,
minSamples,
fn: function (deferred) {
sharp(inputPngBuffer)
.resize(width, heightPng)
.png({ compressionLevel: 6, progressive: true })
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-adaptiveFiltering', {
defer: true,
minSamples,
fn: function (deferred) {
sharp(inputPngBuffer)
.resize(width, heightPng)
.png({ adaptiveFiltering: true, compressionLevel: 6 })
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-compressionLevel=9', {
defer: true,
minSamples,
fn: function (deferred) {
sharp(inputPngBuffer)
.resize(width, heightPng)
.png({ compressionLevel: 9 })
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
});
pngSuite.on('cycle', function (event) {
console.log(' png ' + String(event.target));
}).on('complete', function () {
callback(null, this.filter('fastest').map('name'));
}).run();
},
// WebP
webp: function (callback) {
const inputWebPBuffer = fs.readFileSync(fixtures.inputWebP);
(new Benchmark.Suite('webp')).add('sharp-buffer-file', {
defer: true,
fn: function (deferred) {
sharp(inputWebPBuffer)
.resize(width, height)
.toFile(outputWebP, function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-buffer-buffer', {
defer: true,
fn: function (deferred) {
sharp(inputWebPBuffer)
.resize(width, height)
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-file-file', {
defer: true,
fn: function (deferred) {
sharp(fixtures.inputWebP)
.resize(width, height)
.toFile(outputWebP, function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('sharp-file-buffer', {
defer: true,
fn: function (deferred) {
sharp(fixtures.inputWebP)
.resize(width, height)
.toBuffer(function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).on('cycle', function (event) {
console.log('webp ' + String(event.target));
}).on('complete', function () {
callback(null, this.filter('fastest').map('name'));
}).run();
}
}, function (err, results) {
if (err) {
throw err;
}
Object.keys(results).forEach(function (format) {
if (results[format].toString().substr(0, 5) !== 'sharp') {
console.log('sharp was slower than ' + results[format] + ' for ' + format);
}
});
console.dir(sharp.cache());
});

77
test/bench/random.js Normal file
View File

@ -0,0 +1,77 @@
// Copyright 2013 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
const imagemagick = require('imagemagick');
const gm = require('gm');
const assert = require('assert');
const Benchmark = require('benchmark');
const sharp = require('../../');
const fixtures = require('../fixtures');
sharp.cache(false);
const min = 320;
const max = 960;
const randomDimension = function () {
return Math.ceil((Math.random() * (max - min)) + min);
};
new Benchmark.Suite('random').add('imagemagick', {
defer: true,
fn: function (deferred) {
imagemagick.resize({
srcPath: fixtures.inputJpg,
dstPath: fixtures.path('output.jpg'),
quality: 0.8,
width: randomDimension(),
height: randomDimension(),
format: 'jpg',
filter: 'Lanczos'
}, function (err) {
if (err) {
throw err;
} else {
deferred.resolve();
}
});
}
}).add('gm', {
defer: true,
fn: function (deferred) {
gm(fixtures.inputJpg)
.resize(randomDimension(), randomDimension())
.filter('Lanczos')
.quality(80)
.toBuffer(function (err, buffer) {
if (err) {
throw err;
} else {
assert.notStrictEqual(null, buffer);
deferred.resolve();
}
});
}
}).add('sharp', {
defer: true,
fn: function (deferred) {
sharp(fixtures.inputJpg)
.resize(randomDimension(), randomDimension())
.toBuffer(function (err, buffer) {
if (err) {
throw err;
} else {
assert.notStrictEqual(null, buffer);
deferred.resolve();
}
});
}
}).on('cycle', function (event) {
console.log(String(event.target));
}).on('complete', function () {
const winner = this.filter('fastest').map('name');
assert.strictEqual('sharp', String(winner), 'sharp was slower than ' + winner);
}).run();

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

BIN
test/fixtures/16-bit-grey-alpha.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

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