Compare commits
557 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
276ac2df8d | ||
|
|
2dedcf35a0 | ||
|
|
92f21451c1 | ||
|
|
2cd2f8430a | ||
|
|
8ee8d273ee | ||
|
|
4e3f3792ad | ||
|
|
df5454e7dc | ||
|
|
32cf6be1b8 | ||
|
|
96dfd400b2 | ||
|
|
1422798c1d | ||
|
|
e26d4e9d5b | ||
|
|
852c7f8663 | ||
|
|
e286e2bff9 | ||
|
|
76995deefa | ||
|
|
e688c53659 | ||
|
|
c4b1d80c35 | ||
|
|
f92540f134 | ||
|
|
8c53d499f7 | ||
|
|
9392b8702b | ||
|
|
8669fbc936 | ||
|
|
cab02463ec | ||
|
|
5374b036f3 | ||
|
|
327a6d2083 | ||
|
|
751f9992c4 | ||
|
|
01f6cbbaee | ||
|
|
99be893dd4 | ||
|
|
4d1f7e051d | ||
|
|
91f1b58f31 | ||
|
|
6d04b7c1fa | ||
|
|
d4b30b7392 | ||
|
|
7f03502003 | ||
|
|
63b0a11b5b | ||
|
|
c4d6aec48c | ||
|
|
e75ae970ed | ||
|
|
956d72ddc0 | ||
|
|
00e66efbee | ||
|
|
db3a4528eb | ||
|
|
d36fd5064d | ||
|
|
8e17c6f518 | ||
|
|
94481a967e | ||
|
|
32872ef840 | ||
|
|
7c7f960b60 | ||
|
|
0b5f131df8 | ||
|
|
e922ef7450 | ||
|
|
73bec629cf | ||
|
|
758d7e63cc | ||
|
|
eba3e9aeb2 | ||
|
|
701143afb3 | ||
|
|
38b6f44611 | ||
|
|
5b5dfbad77 | ||
|
|
a642767329 | ||
|
|
5cae1abe8f | ||
|
|
66ffc48707 | ||
|
|
3c7dbb8fba | ||
|
|
a9e191328f | ||
|
|
7323dbee98 | ||
|
|
d7a771ca7a | ||
|
|
7d0585fad1 | ||
|
|
ddc1eb8c4c | ||
|
|
c26e67cc5b | ||
|
|
a00ee26d17 | ||
|
|
6dfb60cda2 | ||
|
|
dbb7606129 | ||
|
|
031c808aa5 | ||
|
|
03e1b19764 | ||
|
|
3e41f8b65e | ||
|
|
3fd818c4b5 | ||
|
|
d419aba76d | ||
|
|
3fb1091114 | ||
|
|
2035492fd9 | ||
|
|
5ee83d13e2 | ||
|
|
0d04e9dba3 | ||
|
|
f3a4f060c6 | ||
|
|
3c177af594 | ||
|
|
9d40a64120 | ||
|
|
fda06a62b0 | ||
|
|
75a135eabe | ||
|
|
c9850afe67 | ||
|
|
a619f29313 | ||
|
|
9b88547f12 | ||
|
|
8e3ec0fc61 | ||
|
|
edad89c531 | ||
|
|
9d01dd20bf | ||
|
|
5ab9168813 | ||
|
|
67ff930535 | ||
|
|
ae5ba702a4 | ||
|
|
63f0ab5e20 | ||
|
|
eeac8d4656 | ||
|
|
14c83e1f4c | ||
|
|
b7ff2645c4 | ||
|
|
79ac524262 | ||
|
|
92083ea64c | ||
|
|
82dc859a49 | ||
|
|
bee1fbaa34 | ||
|
|
eba82a8ba5 | ||
|
|
06b08bf10f | ||
|
|
7bdf419eb1 | ||
|
|
04e7f58cea | ||
|
|
3796dd8a87 | ||
|
|
8afec170ed | ||
|
|
3154af776e | ||
|
|
6480a94181 | ||
|
|
9582b5036f | ||
|
|
1533bf995a | ||
|
|
a53d7cb6bf | ||
|
|
b249357732 | ||
|
|
807d9241bd | ||
|
|
9bfaca2857 | ||
|
|
c26b77683a | ||
|
|
7ee54810d4 | ||
|
|
fc32e0bd3f | ||
|
|
0546e48467 | ||
|
|
ab65b7a0f1 | ||
|
|
2474bd4163 | ||
|
|
ff2e689d35 | ||
|
|
6327f13717 | ||
|
|
f1e69a218e | ||
|
|
3c14dbb21e | ||
|
|
82cebc31d0 | ||
|
|
ad36fa0605 | ||
|
|
de42667767 | ||
|
|
2eb03b0049 | ||
|
|
f7ed9b7fb6 | ||
|
|
7fbb988180 | ||
|
|
490210fc60 | ||
|
|
735fee74db | ||
|
|
67a5854b89 | ||
|
|
f128ebdbd4 | ||
|
|
2672de2480 | ||
|
|
67a4592756 | ||
|
|
10c6f474d9 | ||
|
|
d642108be2 | ||
|
|
c2a024101b | ||
|
|
2f0bbebfc9 | ||
|
|
60c5c5083d | ||
|
|
eab7dc1b49 | ||
|
|
5c7f37a0e0 | ||
|
|
ae06f46914 | ||
|
|
9c05ea8dd2 | ||
|
|
472aaf3311 | ||
|
|
56fae3eda1 | ||
|
|
cc96c21e42 | ||
|
|
1d344888ec | ||
|
|
bee235ee76 | ||
|
|
19d0e272e6 | ||
|
|
16b764f1c1 | ||
|
|
1593ee3838 | ||
|
|
668b5ba8bc | ||
|
|
29336f4cc7 | ||
|
|
b5fddd7c5e | ||
|
|
da655a1859 | ||
|
|
93c615d39f | ||
|
|
f325dc3ec9 | ||
|
|
0fde71c783 | ||
|
|
9c8fbaa1cc | ||
|
|
a9e662e612 | ||
|
|
ba843002be | ||
|
|
7f3d452bc5 | ||
|
|
aa8bc19362 | ||
|
|
36e60bf040 | ||
|
|
a1309aa3b8 | ||
|
|
3e8a0fc522 | ||
|
|
397ee492d9 | ||
|
|
52b9dc0f63 | ||
|
|
a715c73fc2 | ||
|
|
579cf93030 | ||
|
|
f67228e5ea | ||
|
|
6257994746 | ||
|
|
7950fc0ea3 | ||
|
|
fc93ab3b82 | ||
|
|
0981b24f60 | ||
|
|
02fd565476 | ||
|
|
e55bb93b10 | ||
|
|
55466f122c | ||
|
|
ede8217ab3 | ||
|
|
2689fb4e65 | ||
|
|
eaf31a59e5 | ||
|
|
aa1bbcb5c1 | ||
|
|
3c26080c39 | ||
|
|
dc07fd4e9c | ||
|
|
7bc74feb11 | ||
|
|
c5f318ed4d | ||
|
|
8fbb1cd154 | ||
|
|
88aee8a887 | ||
|
|
0f77b18078 | ||
|
|
3eeaee71c0 | ||
|
|
045d54e2e6 | ||
|
|
75fedf1b75 | ||
|
|
debdacb726 | ||
|
|
1c8ae67ed2 | ||
|
|
0eb57698ec | ||
|
|
bc95531f2d | ||
|
|
60f4048d6c | ||
|
|
fb70fbb09f | ||
|
|
fc439bedf1 | ||
|
|
26d0b7147d | ||
|
|
af6aa8a690 | ||
|
|
bd4f1abba2 | ||
|
|
d2656a3679 | ||
|
|
a3b45ceccc | ||
|
|
0dcc7d50a8 | ||
|
|
bcb22af034 | ||
|
|
d04dc62666 | ||
|
|
c30d355f97 | ||
|
|
49cb148b38 | ||
|
|
3bc31a8b20 | ||
|
|
c28523e70e | ||
|
|
278f393f74 | ||
|
|
cbf68c1395 | ||
|
|
45e8071599 | ||
|
|
b96389d975 | ||
|
|
a77ac6ae25 | ||
|
|
9bcf399b4c | ||
|
|
4aacee8055 | ||
|
|
0b18aeff62 | ||
|
|
bed1c2ac18 | ||
|
|
8cd832656b | ||
|
|
0499f59e71 | ||
|
|
1fa59bf9b3 | ||
|
|
db40ee6912 | ||
|
|
02b98b8e1b | ||
|
|
31fef216e4 | ||
|
|
77ab5d7a51 | ||
|
|
cd5cf7ce2d | ||
|
|
39cb9d9a6c | ||
|
|
4919bc5134 | ||
|
|
a4e64eb01f | ||
|
|
328b18df88 | ||
|
|
5e7bf32e5e | ||
|
|
04403f4e5f | ||
|
|
420e0822b4 | ||
|
|
f7a3ea6415 | ||
|
|
f28e79ef4f | ||
|
|
5cd787bf85 | ||
|
|
021d637fd6 | ||
|
|
2e14096af7 | ||
|
|
fe2b298a2f | ||
|
|
c9e3996007 | ||
|
|
3a0c375692 | ||
|
|
c5eaeb2ddb | ||
|
|
19fa4cd1d3 | ||
|
|
0adf7ef16f | ||
|
|
8f7fb96a44 | ||
|
|
9e3b021b1a | ||
|
|
25164d4cef | ||
|
|
516b1ec332 | ||
|
|
95ba045a69 | ||
|
|
6e02f9288e | ||
|
|
a584ae093e | ||
|
|
1592f96b7b | ||
|
|
004fff975f | ||
|
|
4d049ee8f5 | ||
|
|
c80e92fa16 | ||
|
|
545e09fad2 | ||
|
|
133dc56ff4 | ||
|
|
9c877d93fa | ||
|
|
7ad86fed03 | ||
|
|
31cf07f0ba | ||
|
|
4ffb48711a | ||
|
|
3da96a86e6 | ||
|
|
45ed9ea9bf | ||
|
|
61057f25bc | ||
|
|
68ef72cb61 | ||
|
|
ef32dccb83 | ||
|
|
e78200cc84 | ||
|
|
3f7313d031 | ||
|
|
139e4b9f65 | ||
|
|
9680f00ddd | ||
|
|
0b0ebfe6f8 | ||
|
|
5aadb8294c | ||
|
|
ace1681886 | ||
|
|
75ef61a958 | ||
|
|
2dba5b5451 | ||
|
|
a8f68ba7f0 | ||
|
|
475bf16b09 | ||
|
|
67f49a8dcd | ||
|
|
074004392c | ||
|
|
8c5a493f68 | ||
|
|
cccd1635c5 | ||
|
|
1915c1387e | ||
|
|
4a37a27cca | ||
|
|
ab8a4ed532 | ||
|
|
12fd512b83 | ||
|
|
239435a6dc | ||
|
|
7c1551bdc9 | ||
|
|
bdcf02695f | ||
|
|
d206fd5392 | ||
|
|
0bd1715f36 | ||
|
|
2e7c60675b | ||
|
|
7caaa8e22b | ||
|
|
839c92bf3d | ||
|
|
28aa176957 | ||
|
|
0f24f0f214 | ||
|
|
655da113c8 | ||
|
|
159b986cdd | ||
|
|
069d1786f5 | ||
|
|
f43829a16a | ||
|
|
65e61ad001 | ||
|
|
0107a4de81 | ||
|
|
337ce7b1c2 | ||
|
|
3719f79065 | ||
|
|
8d1747aa6a | ||
|
|
de9bdcba0a | ||
|
|
f8b6cb6d5b | ||
|
|
e6942805b4 | ||
|
|
47e76c9981 | ||
|
|
68fa84ef6f | ||
|
|
ff2fb18c76 | ||
|
|
28a9b1e9fa | ||
|
|
6377d5a73a | ||
|
|
80e4707af1 | ||
|
|
ab00e34d0d | ||
|
|
7c2f883b67 | ||
|
|
9b5eecba8f | ||
|
|
4b028edfe9 | ||
|
|
7e25dd7be1 | ||
|
|
09460d7af4 | ||
|
|
3b22640077 | ||
|
|
946976ba8f | ||
|
|
29a83250a4 | ||
|
|
3f54ef7525 | ||
|
|
4dc2467f49 | ||
|
|
f54ceb0973 | ||
|
|
8d033ae341 | ||
|
|
f7da2e5970 | ||
|
|
51e56f994c | ||
|
|
68ac12292c | ||
|
|
a9aa7339ce | ||
|
|
08108f5fad | ||
|
|
58e3c4c70e | ||
|
|
f8cf25ca56 | ||
|
|
ca95979ecc | ||
|
|
392f6afb5e | ||
|
|
7c97aabaf8 | ||
|
|
fcc7e84bee | ||
|
|
226a9a13ef | ||
|
|
4d3c9ae3d1 | ||
|
|
f31011d759 | ||
|
|
7cf4ae5648 | ||
|
|
9161c605e1 | ||
|
|
70ac6905c7 | ||
|
|
265d70111a | ||
|
|
59327bdd53 | ||
|
|
3043e01171 | ||
|
|
36feb7551b | ||
|
|
a41c62be2b | ||
|
|
854ed65016 | ||
|
|
8f63d131a4 | ||
|
|
70a3067963 | ||
|
|
aabbe1fa08 | ||
|
|
0f8bb9196e | ||
|
|
efee9f1779 | ||
|
|
61c5cb4669 | ||
|
|
e618c17bd0 | ||
|
|
6578118f32 | ||
|
|
ba20b8ada4 | ||
|
|
eefaa99872 | ||
|
|
dbce6fab79 | ||
|
|
af0fcb37c2 | ||
|
|
c6f54e59da | ||
|
|
846563e45f | ||
|
|
9c217ab580 | ||
|
|
e7381e522e | ||
|
|
4340d60ccf | ||
|
|
7f64d464de | ||
|
|
67e927bdb6 | ||
|
|
9c7713ed54 | ||
|
|
8be6da1def | ||
|
|
95635683ac | ||
|
|
44a0ee3fd3 | ||
|
|
ccd51c8cbf | ||
|
|
bb7469b2d1 | ||
|
|
a2cac61209 | ||
|
|
5c19f6dd9b | ||
|
|
3d01775972 | ||
|
|
87562a5111 | ||
|
|
2829e17743 | ||
|
|
ffefbd2ecc | ||
|
|
bc8f983329 | ||
|
|
440936a699 | ||
|
|
0bc79cdb95 | ||
|
|
9a66e25f53 | ||
|
|
8370935ccf | ||
|
|
f908987f35 | ||
|
|
aea368a3a0 | ||
|
|
7ecbc20d3d | ||
|
|
cb0e2a91c4 | ||
|
|
739b317a6f | ||
|
|
a0e1c39785 | ||
|
|
85b26dab68 | ||
|
|
66f7cef253 | ||
|
|
863174f201 | ||
|
|
bcd865cc96 | ||
|
|
16ea04fe80 | ||
|
|
9c547dc321 | ||
|
|
5522060e9e | ||
|
|
d2f0fa855b | ||
|
|
2bb3ea8170 | ||
|
|
3434eef5b9 | ||
|
|
2f67823c3d | ||
|
|
38c760cdd7 | ||
|
|
14c3346800 | ||
|
|
0da55bab7e | ||
|
|
cfb659f576 | ||
|
|
cc5ac5385f | ||
|
|
93fafb0c18 | ||
|
|
41e3c8ca09 | ||
|
|
da61ea0199 | ||
|
|
7e6a70af44 | ||
|
|
f5845c7e61 | ||
|
|
eb1e53db83 | ||
|
|
3340120aea | ||
|
|
de0fc07092 | ||
|
|
dc4b39f73f | ||
|
|
e873978e53 | ||
|
|
5255964c79 | ||
|
|
dea319daf6 | ||
|
|
a2ca678854 | ||
|
|
e98993a6e2 | ||
|
|
90abd927c9 | ||
|
|
4d7957a043 | ||
|
|
bf9bb56367 | ||
|
|
8408e99aa3 | ||
|
|
a39f959dcc | ||
|
|
d08baa20e6 | ||
|
|
391018ad3d | ||
|
|
afed876f90 | ||
|
|
d6b60a60c6 | ||
|
|
5f8646d937 | ||
|
|
b763801d68 | ||
|
|
2e0f789c9b | ||
|
|
a8645f0f38 | ||
|
|
7b58ad9360 | ||
|
|
9ebbcc3701 | ||
|
|
e87204b92c | ||
|
|
a4c6eba7d4 | ||
|
|
b9c3851515 | ||
|
|
97cf69c26a | ||
|
|
d5be024bfd | ||
|
|
de01fc44e7 | ||
|
|
ca102ebd6c | ||
|
|
b9d4c30a9f | ||
|
|
148760fe55 | ||
|
|
98ed237734 | ||
|
|
b55e58f31e | ||
|
|
0af070ed93 | ||
|
|
9fbb4fcaef | ||
|
|
6008ff8a08 | ||
|
|
cd5e11bd50 | ||
|
|
08d6822265 | ||
|
|
8b8a815fbb | ||
|
|
a44da850c1 | ||
|
|
c5ef4677b1 | ||
|
|
f8a430bdd3 | ||
|
|
cd419a261b | ||
|
|
d7776e3b98 | ||
|
|
1eefd4e562 | ||
|
|
0a16d26ec7 | ||
|
|
fc03fba602 | ||
|
|
c87fe512b4 | ||
|
|
2eaab59c48 | ||
|
|
4ec883eaa0 | ||
|
|
0063df4d4f | ||
|
|
6c61ad256f | ||
|
|
b90474affa | ||
|
|
34cbc6dec3 | ||
|
|
bb8de0cc26 | ||
|
|
863e37455a | ||
|
|
6f0e6f2e65 | ||
|
|
ebf4ccd124 | ||
|
|
b96c8e8ba4 | ||
|
|
42d2f07e44 | ||
|
|
a2988c9edc | ||
|
|
24b3344937 | ||
|
|
9608f219bd | ||
|
|
4798d9da64 | ||
|
|
8d8c6b70eb | ||
|
|
9e2207f376 | ||
|
|
802f560b9b | ||
|
|
a532659b0f | ||
|
|
25c6da2bcd | ||
|
|
02f855d57a | ||
|
|
c150263ef1 | ||
|
|
9f79f80a93 | ||
|
|
069803b83d | ||
|
|
f79760b4f2 | ||
|
|
aa5f0f4e40 | ||
|
|
286a322622 | ||
|
|
6d404f4d2c | ||
|
|
bdc50e1d6e | ||
|
|
a9bd0e79f8 | ||
|
|
a1e464cc5e | ||
|
|
081debd055 | ||
|
|
ef849fd639 | ||
|
|
a42a975c46 | ||
|
|
e8273580af | ||
|
|
5be36c2deb | ||
|
|
6cda090ce2 | ||
|
|
eac6e8b261 | ||
|
|
844deaf480 | ||
|
|
efbb0c22fd | ||
|
|
da0b594900 | ||
|
|
78dada9126 | ||
|
|
15f5cd4671 | ||
|
|
9eb2e94404 | ||
|
|
e40b068628 | ||
|
|
2c46528269 | ||
|
|
584807b4f5 | ||
|
|
a7fa7014ef | ||
|
|
f92e33fbff | ||
|
|
0f1e7ef6f6 | ||
|
|
89e204d824 | ||
|
|
2a71f1830f | ||
|
|
def99a294a | ||
|
|
9d760f3958 | ||
|
|
0265d305fe | ||
|
|
a472aea025 | ||
|
|
01ffa80338 | ||
|
|
789d4851ea | ||
|
|
4490a93430 | ||
|
|
ac0dc10bd5 | ||
|
|
5740f4545e | ||
|
|
a9d692fb43 | ||
|
|
df971207b8 | ||
|
|
3a64a0529a | ||
|
|
76cda885fb | ||
|
|
1a563360c6 | ||
|
|
ca22af203f | ||
|
|
9fa516e849 | ||
|
|
12f472126d | ||
|
|
18be09f1d7 | ||
|
|
b3c3290f90 | ||
|
|
123f95c85a | ||
|
|
5b0fba4c01 | ||
|
|
37f7ccfff4 | ||
|
|
51811d06e2 | ||
|
|
181731f8f4 | ||
|
|
ae79d26ead | ||
|
|
eacb8337fa | ||
|
|
99bf279de8 | ||
|
|
1b0eb6ab53 | ||
|
|
891cf67d0b | ||
|
|
eaf8a86bf2 | ||
|
|
3400976d61 | ||
|
|
2d49f0e93e | ||
|
|
b0c69f1ee9 | ||
|
|
27d0c35a01 | ||
|
|
32a22b5420 | ||
|
|
d1004eed02 | ||
|
|
70e6bb0162 | ||
|
|
32aa3b4b20 | ||
|
|
df24b30755 | ||
|
|
4de74bea94 | ||
|
|
28b87db760 | ||
|
|
fbd4970b57 | ||
|
|
f5da147a58 | ||
|
|
eee0dd36d9 |
@@ -1,79 +0,0 @@
|
|||||||
version: 2.1
|
|
||||||
|
|
||||||
workflows:
|
|
||||||
build:
|
|
||||||
jobs:
|
|
||||||
- linux-arm64-glibc-node-14:
|
|
||||||
filters:
|
|
||||||
tags:
|
|
||||||
only: /^v.*/
|
|
||||||
- linux-arm64-musl-node-14:
|
|
||||||
filters:
|
|
||||||
tags:
|
|
||||||
only: /^v.*/
|
|
||||||
- linux-arm64-glibc-node-18:
|
|
||||||
filters:
|
|
||||||
tags:
|
|
||||||
only: /^v.*/
|
|
||||||
- linux-arm64-musl-node-18:
|
|
||||||
filters:
|
|
||||||
tags:
|
|
||||||
only: /^v.*/
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
linux-arm64-glibc-node-14:
|
|
||||||
resource_class: arm.medium
|
|
||||||
machine:
|
|
||||||
image: ubuntu-2004:current
|
|
||||||
steps:
|
|
||||||
- checkout
|
|
||||||
- run: |
|
|
||||||
sudo docker run -dit --name sharp --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp arm64v8/debian:bullseye
|
|
||||||
sudo docker exec sharp sh -c "apt-get update && apt-get install -y build-essential git python3 curl fonts-noto-core"
|
|
||||||
sudo docker exec sharp sh -c "curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -"
|
|
||||||
sudo docker exec sharp sh -c "echo 'deb https://deb.nodesource.com/node_14.x sid main' >/etc/apt/sources.list.d/nodesource.list"
|
|
||||||
sudo docker exec sharp sh -c "apt-get update && apt-get install -y nodejs"
|
|
||||||
- run: sudo docker exec sharp sh -c "npm install --build-from-source --unsafe-perm"
|
|
||||||
- run: sudo docker exec sharp sh -c "npm test"
|
|
||||||
- run: "[[ -n $CIRCLE_TAG ]] && sudo docker exec --env prebuild_upload sharp sh -c \"npx prebuild --runtime napi --target 7 --upload=$prebuild_upload\" || true"
|
|
||||||
linux-arm64-glibc-node-18:
|
|
||||||
resource_class: arm.medium
|
|
||||||
machine:
|
|
||||||
image: ubuntu-2004:current
|
|
||||||
steps:
|
|
||||||
- checkout
|
|
||||||
- run: |
|
|
||||||
sudo docker run -dit --name sharp --workdir /mnt/sharp arm64v8/debian:bullseye
|
|
||||||
sudo docker exec sharp sh -c "apt-get update && apt-get install -y build-essential git python3 curl fonts-noto-core"
|
|
||||||
sudo docker exec sharp sh -c "curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -"
|
|
||||||
sudo docker exec sharp sh -c "echo 'deb https://deb.nodesource.com/node_18.x sid main' >/etc/apt/sources.list.d/nodesource.list"
|
|
||||||
sudo docker exec sharp sh -c "apt-get update && apt-get install -y nodejs"
|
|
||||||
sudo docker exec sharp sh -c "mkdir -p /mnt/sharp"
|
|
||||||
sudo docker cp . sharp:/mnt/sharp/.
|
|
||||||
- run: sudo docker exec sharp sh -c "npm install --build-from-source"
|
|
||||||
- run: sudo docker exec sharp sh -c "npm test"
|
|
||||||
linux-arm64-musl-node-14:
|
|
||||||
resource_class: arm.medium
|
|
||||||
machine:
|
|
||||||
image: ubuntu-2004:current
|
|
||||||
steps:
|
|
||||||
- checkout
|
|
||||||
- run: |
|
|
||||||
sudo docker run -dit --name sharp --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp node:14-alpine3.12
|
|
||||||
sudo docker exec sharp sh -c "apk add build-base git python3 font-noto --update-cache"
|
|
||||||
- run: sudo docker exec sharp sh -c "npm install --build-from-source --unsafe-perm"
|
|
||||||
- run: sudo docker exec sharp sh -c "npm test"
|
|
||||||
- run: "[[ -n $CIRCLE_TAG ]] && sudo docker exec --env prebuild_upload sharp sh -c \"npx prebuild --runtime napi --target 7 --upload=$prebuild_upload\" || true"
|
|
||||||
linux-arm64-musl-node-18:
|
|
||||||
resource_class: arm.medium
|
|
||||||
machine:
|
|
||||||
image: ubuntu-2004:current
|
|
||||||
steps:
|
|
||||||
- checkout
|
|
||||||
- run: |
|
|
||||||
sudo docker run -dit --name sharp --workdir /mnt/sharp node:18-alpine3.14
|
|
||||||
sudo docker exec sharp sh -c "apk add build-base git python3 font-noto --update-cache"
|
|
||||||
sudo docker exec sharp sh -c "mkdir -p /mnt/sharp"
|
|
||||||
sudo docker cp . sharp:/mnt/sharp/.
|
|
||||||
- run: sudo docker exec sharp sh -c "npm install --build-from-source"
|
|
||||||
- run: sudo docker exec sharp sh -c "npm test"
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
freebsd_instance:
|
freebsd_instance:
|
||||||
image_family: freebsd-14-0-snap
|
image_family: freebsd-15-0-snap
|
||||||
|
|
||||||
task:
|
task:
|
||||||
name: FreeBSD
|
name: FreeBSD
|
||||||
@@ -9,8 +9,9 @@ task:
|
|||||||
prerequisites_script:
|
prerequisites_script:
|
||||||
- pkg update -f
|
- pkg update -f
|
||||||
- pkg upgrade -y
|
- pkg upgrade -y
|
||||||
- pkg install -y devel/pkgconf graphics/vips www/node16 www/npm
|
- pkg install -y devel/git devel/pkgconf graphics/vips www/node20 www/npm
|
||||||
|
- pkg-config --modversion vips-cpp
|
||||||
install_script:
|
install_script:
|
||||||
- npm install --build-from-source --unsafe-perm
|
- npm install --build-from-source
|
||||||
test_script:
|
test_script:
|
||||||
- npm test
|
- npx mocha --no-config --spec=test/unit/io.js --timeout=30000
|
||||||
|
|||||||
1
.gitattributes
vendored
@@ -1 +0,0 @@
|
|||||||
src/libvips/* linguist-vendored
|
|
||||||
3
.github/CONTRIBUTING.md
vendored
@@ -33,6 +33,7 @@ To test C++ changes, you can compile the module using `npm install --build-from-
|
|||||||
|
|
||||||
Please add JavaScript [unit tests](https://github.com/lovell/sharp/tree/main/test/unit) to cover your new feature.
|
Please add JavaScript [unit tests](https://github.com/lovell/sharp/tree/main/test/unit) to cover your new feature.
|
||||||
A test coverage report for the JavaScript code is generated in the `coverage/lcov-report` directory.
|
A test coverage report for the JavaScript code is generated in the `coverage/lcov-report` directory.
|
||||||
|
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
|
Where possible, the functional tests use gradient-based perceptual hashes
|
||||||
based on [dHash](http://www.hackerfactor.com/blog/index.php?/archives/529-Kind-of-Like-That.html)
|
based on [dHash](http://www.hackerfactor.com/blog/index.php?/archives/529-Kind-of-Like-That.html)
|
||||||
@@ -62,7 +63,7 @@ By way of example, the `background()` method present in v0.20.0 was deprecated i
|
|||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
The public API is documented with [JSDoc](http://usejsdoc.org/) annotated comments.
|
The public API is documented with [JSDoc](https://jsdoc.app/) annotated comments.
|
||||||
|
|
||||||
These can be converted to Markdown by running:
|
These can be converted to Markdown by running:
|
||||||
```sh
|
```sh
|
||||||
|
|||||||
38
.github/ISSUE_TEMPLATE/installation.md
vendored
@@ -11,8 +11,10 @@ labels: installation
|
|||||||
|
|
||||||
<!-- Please place an [x] in the box to confirm. -->
|
<!-- Please place an [x] in the box to confirm. -->
|
||||||
|
|
||||||
- [ ] I have read the [documentation relating to installation](https://sharp.pixelplumbing.com/install).
|
- [ ] I have read and understood all of the [documentation relating to installation](https://sharp.pixelplumbing.com/install).
|
||||||
- [ ] I have ensured that the architecture and platform of Node.js used for `npm install` is the same as the architecture and platform of Node.js used at runtime.
|
- [ ] 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?
|
### Are you using the latest version of sharp?
|
||||||
|
|
||||||
@@ -22,15 +24,37 @@ labels: installation
|
|||||||
|
|
||||||
If you cannot confirm this, please upgrade to the latest version and try again before opening an issue.
|
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.
|
If you are using another package which depends on a version of `sharp` that is not the latest,
|
||||||
|
please open an issue against that package instead.
|
||||||
|
|
||||||
### Is this a problem with filesystem permissions?
|
### Are you using a supported runtime?
|
||||||
|
|
||||||
If you are using npm v6 or earlier and installing as a `root` or `sudo` user, have you tried with the `npm install --unsafe-perm` flag?
|
<!-- Please place an [x] in the relevant box to confirm. -->
|
||||||
|
|
||||||
If you are using npm v7 or later, does the user running `npm install` own the directory it is run in?
|
- [ ] 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 are using the `ignore-scripts` feature of `npm`, have you tried with the `npm install --ignore-scripts=false` flag?
|
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?
|
### What is the complete output of running `npm install --verbose --foreground-scripts sharp` in an empty directory?
|
||||||
|
|
||||||
|
|||||||
16
.github/ISSUE_TEMPLATE/possible-bug.md
vendored
@@ -32,6 +32,22 @@ If you are using another package which depends on a version of `sharp` that is n
|
|||||||
|
|
||||||
<!-- Please provide output of the above command here. -->
|
<!-- 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?
|
### What are the steps to reproduce?
|
||||||
|
|
||||||
<!-- Please enter steps to reproduce here. -->
|
<!-- Please enter steps to reproduce here. -->
|
||||||
|
|||||||
18
.github/SECURITY.md
vendored
Normal 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.
|
||||||
36
.github/workflows/ci-darwin-arm64v8.yml
vendored
@@ -1,36 +0,0 @@
|
|||||||
name: CI (MacStadium)
|
|
||||||
on:
|
|
||||||
- push
|
|
||||||
- pull_request
|
|
||||||
jobs:
|
|
||||||
CI:
|
|
||||||
runs-on: macos-m1
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
- nodejs_version: 14
|
|
||||||
nodejs_architecture: x64
|
|
||||||
- nodejs_version: 18
|
|
||||||
nodejs_architecture: arm64
|
|
||||||
prebuild: true
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
shell: /usr/bin/arch -arch arm64e /bin/bash -l {0}
|
|
||||||
steps:
|
|
||||||
- name: Dependencies
|
|
||||||
uses: actions/setup-node@v2
|
|
||||||
with:
|
|
||||||
node-version: ${{ matrix.nodejs_version }}
|
|
||||||
architecture: ${{ matrix.nodejs_architecture }}
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v2
|
|
||||||
- name: Install
|
|
||||||
run: npm install --build-from-source --unsafe-perm
|
|
||||||
- name: Test
|
|
||||||
run: npm test
|
|
||||||
- name: Prebuild
|
|
||||||
if: matrix.prebuild && startsWith(github.ref, 'refs/tags/')
|
|
||||||
env:
|
|
||||||
prebuild_upload: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
run: npx prebuild --runtime napi --target 7
|
|
||||||
356
.github/workflows/ci.yml
vendored
@@ -1,102 +1,324 @@
|
|||||||
name: CI (GitHub)
|
name: CI
|
||||||
on:
|
on:
|
||||||
- push
|
- push
|
||||||
- pull_request
|
- pull_request
|
||||||
|
permissions: {}
|
||||||
jobs:
|
jobs:
|
||||||
CI:
|
build-native:
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
name: "build-${{ matrix.platform }} [Node.js ${{ matrix.nodejs_version_major }}] ${{ matrix.package && '[package]' }}"
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
container: ${{ matrix.container }}
|
container: ${{ matrix.container }}
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
- os: ubuntu-20.04
|
- os: ubuntu-24.04
|
||||||
container: centos:7
|
|
||||||
nodejs_version: 14
|
|
||||||
coverage: true
|
|
||||||
prebuild: true
|
|
||||||
- os: ubuntu-20.04
|
|
||||||
container: centos:7
|
|
||||||
nodejs_version: 16
|
|
||||||
- os: ubuntu-20.04
|
|
||||||
container: rockylinux:8
|
container: rockylinux:8
|
||||||
nodejs_version: 18
|
|
||||||
- os: ubuntu-20.04
|
|
||||||
container: node:14-alpine3.12
|
|
||||||
prebuild: true
|
|
||||||
- os: ubuntu-20.04
|
|
||||||
container: node:16-alpine3.12
|
|
||||||
- os: ubuntu-20.04
|
|
||||||
container: node:18-alpine3.14
|
|
||||||
- os: macos-11
|
|
||||||
nodejs_version: 14
|
|
||||||
prebuild: true
|
|
||||||
nodejs_arch: x64
|
nodejs_arch: x64
|
||||||
- os: macos-11
|
nodejs_version: "^18.17.0"
|
||||||
nodejs_version: 16
|
nodejs_version_major: 18
|
||||||
|
platform: linux-x64
|
||||||
|
package: true
|
||||||
|
- os: ubuntu-24.04
|
||||||
|
container: rockylinux:8
|
||||||
nodejs_arch: x64
|
nodejs_arch: x64
|
||||||
- os: macos-11
|
nodejs_version: "^20.3.0"
|
||||||
nodejs_version: 18
|
nodejs_version_major: 20
|
||||||
|
platform: linux-x64
|
||||||
|
- os: ubuntu-24.04
|
||||||
|
container: rockylinux:8
|
||||||
nodejs_arch: x64
|
nodejs_arch: x64
|
||||||
- os: windows-2019
|
nodejs_version: "^22.9.0"
|
||||||
nodejs_version: 14
|
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_arch: x86
|
||||||
prebuild: true
|
nodejs_version: "18.18.2" # pinned to avoid 18.19.0 and npm 10
|
||||||
- os: windows-2019
|
nodejs_version_major: 18
|
||||||
nodejs_version: 16
|
platform: win32-ia32
|
||||||
|
package: true
|
||||||
|
- os: windows-2022
|
||||||
nodejs_arch: x86
|
nodejs_arch: x86
|
||||||
- os: windows-2019
|
nodejs_version: "^20.3.0"
|
||||||
nodejs_version: 18
|
nodejs_version_major: 20
|
||||||
|
platform: win32-ia32
|
||||||
|
- os: windows-2022
|
||||||
nodejs_arch: x86
|
nodejs_arch: x86
|
||||||
- os: windows-2019
|
nodejs_version: "^22.9.0"
|
||||||
nodejs_version: 14
|
nodejs_version_major: 22
|
||||||
|
platform: win32-ia32
|
||||||
|
- os: windows-2022
|
||||||
nodejs_arch: x64
|
nodejs_arch: x64
|
||||||
prebuild: true
|
nodejs_version: "^18.17.0"
|
||||||
- os: windows-2019
|
nodejs_version_major: 18
|
||||||
nodejs_version: 16
|
platform: win32-x64
|
||||||
|
package: true
|
||||||
|
- os: windows-2022
|
||||||
nodejs_arch: x64
|
nodejs_arch: x64
|
||||||
- os: windows-2019
|
nodejs_version: "^20.3.0"
|
||||||
nodejs_version: 18
|
nodejs_version_major: 20
|
||||||
|
platform: win32-x64
|
||||||
|
- os: windows-2022
|
||||||
nodejs_arch: x64
|
nodejs_arch: x64
|
||||||
|
nodejs_version: "^22.9.0"
|
||||||
|
nodejs_version_major: 22
|
||||||
|
platform: win32-x64
|
||||||
|
- os: windows-11-arm
|
||||||
|
nodejs_arch: arm64
|
||||||
|
nodejs_version: "^20.3.0"
|
||||||
|
nodejs_version_major: 20
|
||||||
|
platform: win32-arm64
|
||||||
|
package: true
|
||||||
|
- os: windows-11-arm
|
||||||
|
nodejs_arch: arm64
|
||||||
|
nodejs_version: "^22.9.0"
|
||||||
|
nodejs_version_major: 22
|
||||||
|
platform: win32-arm64
|
||||||
steps:
|
steps:
|
||||||
- name: Dependencies (Linux glibc)
|
|
||||||
if: contains(matrix.container, 'centos')
|
|
||||||
run: |
|
|
||||||
curl -sL https://rpm.nodesource.com/setup_${{ matrix.nodejs_version }}.x | bash -
|
|
||||||
yum install -y centos-release-scl
|
|
||||||
yum install -y devtoolset-11-gcc-c++ make git python3 nodejs fontconfig google-noto-sans-fonts
|
|
||||||
echo "/opt/rh/devtoolset-11/root/usr/bin" >> $GITHUB_PATH
|
|
||||||
- name: Dependencies (Rocky Linux glibc)
|
- name: Dependencies (Rocky Linux glibc)
|
||||||
if: contains(matrix.container, 'rockylinux')
|
if: contains(matrix.container, 'rockylinux')
|
||||||
run: |
|
run: |
|
||||||
curl -sL https://rpm.nodesource.com/setup_${{ matrix.nodejs_version }}.x | bash -
|
dnf install -y gcc-toolset-14-gcc-c++ make git python3.12 fontconfig google-noto-sans-fonts
|
||||||
dnf install -y gcc-toolset-11-gcc-c++ make git python3 nodejs fontconfig google-noto-sans-fonts
|
echo "/opt/rh/gcc-toolset-14/root/usr/bin" >> $GITHUB_PATH
|
||||||
echo "/opt/rh/gcc-toolset-11/root/usr/bin" >> $GITHUB_PATH
|
|
||||||
- name: Dependencies (Linux musl)
|
- name: Dependencies (Linux musl)
|
||||||
if: contains(matrix.container, 'alpine')
|
if: contains(matrix.container, 'alpine')
|
||||||
run: apk add build-base git python3 font-noto --update-cache
|
run: apk add build-base git python3 font-noto --update-cache
|
||||||
- name: Dependencies (macOS, Windows)
|
- name: Dependencies (Python 3.11 - macOS, Windows)
|
||||||
if: contains(matrix.os, 'macos') || contains(matrix.os, 'windows')
|
if: contains(matrix.os, 'macos') || contains(matrix.os, 'windows')
|
||||||
uses: actions/setup-node@v3
|
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:
|
with:
|
||||||
node-version: ${{ matrix.nodejs_version }}
|
node-version: ${{ matrix.nodejs_version }}
|
||||||
architecture: ${{ matrix.nodejs_arch }}
|
architecture: ${{ matrix.nodejs_arch }}
|
||||||
- name: Checkout
|
- uses: actions/checkout@v4
|
||||||
uses: actions/checkout@v2
|
|
||||||
- name: Fix working directory ownership
|
|
||||||
if: matrix.container
|
|
||||||
run: chown root.root .
|
|
||||||
- name: Install
|
- name: Install
|
||||||
run: npm install --build-from-source --unsafe-perm
|
run: npm install --build-from-source
|
||||||
- name: Test
|
- name: Test
|
||||||
run: npm test
|
run: npm test
|
||||||
- name: Coverage
|
- name: Populate npm package
|
||||||
if: matrix.coverage
|
if: matrix.package
|
||||||
uses: coverallsapp/github-action@v1.1.2
|
run: npm run package-from-local-build
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
if: matrix.package
|
||||||
with:
|
with:
|
||||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
name: ${{ matrix.platform }}
|
||||||
- name: Prebuild
|
path: npm/${{ matrix.platform }}
|
||||||
if: matrix.prebuild && startsWith(github.ref, 'refs/tags/')
|
retention-days: 1
|
||||||
env:
|
if-no-files-found: error
|
||||||
prebuild_upload: ${{ secrets.GITHUB_TOKEN }}
|
build-linuxmusl-arm-64:
|
||||||
run: npx prebuild --runtime napi --target 7
|
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
@@ -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
|
||||||
14
.gitignore
vendored
@@ -1,18 +1,18 @@
|
|||||||
build
|
src/build
|
||||||
|
src/node_modules
|
||||||
node_modules
|
node_modules
|
||||||
/coverage
|
/coverage
|
||||||
|
npm/*/*
|
||||||
|
!npm/*/package.json
|
||||||
test/bench/node_modules
|
test/bench/node_modules
|
||||||
test/fixtures/output*
|
test/fixtures/output*
|
||||||
|
test/fixtures/vips-properties.xml
|
||||||
test/leak/libvips.supp
|
test/leak/libvips.supp
|
||||||
test/saliency/report.json
|
|
||||||
test/saliency/Image*
|
|
||||||
test/saliency/[Uu]serData*
|
|
||||||
!test/saliency/userData.js
|
|
||||||
vendor
|
|
||||||
.gitattributes
|
|
||||||
.DS_Store
|
.DS_Store
|
||||||
.nyc_output
|
.nyc_output
|
||||||
.vscode/
|
.vscode/
|
||||||
package-lock.json
|
package-lock.json
|
||||||
.idea
|
.idea
|
||||||
.firebase
|
.firebase
|
||||||
|
.astro
|
||||||
|
docs/dist
|
||||||
|
|||||||
7
.mocharc.jsonc
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"parallel": true,
|
||||||
|
"slow": 1000,
|
||||||
|
"timeout": 30000,
|
||||||
|
"require": "./test/beforeEach.js",
|
||||||
|
"spec": "./test/unit/*.js"
|
||||||
|
}
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
{
|
|
||||||
"include-regex": "(sharp-.+\\.node|libvips-cpp\\.dll)",
|
|
||||||
"strip": true
|
|
||||||
}
|
|
||||||
15
README.md
@@ -1,11 +1,15 @@
|
|||||||
# sharp
|
# sharp
|
||||||
|
|
||||||
<img src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right">
|
<img src="https://sharp.pixelplumbing.com/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right">
|
||||||
|
|
||||||
The typical use case for this high speed Node.js module
|
The typical use case for this high speed Node-API module
|
||||||
is to convert large images in common formats to
|
is to convert large images in common formats to
|
||||||
smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions.
|
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 or >= 20.3.0), Deno and Bun.
|
||||||
|
|
||||||
Resizing an image is typically 4x-5x faster than using the
|
Resizing an image is typically 4x-5x faster than using the
|
||||||
quickest ImageMagick and GraphicsMagick settings
|
quickest ImageMagick and GraphicsMagick settings
|
||||||
due to its use of [libvips](https://github.com/libvips/libvips).
|
due to its use of [libvips](https://github.com/libvips/libvips).
|
||||||
@@ -16,7 +20,7 @@ Lanczos resampling ensures quality is not sacrificed for speed.
|
|||||||
As well as image resizing, operations such as
|
As well as image resizing, operations such as
|
||||||
rotation, extraction, compositing and gamma correction are available.
|
rotation, extraction, compositing and gamma correction are available.
|
||||||
|
|
||||||
Most modern macOS, Windows and Linux systems running Node.js >= 14.15.0
|
Most modern macOS, Windows and Linux systems
|
||||||
do not require any additional install or runtime dependencies.
|
do not require any additional install or runtime dependencies.
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
@@ -98,12 +102,9 @@ readableStream
|
|||||||
A [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md)
|
A [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md)
|
||||||
covers reporting bugs, requesting features and submitting code changes.
|
covers reporting bugs, requesting features and submitting code changes.
|
||||||
|
|
||||||
[](https://coveralls.io/r/lovell/sharp?branch=main)
|
|
||||||
[](https://nodejs.org/dist/latest/docs/api/n-api.html#n_api_n_api_version_matrix)
|
|
||||||
|
|
||||||
## Licensing
|
## Licensing
|
||||||
|
|
||||||
Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Lovell Fuller and contributors.
|
Copyright 2013 Lovell Fuller and others.
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
|
|||||||
234
binding.gyp
@@ -1,234 +0,0 @@
|
|||||||
{
|
|
||||||
'variables': {
|
|
||||||
'vips_version': '<!(node -p "require(\'./lib/libvips\').minimumLibvipsVersion")',
|
|
||||||
'platform_and_arch': '<!(node -p "require(\'./lib/platform\')()")',
|
|
||||||
'sharp_vendor_dir': './vendor/<(vips_version)/<(platform_and_arch)'
|
|
||||||
},
|
|
||||||
'targets': [{
|
|
||||||
'target_name': 'libvips-cpp',
|
|
||||||
'conditions': [
|
|
||||||
['OS == "win"', {
|
|
||||||
# Build libvips C++ binding for Windows due to MSVC std library ABI changes
|
|
||||||
'type': 'shared_library',
|
|
||||||
'defines': [
|
|
||||||
'VIPS_CPLUSPLUS_EXPORTS',
|
|
||||||
'_ALLOW_KEYWORD_MACROS'
|
|
||||||
],
|
|
||||||
'sources': [
|
|
||||||
'src/libvips/cplusplus/VConnection.cpp',
|
|
||||||
'src/libvips/cplusplus/VError.cpp',
|
|
||||||
'src/libvips/cplusplus/VImage.cpp',
|
|
||||||
'src/libvips/cplusplus/VInterpolate.cpp',
|
|
||||||
'src/libvips/cplusplus/VRegion.cpp'
|
|
||||||
],
|
|
||||||
'include_dirs': [
|
|
||||||
'<(sharp_vendor_dir)/include',
|
|
||||||
'<(sharp_vendor_dir)/include/glib-2.0',
|
|
||||||
'<(sharp_vendor_dir)/lib/glib-2.0/include'
|
|
||||||
],
|
|
||||||
'link_settings': {
|
|
||||||
'library_dirs': ['<(sharp_vendor_dir)/lib'],
|
|
||||||
'libraries': [
|
|
||||||
'libvips.lib',
|
|
||||||
'libglib-2.0.lib',
|
|
||||||
'libgobject-2.0.lib'
|
|
||||||
],
|
|
||||||
},
|
|
||||||
'configurations': {
|
|
||||||
'Release': {
|
|
||||||
'msvs_settings': {
|
|
||||||
'VCCLCompilerTool': {
|
|
||||||
'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': [
|
|
||||||
'NAPI_VERSION=7'
|
|
||||||
],
|
|
||||||
'dependencies': [
|
|
||||||
'<!(node -p "require(\'node-addon-api\').gyp")',
|
|
||||||
'libvips-cpp'
|
|
||||||
],
|
|
||||||
'variables': {
|
|
||||||
'runtime_link%': 'shared',
|
|
||||||
'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': [
|
|
||||||
'src/common.cc',
|
|
||||||
'src/metadata.cc',
|
|
||||||
'src/stats.cc',
|
|
||||||
'src/operations.cc',
|
|
||||||
'src/pipeline.cc',
|
|
||||||
'src/utilities.cc',
|
|
||||||
'src/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)'],
|
|
||||||
'conditions': [
|
|
||||||
['runtime_link == "static"', {
|
|
||||||
'libraries': ['<!@(PKG_CONFIG_PATH="<(pkg_config_path)" pkg-config --libs --static vips-cpp)']
|
|
||||||
}, {
|
|
||||||
'libraries': ['<!@(PKG_CONFIG_PATH="<(pkg_config_path)" pkg-config --libs vips-cpp)']
|
|
||||||
}],
|
|
||||||
['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_vendor_dir)/include',
|
|
||||||
'<(sharp_vendor_dir)/include/glib-2.0',
|
|
||||||
'<(sharp_vendor_dir)/lib/glib-2.0/include'
|
|
||||||
],
|
|
||||||
'conditions': [
|
|
||||||
['OS == "win"', {
|
|
||||||
'defines': [
|
|
||||||
'_ALLOW_KEYWORD_MACROS',
|
|
||||||
'_FILE_OFFSET_BITS=64'
|
|
||||||
],
|
|
||||||
'link_settings': {
|
|
||||||
'library_dirs': ['<(sharp_vendor_dir)/lib'],
|
|
||||||
'libraries': [
|
|
||||||
'libvips.lib',
|
|
||||||
'libglib-2.0.lib',
|
|
||||||
'libgobject-2.0.lib'
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}],
|
|
||||||
['OS == "mac"', {
|
|
||||||
'link_settings': {
|
|
||||||
'library_dirs': ['../<(sharp_vendor_dir)/lib'],
|
|
||||||
'libraries': [
|
|
||||||
'libvips-cpp.42.dylib'
|
|
||||||
]
|
|
||||||
},
|
|
||||||
'xcode_settings': {
|
|
||||||
'OTHER_LDFLAGS': [
|
|
||||||
# Ensure runtime linking is relative to sharp.node
|
|
||||||
'-Wl,-rpath,\'@loader_path/../../<(sharp_vendor_dir)/lib\''
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}],
|
|
||||||
['OS == "linux"', {
|
|
||||||
'defines': [
|
|
||||||
'_GLIBCXX_USE_CXX11_ABI=1'
|
|
||||||
],
|
|
||||||
'link_settings': {
|
|
||||||
'library_dirs': ['../<(sharp_vendor_dir)/lib'],
|
|
||||||
'libraries': [
|
|
||||||
'-l:libvips-cpp.so.42'
|
|
||||||
],
|
|
||||||
'ldflags': [
|
|
||||||
# Ensure runtime linking is relative to sharp.node
|
|
||||||
'-Wl,-s -Wl,--disable-new-dtags -Wl,-rpath=\'$$ORIGIN/../../<(sharp_vendor_dir)/lib\''
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}]
|
|
||||||
]
|
|
||||||
}]
|
|
||||||
],
|
|
||||||
'cflags_cc': [
|
|
||||||
'-std=c++0x',
|
|
||||||
'-fexceptions',
|
|
||||||
'-Wall',
|
|
||||||
'-Os'
|
|
||||||
],
|
|
||||||
'xcode_settings': {
|
|
||||||
'CLANG_CXX_LANGUAGE_STANDARD': 'c++11',
|
|
||||||
'MACOSX_DEPLOYMENT_TARGET': '10.9',
|
|
||||||
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
|
|
||||||
'GCC_ENABLE_CPP_RTTI': 'YES',
|
|
||||||
'OTHER_CPLUSPLUSFLAGS': [
|
|
||||||
'-fexceptions',
|
|
||||||
'-Wall',
|
|
||||||
'-Oz'
|
|
||||||
]
|
|
||||||
},
|
|
||||||
'configurations': {
|
|
||||||
'Release': {
|
|
||||||
'conditions': [
|
|
||||||
['OS == "linux"', {
|
|
||||||
'cflags_cc': [
|
|
||||||
'-Wno-cast-function-type'
|
|
||||||
]
|
|
||||||
}],
|
|
||||||
['target_arch == "arm"', {
|
|
||||||
'cflags_cc': [
|
|
||||||
'-Wno-psabi'
|
|
||||||
]
|
|
||||||
}],
|
|
||||||
['OS == "win"', {
|
|
||||||
'msvs_settings': {
|
|
||||||
'VCCLCompilerTool': {
|
|
||||||
'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
|
|
||||||
]
|
|
||||||
}]
|
|
||||||
]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
@@ -1,150 +0,0 @@
|
|||||||
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
|
|
||||||
|
|
||||||
## tint
|
|
||||||
|
|
||||||
Tint the image using the provided chroma while preserving the image luminance.
|
|
||||||
An alpha channel may be present and will be unchanged by the operation.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `rgb` **([string][1] | [Object][2])** parsed by the [color][3] module to extract chroma values.
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const output = await sharp(input)
|
|
||||||
.tint({ r: 255, g: 240, b: 16 })
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][4]** Invalid parameter
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## greyscale
|
|
||||||
|
|
||||||
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) color channels.
|
|
||||||
This may be overridden by other sharp operations such as `toColourspace('b-w')`,
|
|
||||||
which will produce an output image containing one color channel.
|
|
||||||
An alpha channel may be present, and will be unchanged by the operation.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `greyscale` **[Boolean][5]** (optional, default `true`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const output = await sharp(input).greyscale().toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## grayscale
|
|
||||||
|
|
||||||
Alternative spelling of `greyscale`.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `grayscale` **[Boolean][5]** (optional, default `true`)
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## pipelineColourspace
|
|
||||||
|
|
||||||
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][6].
|
|
||||||
|
|
||||||
This feature is experimental and has not yet been fully-tested with all operations.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `colourspace` **[string][1]?** pipeline colourspace e.g. `rgb16`, `scrgb`, `lab`, `grey16` [...][7]
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// 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')
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][4]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
**Meta**
|
|
||||||
|
|
||||||
* **since**: 0.29.0
|
|
||||||
|
|
||||||
## pipelineColorspace
|
|
||||||
|
|
||||||
Alternative spelling of `pipelineColourspace`.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `colorspace` **[string][1]?** pipeline colorspace.
|
|
||||||
|
|
||||||
<!---->
|
|
||||||
|
|
||||||
* Throws **[Error][4]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## toColourspace
|
|
||||||
|
|
||||||
Set the output colourspace.
|
|
||||||
By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `colourspace` **[string][1]?** output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...][8]
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Output 16 bits per pixel RGB
|
|
||||||
await sharp(input)
|
|
||||||
.toColourspace('rgb16')
|
|
||||||
.toFile('16-bpp.png')
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][4]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## toColorspace
|
|
||||||
|
|
||||||
Alternative spelling of `toColourspace`.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `colorspace` **[string][1]?** output colorspace.
|
|
||||||
|
|
||||||
<!---->
|
|
||||||
|
|
||||||
* Throws **[Error][4]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
|
|
||||||
|
|
||||||
[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
|
|
||||||
|
|
||||||
[3]: https://www.npmjs.org/package/color
|
|
||||||
|
|
||||||
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
|
|
||||||
|
|
||||||
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
|
|
||||||
|
|
||||||
[6]: #tocolourspace
|
|
||||||
|
|
||||||
[7]: https://github.com/libvips/libvips/blob/41cff4e9d0838498487a00623462204eb10ee5b8/libvips/iofuncs/enumtypes.c#L774
|
|
||||||
|
|
||||||
[8]: https://github.com/libvips/libvips/blob/3c0bfdf74ce1dc37a6429bed47fa76f16e2cd70a/libvips/iofuncs/enumtypes.c#L777-L794
|
|
||||||
@@ -1,127 +0,0 @@
|
|||||||
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
|
|
||||||
|
|
||||||
## composite
|
|
||||||
|
|
||||||
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`.
|
|
||||||
|
|
||||||
Any resize or rotate operations in the same processing pipeline
|
|
||||||
will always be applied to the input image before composition.
|
|
||||||
|
|
||||||
The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`,
|
|
||||||
`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][1]
|
|
||||||
and [https://www.cairographics.org/operators/][2]
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `images` **[Array][3]<[Object][4]>** Ordered list of images to composite
|
|
||||||
|
|
||||||
* `images[].input` **([Buffer][5] | [String][6])?** Buffer containing image data, String containing the path to an image file, or Create object (see below)
|
|
||||||
|
|
||||||
* `images[].input.create` **[Object][4]?** describes a blank overlay to be created.
|
|
||||||
|
|
||||||
* `images[].input.create.width` **[Number][7]?** 
|
|
||||||
* `images[].input.create.height` **[Number][7]?** 
|
|
||||||
* `images[].input.create.channels` **[Number][7]?** 3-4
|
|
||||||
* `images[].input.create.background` **([String][6] | [Object][4])?** parsed by the [color][8] module to extract values for red, green, blue and alpha.
|
|
||||||
* `images[].input.text` **[Object][4]?** describes a new text image to be created.
|
|
||||||
|
|
||||||
* `images[].input.text.text` **[string][6]?** text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.
|
|
||||||
* `images[].input.text.font` **[string][6]?** font name to render with.
|
|
||||||
* `images[].input.text.fontfile` **[string][6]?** absolute filesystem path to a font file that can be used by `font`.
|
|
||||||
* `images[].input.text.width` **[number][7]** integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. (optional, default `0`)
|
|
||||||
* `images[].input.text.height` **[number][7]** integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. (optional, default `0`)
|
|
||||||
* `images[].input.text.align` **[string][6]** text alignment (`'left'`, `'centre'`, `'center'`, `'right'`). (optional, default `'left'`)
|
|
||||||
* `images[].input.text.justify` **[boolean][9]** set this to true to apply justification to the text. (optional, default `false`)
|
|
||||||
* `images[].input.text.dpi` **[number][7]** the resolution (size) at which to render the text. Does not take effect if `height` is specified. (optional, default `72`)
|
|
||||||
* `images[].input.text.rgba` **[boolean][9]** set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`. (optional, default `false`)
|
|
||||||
* `images[].input.text.spacing` **[number][7]** text line height in points. Will use the font line height if none is specified. (optional, default `0`)
|
|
||||||
* `images[].blend` **[String][6]** how to blend this image with the image below. (optional, default `'over'`)
|
|
||||||
* `images[].gravity` **[String][6]** gravity at which to place the overlay. (optional, default `'centre'`)
|
|
||||||
* `images[].top` **[Number][7]?** the pixel offset from the top edge.
|
|
||||||
* `images[].left` **[Number][7]?** the pixel offset from the left edge.
|
|
||||||
* `images[].tile` **[Boolean][9]** set to true to repeat the overlay image across the entire image with the given `gravity`. (optional, default `false`)
|
|
||||||
* `images[].premultiplied` **[Boolean][9]** set to true to avoid premultipling the image below. Equivalent to the `--premultiplied` vips option. (optional, default `false`)
|
|
||||||
* `images[].density` **[Number][7]** number representing the DPI for vector overlay image. (optional, default `72`)
|
|
||||||
* `images[].raw` **[Object][4]?** describes overlay when using raw pixel data.
|
|
||||||
|
|
||||||
* `images[].raw.width` **[Number][7]?** 
|
|
||||||
* `images[].raw.height` **[Number][7]?** 
|
|
||||||
* `images[].raw.channels` **[Number][7]?** 
|
|
||||||
* `images[].animated` **[boolean][9]** Set to `true` to read all frames/pages of an animated image. (optional, default `false`)
|
|
||||||
* `images[].failOn` **[string][6]** @see [constructor parameters][10] (optional, default `'warning'`)
|
|
||||||
* `images[].limitInputPixels` **([number][7] | [boolean][9])** @see [constructor parameters][10] (optional, default `268402689`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
await sharp(background)
|
|
||||||
.composite([
|
|
||||||
{ input: layer1, gravity: 'northwest' },
|
|
||||||
{ input: layer2, gravity: 'southeast' },
|
|
||||||
])
|
|
||||||
.toFile('combined.png');
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const output = await sharp('input.gif', { animated: true })
|
|
||||||
.composite([
|
|
||||||
{ input: 'overlay.png', tile: true, blend: 'saturate' }
|
|
||||||
])
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
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!
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][11]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
**Meta**
|
|
||||||
|
|
||||||
* **since**: 0.22.0
|
|
||||||
|
|
||||||
[1]: https://www.libvips.org/API/current/libvips-conversion.html#VipsBlendMode
|
|
||||||
|
|
||||||
[2]: https://www.cairographics.org/operators/
|
|
||||||
|
|
||||||
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
|
|
||||||
|
|
||||||
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
|
|
||||||
|
|
||||||
[5]: https://nodejs.org/api/buffer.html
|
|
||||||
|
|
||||||
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
|
|
||||||
|
|
||||||
[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
|
|
||||||
|
|
||||||
[8]: https://www.npmjs.org/package/color
|
|
||||||
|
|
||||||
[9]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
|
|
||||||
|
|
||||||
[10]: /api-constructor#parameters
|
|
||||||
|
|
||||||
[11]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
|
|
||||||
@@ -1,269 +0,0 @@
|
|||||||
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
|
|
||||||
|
|
||||||
## Sharp
|
|
||||||
|
|
||||||
Constructor factory to create an instance of `sharp`, to which further methods are chained.
|
|
||||||
|
|
||||||
JPEG, PNG, WebP, GIF, AVIF or TIFF format image data can be streamed out from this object.
|
|
||||||
When using Stream based output, derived attributes are available from the `info` event.
|
|
||||||
|
|
||||||
Non-critical problems encountered during processing are emitted as `warning` events.
|
|
||||||
|
|
||||||
Implements the [stream.Duplex][1] class.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `input` **([Buffer][2] | [Uint8Array][3] | [Uint8ClampedArray][4] | [Int8Array][5] | [Uint16Array][6] | [Int16Array][7] | [Uint32Array][8] | [Int32Array][9] | [Float32Array][10] | [Float64Array][11] | [string][12])?** if present, can be
|
|
||||||
a Buffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or
|
|
||||||
a TypedArray containing raw pixel image data, or
|
|
||||||
a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file.
|
|
||||||
JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present.
|
|
||||||
* `options` **[Object][13]?** if present, is an Object with optional attributes.
|
|
||||||
|
|
||||||
* `options.failOn` **[string][12]** level of sensitivity to invalid images, one of (in order of sensitivity): 'none' (least), 'truncated', 'error' or 'warning' (most), highers level imply lower levels. (optional, default `'warning'`)
|
|
||||||
* `options.limitInputPixels` **([number][14] | [boolean][15])** Do not process input images where the number of pixels
|
|
||||||
(width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted.
|
|
||||||
An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). (optional, default `268402689`)
|
|
||||||
* `options.unlimited` **[boolean][15]** Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). (optional, default `false`)
|
|
||||||
* `options.sequentialRead` **[boolean][15]** Set this to `true` to use sequential rather than random access where possible.
|
|
||||||
This can reduce memory usage and might improve performance on some systems. (optional, default `false`)
|
|
||||||
* `options.density` **[number][14]** number representing the DPI for vector images in the range 1 to 100000. (optional, default `72`)
|
|
||||||
* `options.pages` **[number][14]** number of pages to extract for multi-page input (GIF, WebP, AVIF, TIFF, PDF), use -1 for all pages. (optional, default `1`)
|
|
||||||
* `options.page` **[number][14]** page number to start extracting from for multi-page input (GIF, WebP, AVIF, TIFF, PDF), zero based. (optional, default `0`)
|
|
||||||
* `options.subifd` **[number][14]** subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. (optional, default `-1`)
|
|
||||||
* `options.level` **[number][14]** level to extract from a multi-level input (OpenSlide), zero based. (optional, default `0`)
|
|
||||||
* `options.animated` **[boolean][15]** Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). (optional, default `false`)
|
|
||||||
* `options.raw` **[Object][13]?** describes raw pixel input image data. See `raw()` for pixel ordering.
|
|
||||||
|
|
||||||
* `options.raw.width` **[number][14]?** integral number of pixels wide.
|
|
||||||
* `options.raw.height` **[number][14]?** integral number of pixels high.
|
|
||||||
* `options.raw.channels` **[number][14]?** integral number of channels, between 1 and 4.
|
|
||||||
* `options.raw.premultiplied` **[boolean][15]?** specifies that the raw input has already been premultiplied, set to `true`
|
|
||||||
to avoid sharp premultiplying the image. (optional, default `false`)
|
|
||||||
* `options.create` **[Object][13]?** describes a new image to be created.
|
|
||||||
|
|
||||||
* `options.create.width` **[number][14]?** integral number of pixels wide.
|
|
||||||
* `options.create.height` **[number][14]?** integral number of pixels high.
|
|
||||||
* `options.create.channels` **[number][14]?** integral number of channels, either 3 (RGB) or 4 (RGBA).
|
|
||||||
* `options.create.background` **([string][12] | [Object][13])?** parsed by the [color][16] module to extract values for red, green, blue and alpha.
|
|
||||||
* `options.create.noise` **[Object][13]?** describes a noise to be created.
|
|
||||||
|
|
||||||
* `options.create.noise.type` **[string][12]?** type of generated noise, currently only `gaussian` is supported.
|
|
||||||
* `options.create.noise.mean` **[number][14]?** mean of pixels in generated noise.
|
|
||||||
* `options.create.noise.sigma` **[number][14]?** standard deviation of pixels in generated noise.
|
|
||||||
* `options.text` **[Object][13]?** describes a new text image to be created.
|
|
||||||
|
|
||||||
* `options.text.text` **[string][12]?** text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.
|
|
||||||
* `options.text.font` **[string][12]?** font name to render with.
|
|
||||||
* `options.text.fontfile` **[string][12]?** absolute filesystem path to a font file that can be used by `font`.
|
|
||||||
* `options.text.width` **[number][14]** integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. (optional, default `0`)
|
|
||||||
* `options.text.height` **[number][14]** integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. (optional, default `0`)
|
|
||||||
* `options.text.align` **[string][12]** text alignment (`'left'`, `'centre'`, `'center'`, `'right'`). (optional, default `'left'`)
|
|
||||||
* `options.text.justify` **[boolean][15]** set this to true to apply justification to the text. (optional, default `false`)
|
|
||||||
* `options.text.dpi` **[number][14]** the resolution (size) at which to render the text. Does not take effect if `height` is specified. (optional, default `72`)
|
|
||||||
* `options.text.rgba` **[boolean][15]** set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`. (optional, default `false`)
|
|
||||||
* `options.text.spacing` **[number][14]** text line height in points. Will use the font line height if none is specified. (optional, default `0`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
sharp('input.jpg')
|
|
||||||
.resize(300, 200)
|
|
||||||
.toFile('output.jpg', function(err) {
|
|
||||||
// output.jpg is a 300 pixels wide and 200 pixels high image
|
|
||||||
// containing a scaled and cropped version of input.jpg
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Read image data from readableStream,
|
|
||||||
// resize to 300 pixels wide,
|
|
||||||
// emit an 'info' event with calculated dimensions
|
|
||||||
// and finally write image data to writableStream
|
|
||||||
var transformer = sharp()
|
|
||||||
.resize(300)
|
|
||||||
.on('info', function(info) {
|
|
||||||
console.log('Image height is ' + info.height);
|
|
||||||
});
|
|
||||||
readableStream.pipe(transformer).pipe(writableStream);
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Create a blank 300x200 PNG image of semi-transluent red pixels
|
|
||||||
sharp({
|
|
||||||
create: {
|
|
||||||
width: 300,
|
|
||||||
height: 200,
|
|
||||||
channels: 4,
|
|
||||||
background: { r: 255, g: 0, b: 0, alpha: 0.5 }
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.png()
|
|
||||||
.toBuffer()
|
|
||||||
.then( ... );
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Convert an animated GIF to an animated WebP
|
|
||||||
await sharp('in.gif', { animated: true }).toFile('out.webp');
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Read a raw array of pixels and save it to a png
|
|
||||||
const input = Uint8Array.from([255, 255, 255, 0, 0, 0]); // or Uint8ClampedArray
|
|
||||||
const image = sharp(input, {
|
|
||||||
// because the input does not contain its dimensions or how many channels it has
|
|
||||||
// we need to specify it in the constructor options
|
|
||||||
raw: {
|
|
||||||
width: 2,
|
|
||||||
height: 1,
|
|
||||||
channels: 3
|
|
||||||
}
|
|
||||||
});
|
|
||||||
await image.toFile('my-two-pixels.png');
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Generate RGB Gaussian noise
|
|
||||||
await sharp({
|
|
||||||
create: {
|
|
||||||
width: 300,
|
|
||||||
height: 200,
|
|
||||||
channels: 3,
|
|
||||||
noise: {
|
|
||||||
type: 'gaussian',
|
|
||||||
mean: 128,
|
|
||||||
sigma: 30
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}).toFile('noise.png');
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Generate an image from text
|
|
||||||
await sharp({
|
|
||||||
text: {
|
|
||||||
text: 'Hello, world!',
|
|
||||||
width: 400, // max width
|
|
||||||
height: 300 // max height
|
|
||||||
}
|
|
||||||
}).toFile('text_bw.png');
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Generate an rgba image from text using pango markup and font
|
|
||||||
await sharp({
|
|
||||||
text: {
|
|
||||||
text: '<span foreground="red">Red!</span><span background="cyan">blue</span>',
|
|
||||||
font: 'sans',
|
|
||||||
rgba: true,
|
|
||||||
dpi: 300
|
|
||||||
}
|
|
||||||
}).toFile('text_rgba.png');
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][17]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **[Sharp][18]** 
|
|
||||||
|
|
||||||
## clone
|
|
||||||
|
|
||||||
Take a "snapshot" of the Sharp instance, returning a new instance.
|
|
||||||
Cloned instances inherit the input of their parent instance.
|
|
||||||
This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream.
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const pipeline = sharp().rotate();
|
|
||||||
pipeline.clone().resize(800, 600).pipe(firstWritableStream);
|
|
||||||
pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 }).pipe(secondWritableStream);
|
|
||||||
readableStream.pipe(pipeline);
|
|
||||||
// firstWritableStream receives auto-rotated, resized readableStream
|
|
||||||
// secondWritableStream receives auto-rotated, extracted region of readableStream
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Create a pipeline that will download an image, resize it and format it to different files
|
|
||||||
// Using Promises to know when the pipeline is complete
|
|
||||||
const fs = require("fs");
|
|
||||||
const got = require("got");
|
|
||||||
const sharpStream = sharp({ failOn: 'none' });
|
|
||||||
|
|
||||||
const promises = [];
|
|
||||||
|
|
||||||
promises.push(
|
|
||||||
sharpStream
|
|
||||||
.clone()
|
|
||||||
.jpeg({ quality: 100 })
|
|
||||||
.toFile("originalFile.jpg")
|
|
||||||
);
|
|
||||||
|
|
||||||
promises.push(
|
|
||||||
sharpStream
|
|
||||||
.clone()
|
|
||||||
.resize({ width: 500 })
|
|
||||||
.jpeg({ quality: 80 })
|
|
||||||
.toFile("optimized-500.jpg")
|
|
||||||
);
|
|
||||||
|
|
||||||
promises.push(
|
|
||||||
sharpStream
|
|
||||||
.clone()
|
|
||||||
.resize({ width: 500 })
|
|
||||||
.webp({ quality: 80 })
|
|
||||||
.toFile("optimized-500.webp")
|
|
||||||
);
|
|
||||||
|
|
||||||
// https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md
|
|
||||||
got.stream("https://www.example.com/some-file.jpg").pipe(sharpStream);
|
|
||||||
|
|
||||||
Promise.all(promises)
|
|
||||||
.then(res => { console.log("Done!", res); })
|
|
||||||
.catch(err => {
|
|
||||||
console.error("Error processing files, let's clean it up", err);
|
|
||||||
try {
|
|
||||||
fs.unlinkSync("originalFile.jpg");
|
|
||||||
fs.unlinkSync("optimized-500.jpg");
|
|
||||||
fs.unlinkSync("optimized-500.webp");
|
|
||||||
} catch (e) {}
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **[Sharp][18]** 
|
|
||||||
|
|
||||||
[1]: http://nodejs.org/api/stream.html#stream_class_stream_duplex
|
|
||||||
|
|
||||||
[2]: https://nodejs.org/api/buffer.html
|
|
||||||
|
|
||||||
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array
|
|
||||||
|
|
||||||
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray
|
|
||||||
|
|
||||||
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Int8Array
|
|
||||||
|
|
||||||
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array
|
|
||||||
|
|
||||||
[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Int16Array
|
|
||||||
|
|
||||||
[8]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array
|
|
||||||
|
|
||||||
[9]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Int32Array
|
|
||||||
|
|
||||||
[10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Float32Array
|
|
||||||
|
|
||||||
[11]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Float64Array
|
|
||||||
|
|
||||||
[12]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
|
|
||||||
|
|
||||||
[13]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
|
|
||||||
|
|
||||||
[14]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
|
|
||||||
|
|
||||||
[15]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
|
|
||||||
|
|
||||||
[16]: https://www.npmjs.org/package/color
|
|
||||||
|
|
||||||
[17]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
|
|
||||||
|
|
||||||
[18]: #sharp
|
|
||||||
@@ -1,149 +0,0 @@
|
|||||||
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
|
|
||||||
|
|
||||||
## metadata
|
|
||||||
|
|
||||||
Fast access to (uncached) image metadata without decoding any compressed pixel data.
|
|
||||||
|
|
||||||
This is taken from the header of the input image.
|
|
||||||
It does not include operations, such as resize, to be applied to the output image.
|
|
||||||
|
|
||||||
Dimensions in the response will respect the `page` and `pages` properties of the
|
|
||||||
[constructor parameters][1].
|
|
||||||
|
|
||||||
A `Promise` is returned when `callback` is not provided.
|
|
||||||
|
|
||||||
* `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` [...][2]
|
|
||||||
* `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK
|
|
||||||
* `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...][3]
|
|
||||||
* `density`: Number of pixels per inch (DPI), if present
|
|
||||||
* `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK
|
|
||||||
* `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan
|
|
||||||
* `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP
|
|
||||||
* `pageHeight`: Number of pixels high each page in a multi-page image will be.
|
|
||||||
* `loop`: Number of times to loop an animated image, zero refers to a continuous loop.
|
|
||||||
* `delay`: Delay in ms between each page in an animated image, provided as an array of integers.
|
|
||||||
* `pagePrimary`: Number of the primary page in a HEIF image
|
|
||||||
* `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide
|
|
||||||
* `subifds`: Number of Sub Image File Directories in an OME-TIFF image
|
|
||||||
* `background`: Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value
|
|
||||||
* `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][4] profile data, if present
|
|
||||||
* `iptc`: Buffer containing raw IPTC data, if present
|
|
||||||
* `xmp`: Buffer containing raw XMP data, if present
|
|
||||||
* `tifftagPhotoshop`: Buffer containing raw TIFFTAG\_PHOTOSHOP data, if present
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `callback` **[Function][5]?** called with the arguments `(err, metadata)`
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const metadata = await sharp(input).metadata();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
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
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Based on EXIF rotation metadata, get the right-side-up width and height:
|
|
||||||
|
|
||||||
const size = getNormalSize(await sharp(input).metadata());
|
|
||||||
|
|
||||||
function getNormalSize({ width, height, orientation }) {
|
|
||||||
return (orientation || 0) >= 5
|
|
||||||
? { width: height, height: width }
|
|
||||||
: { width, height };
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **([Promise][6]<[Object][7]> | Sharp)** 
|
|
||||||
|
|
||||||
## stats
|
|
||||||
|
|
||||||
Access to pixel-derived image statistics for every channel in the image.
|
|
||||||
A `Promise` is returned when `callback` is not provided.
|
|
||||||
|
|
||||||
* `channels`: Array of channel statistics for each channel in the image. Each channel statistic contains
|
|
||||||
* `min` (minimum value in the channel)
|
|
||||||
* `max` (maximum value in the channel)
|
|
||||||
* `sum` (sum of all values in a channel)
|
|
||||||
* `squaresSum` (sum of squared values in a channel)
|
|
||||||
* `mean` (mean of the values in a channel)
|
|
||||||
* `stdev` (standard deviation for the values in a channel)
|
|
||||||
* `minX` (x-coordinate of one of the pixel where the minimum lies)
|
|
||||||
* `minY` (y-coordinate of one of the pixel where the minimum lies)
|
|
||||||
* `maxX` (x-coordinate of one of the pixel where the maximum lies)
|
|
||||||
* `maxY` (y-coordinate of one of the pixel where the maximum lies)
|
|
||||||
* `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque.
|
|
||||||
* `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any.
|
|
||||||
* `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).
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `callback` **[Function][5]?** called with the arguments `(err, stats)`
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const image = sharp(inputJpg);
|
|
||||||
image
|
|
||||||
.stats()
|
|
||||||
.then(function(stats) {
|
|
||||||
// stats contains the channel-wise statistics array and the isOpaque value
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const { entropy, sharpness, dominant } = await sharp(input).stats();
|
|
||||||
const { r, g, b } = dominant;
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
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();
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **[Promise][6]<[Object][7]>** 
|
|
||||||
|
|
||||||
[1]: /api-constructor#parameters
|
|
||||||
|
|
||||||
[2]: https://www.libvips.org/API/current/VipsImage.html#VipsInterpretation
|
|
||||||
|
|
||||||
[3]: https://www.libvips.org/API/current/VipsImage.html#VipsBandFormat
|
|
||||||
|
|
||||||
[4]: https://www.npmjs.com/package/icc
|
|
||||||
|
|
||||||
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function
|
|
||||||
|
|
||||||
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise
|
|
||||||
|
|
||||||
[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
|
|
||||||
@@ -1,613 +0,0 @@
|
|||||||
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
|
|
||||||
|
|
||||||
## rotate
|
|
||||||
|
|
||||||
Rotate the output image by either an explicit angle
|
|
||||||
or auto-orient based on the EXIF `Orientation` tag.
|
|
||||||
|
|
||||||
If an angle is provided, it is converted to a valid positive degree rotation.
|
|
||||||
For example, `-450` will produce a 270deg rotation.
|
|
||||||
|
|
||||||
When rotating by an angle other than a multiple of 90,
|
|
||||||
the background colour can be provided with the `background` option.
|
|
||||||
|
|
||||||
If no angle is provided, it is determined from the EXIF data.
|
|
||||||
Mirroring is supported and may infer the use of a flip operation.
|
|
||||||
|
|
||||||
The use of `rotate` implies the removal of the EXIF `Orientation` tag, if any.
|
|
||||||
|
|
||||||
Only one rotation can occur per pipeline.
|
|
||||||
Previous calls to `rotate` in the same pipeline will be ignored.
|
|
||||||
|
|
||||||
Method order is important when rotating, resizing and/or extracting regions,
|
|
||||||
for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `angle` **[number][1]** angle of rotation. (optional, default `auto`)
|
|
||||||
* `options` **[Object][2]?** if present, is an Object with optional attributes.
|
|
||||||
|
|
||||||
* `options.background` **([string][3] | [Object][2])** parsed by the [color][4] module to extract values for red, green, blue and alpha. (optional, default `"#000000"`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const pipeline = sharp()
|
|
||||||
.rotate()
|
|
||||||
.resize(null, 200)
|
|
||||||
.toBuffer(function (err, outputBuffer, info) {
|
|
||||||
// outputBuffer contains 200px high JPEG image data,
|
|
||||||
// auto-rotated using EXIF Orientation tag
|
|
||||||
// info.width and info.height contain the dimensions of the resized image
|
|
||||||
});
|
|
||||||
readableStream.pipe(pipeline);
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const rotateThenResize = await sharp(input)
|
|
||||||
.rotate(90)
|
|
||||||
.resize({ width: 16, height: 8, fit: 'fill' })
|
|
||||||
.toBuffer();
|
|
||||||
const resizeThenRotate = await sharp(input)
|
|
||||||
.resize({ width: 16, height: 8, fit: 'fill' })
|
|
||||||
.rotate(90)
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][5]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## flip
|
|
||||||
|
|
||||||
Flip the image about the vertical Y axis. This always occurs before rotation, if any.
|
|
||||||
The use of `flip` implies the removal of the EXIF `Orientation` tag, if any.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `flip` **[Boolean][6]** (optional, default `true`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const output = await sharp(input).flip().toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## flop
|
|
||||||
|
|
||||||
Flop the image about the horizontal X axis. This always occurs before rotation, if any.
|
|
||||||
The use of `flop` implies the removal of the EXIF `Orientation` tag, if any.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `flop` **[Boolean][6]** (optional, default `true`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const output = await sharp(input).flop().toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## affine
|
|
||||||
|
|
||||||
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 color with the `background` option.
|
|
||||||
A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolator` Object e.g. `sharp.interpolator.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.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `matrix` **([Array][7]<[Array][7]<[number][1]>> | [Array][7]<[number][1]>)** affine transformation matrix
|
|
||||||
* `options` **[Object][2]?** if present, is an Object with optional attributes.
|
|
||||||
|
|
||||||
* `options.background` **([String][3] | [Object][2])** parsed by the [color][4] module to extract values for red, green, blue and alpha. (optional, default `"#000000"`)
|
|
||||||
* `options.idx` **[Number][1]** input horizontal offset (optional, default `0`)
|
|
||||||
* `options.idy` **[Number][1]** input vertical offset (optional, default `0`)
|
|
||||||
* `options.odx` **[Number][1]** output horizontal offset (optional, default `0`)
|
|
||||||
* `options.ody` **[Number][1]** output vertical offset (optional, default `0`)
|
|
||||||
* `options.interpolator` **[String][3]** interpolator (optional, default `sharp.interpolators.bicubic`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const pipeline = sharp()
|
|
||||||
.affine([[1, 0.3], [0.1, 0.7]], {
|
|
||||||
background: 'white',
|
|
||||||
interpolate: sharp.interpolators.nohalo
|
|
||||||
})
|
|
||||||
.toBuffer((err, outputBuffer, info) => {
|
|
||||||
// outputBuffer contains the transformed image
|
|
||||||
// info.width and info.height contain the new dimensions
|
|
||||||
});
|
|
||||||
|
|
||||||
inputStream
|
|
||||||
.pipe(pipeline);
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][5]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
**Meta**
|
|
||||||
|
|
||||||
* **since**: 0.27.0
|
|
||||||
|
|
||||||
## sharpen
|
|
||||||
|
|
||||||
Sharpen the image.
|
|
||||||
When used without parameters, performs a fast, mild sharpen of the output image.
|
|
||||||
When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space.
|
|
||||||
Separate control over the level of sharpening in "flat" and "jagged" areas is available.
|
|
||||||
|
|
||||||
See [libvips sharpen][8] operation.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **([Object][2] | [number][1])?** if present, is an Object with attributes or (deprecated) a number for `options.sigma`.
|
|
||||||
|
|
||||||
* `options.sigma` **[number][1]?** the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
|
|
||||||
* `options.m1` **[number][1]** the level of sharpening to apply to "flat" areas. (optional, default `1.0`)
|
|
||||||
* `options.m2` **[number][1]** the level of sharpening to apply to "jagged" areas. (optional, default `2.0`)
|
|
||||||
* `options.x1` **[number][1]** threshold between "flat" and "jagged" (optional, default `2.0`)
|
|
||||||
* `options.y2` **[number][1]** maximum amount of brightening. (optional, default `10.0`)
|
|
||||||
* `options.y3` **[number][1]** maximum amount of darkening. (optional, default `20.0`)
|
|
||||||
* `flat` **[number][1]?** (deprecated) see `options.m1`.
|
|
||||||
* `jagged` **[number][1]?** (deprecated) see `options.m2`.
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const data = await sharp(input).sharpen().toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const data = await sharp(input).sharpen({ sigma: 2 }).toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const data = await sharp(input)
|
|
||||||
.sharpen({
|
|
||||||
sigma: 2,
|
|
||||||
m1: 0,
|
|
||||||
m2: 3,
|
|
||||||
x1: 3,
|
|
||||||
y2: 15,
|
|
||||||
y3: 15,
|
|
||||||
})
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][5]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## median
|
|
||||||
|
|
||||||
Apply median filter.
|
|
||||||
When used without parameters the default window is 3x3.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `size` **[number][1]** square mask size: size x size (optional, default `3`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const output = await sharp(input).median().toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const output = await sharp(input).median(5).toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][5]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## blur
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `sigma` **[number][1]?** a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const boxBlurred = await sharp(input)
|
|
||||||
.blur()
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const gaussianBlurred = await sharp(input)
|
|
||||||
.blur(5)
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][5]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## flatten
|
|
||||||
|
|
||||||
Merge alpha transparency channel, if any, with a background, then remove the alpha channel.
|
|
||||||
|
|
||||||
See also [removeAlpha][9].
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][2]?** 
|
|
||||||
|
|
||||||
* `options.background` **([string][3] | [Object][2])** background colour, parsed by the [color][4] module, defaults to black. (optional, default `{r:0,g:0,b:0}`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
await sharp(rgbaInput)
|
|
||||||
.flatten({ background: '#F0A703' })
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## gamma
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `gamma` **[number][1]** value between 1.0 and 3.0. (optional, default `2.2`)
|
|
||||||
* `gammaOut` **[number][1]?** value between 1.0 and 3.0. (optional, defaults to same as `gamma`)
|
|
||||||
|
|
||||||
<!---->
|
|
||||||
|
|
||||||
* Throws **[Error][5]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## negate
|
|
||||||
|
|
||||||
Produce the "negative" of the image.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][2]?** 
|
|
||||||
|
|
||||||
* `options.alpha` **[Boolean][6]** Whether or not to negate any alpha channel (optional, default `true`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const output = await sharp(input)
|
|
||||||
.negate()
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const output = await sharp(input)
|
|
||||||
.negate({ alpha: false })
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## normalise
|
|
||||||
|
|
||||||
Enhance output image contrast by stretching its luminance to cover the full dynamic range.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `normalise` **[Boolean][6]** (optional, default `true`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const output = await sharp(input).normalise().toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## normalize
|
|
||||||
|
|
||||||
Alternative spelling of normalise.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `normalize` **[Boolean][6]** (optional, default `true`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const output = await sharp(input).normalize().toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## clahe
|
|
||||||
|
|
||||||
Perform contrast limiting adaptive histogram equalization
|
|
||||||
[CLAHE][10].
|
|
||||||
|
|
||||||
This will, in general, enhance the clarity of the image by bringing out darker details.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][2]** 
|
|
||||||
|
|
||||||
* `options.width` **[number][1]** integer width of the region in pixels.
|
|
||||||
* `options.height` **[number][1]** integer height of the region in pixels.
|
|
||||||
* `options.maxSlope` **[number][1]** maximum value for the slope of the
|
|
||||||
cumulative histogram. A value of 0 disables contrast limiting. Valid values
|
|
||||||
are integers in the range 0-100 (inclusive) (optional, default `3`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const output = await sharp(input)
|
|
||||||
.clahe({
|
|
||||||
width: 3,
|
|
||||||
height: 3,
|
|
||||||
})
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][5]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
**Meta**
|
|
||||||
|
|
||||||
* **since**: 0.28.3
|
|
||||||
|
|
||||||
## convolve
|
|
||||||
|
|
||||||
Convolve the image with the specified kernel.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `kernel` **[Object][2]** 
|
|
||||||
|
|
||||||
* `kernel.width` **[number][1]** width of the kernel in pixels.
|
|
||||||
* `kernel.height` **[number][1]** height of the kernel in pixels.
|
|
||||||
* `kernel.kernel` **[Array][7]<[number][1]>** Array of length `width*height` containing the kernel values.
|
|
||||||
* `kernel.scale` **[number][1]** the scale of the kernel in pixels. (optional, default `sum`)
|
|
||||||
* `kernel.offset` **[number][1]** the offset of the kernel in pixels. (optional, default `0`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
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
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][5]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## threshold
|
|
||||||
|
|
||||||
Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `threshold` **[number][1]** a value in the range 0-255 representing the level at which the threshold will be applied. (optional, default `128`)
|
|
||||||
* `options` **[Object][2]?** 
|
|
||||||
|
|
||||||
* `options.greyscale` **[Boolean][6]** convert to single channel greyscale. (optional, default `true`)
|
|
||||||
* `options.grayscale` **[Boolean][6]** alternative spelling for greyscale. (optional, default `true`)
|
|
||||||
|
|
||||||
<!---->
|
|
||||||
|
|
||||||
* Throws **[Error][5]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## boolean
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `operand` **([Buffer][11] | [string][3])** Buffer containing image data or string containing the path to an image file.
|
|
||||||
* `operator` **[string][3]** one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.
|
|
||||||
* `options` **[Object][2]?** 
|
|
||||||
|
|
||||||
* `options.raw` **[Object][2]?** describes operand when using raw pixel data.
|
|
||||||
|
|
||||||
* `options.raw.width` **[number][1]?** 
|
|
||||||
* `options.raw.height` **[number][1]?** 
|
|
||||||
* `options.raw.channels` **[number][1]?** 
|
|
||||||
|
|
||||||
<!---->
|
|
||||||
|
|
||||||
* Throws **[Error][5]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## linear
|
|
||||||
|
|
||||||
Apply the linear formula `a` \* input + `b` to the image to adjust image levels.
|
|
||||||
|
|
||||||
When a single number is provided, it will be used for all image channels.
|
|
||||||
When an array of numbers is provided, the array length must match the number of channels.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `a` **([number][1] | [Array][7]<[number][1]>)** multiplier (optional, default `[]`)
|
|
||||||
* `b` **([number][1] | [Array][7]<[number][1]>)** offset (optional, default `[]`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
await sharp(input)
|
|
||||||
.linear(0.5, 2)
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
await sharp(rgbInput)
|
|
||||||
.linear(
|
|
||||||
[0.25, 0.5, 0.75],
|
|
||||||
[150, 100, 50]
|
|
||||||
)
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][5]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## recomb
|
|
||||||
|
|
||||||
Recomb the image with the specified matrix.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `inputMatrix` **[Array][7]<[Array][7]<[number][1]>>** 3x3 Recombination matrix
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
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 recomb
|
|
||||||
// With this example input, a sepia filter has been applied
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][5]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
**Meta**
|
|
||||||
|
|
||||||
* **since**: 0.21.1
|
|
||||||
|
|
||||||
## modulate
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][2]?** 
|
|
||||||
|
|
||||||
* `options.brightness` **[number][1]?** Brightness multiplier
|
|
||||||
* `options.saturation` **[number][1]?** Saturation multiplier
|
|
||||||
* `options.hue` **[number][1]?** Degrees for hue rotation
|
|
||||||
* `options.lightness` **[number][1]?** Lightness addend
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// increase brightness by a factor of 2
|
|
||||||
const output = await sharp(input)
|
|
||||||
.modulate({
|
|
||||||
brightness: 2
|
|
||||||
})
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// hue-rotate by 180 degrees
|
|
||||||
const output = await sharp(input)
|
|
||||||
.modulate({
|
|
||||||
hue: 180
|
|
||||||
})
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// increase lightness by +50
|
|
||||||
const output = await sharp(input)
|
|
||||||
.modulate({
|
|
||||||
lightness: 50
|
|
||||||
})
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// decreate 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();
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
**Meta**
|
|
||||||
|
|
||||||
* **since**: 0.22.1
|
|
||||||
|
|
||||||
[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
|
|
||||||
|
|
||||||
[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
|
|
||||||
|
|
||||||
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
|
|
||||||
|
|
||||||
[4]: https://www.npmjs.org/package/color
|
|
||||||
|
|
||||||
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
|
|
||||||
|
|
||||||
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
|
|
||||||
|
|
||||||
[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
|
|
||||||
|
|
||||||
[8]: https://www.libvips.org/API/current/libvips-convolution.html#vips-sharpen
|
|
||||||
|
|
||||||
[9]: /api-channel#removealpha
|
|
||||||
|
|
||||||
[10]: https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE
|
|
||||||
|
|
||||||
[11]: https://nodejs.org/api/buffer.html
|
|
||||||
@@ -1,682 +0,0 @@
|
|||||||
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
|
|
||||||
|
|
||||||
## toFile
|
|
||||||
|
|
||||||
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][1] for control over this.
|
|
||||||
|
|
||||||
The caller is responsible for ensuring directory structures and permissions exist.
|
|
||||||
|
|
||||||
A `Promise` is returned when `callback` is not provided.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `fileOut` **[string][2]** the path to write the image data to.
|
|
||||||
* `callback` **[Function][3]?** called on completion with two arguments `(err, info)`.
|
|
||||||
`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`.
|
|
||||||
May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
sharp(input)
|
|
||||||
.toFile('output.png', (err, info) => { ... });
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
sharp(input)
|
|
||||||
.toFile('output.png')
|
|
||||||
.then(info => { ... })
|
|
||||||
.catch(err => { ... });
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][4]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **[Promise][5]<[Object][6]>** when no callback is provided
|
|
||||||
|
|
||||||
## toBuffer
|
|
||||||
|
|
||||||
Write output to a Buffer.
|
|
||||||
JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.
|
|
||||||
|
|
||||||
Use [toFormat][7] or one of the format-specific functions such as [jpeg][8], [png][9] etc. to set the output format.
|
|
||||||
|
|
||||||
If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output.
|
|
||||||
|
|
||||||
By default all metadata will be removed, which includes EXIF-based orientation.
|
|
||||||
See [withMetadata][1] for control over this.
|
|
||||||
|
|
||||||
`callback`, if present, gets three arguments `(err, data, info)` where:
|
|
||||||
|
|
||||||
* `err` is an error, if any.
|
|
||||||
* `data` is the output image data.
|
|
||||||
* `info` contains the output image `format`, `size` (bytes), `width`, `height`,
|
|
||||||
`channels` and `premultiplied` (indicating if premultiplication was used).
|
|
||||||
When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
|
|
||||||
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.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][6]?** 
|
|
||||||
|
|
||||||
* `options.resolveWithObject` **[boolean][10]?** Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`.
|
|
||||||
* `callback` **[Function][3]?** 
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
sharp(input)
|
|
||||||
.toBuffer((err, data, info) => { ... });
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
sharp(input)
|
|
||||||
.toBuffer()
|
|
||||||
.then(data => { ... })
|
|
||||||
.catch(err => { ... });
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
sharp(input)
|
|
||||||
.png()
|
|
||||||
.toBuffer({ resolveWithObject: true })
|
|
||||||
.then(({ data, info }) => { ... })
|
|
||||||
.catch(err => { ... });
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
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');
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **[Promise][5]<[Buffer][11]>** when no callback is provided
|
|
||||||
|
|
||||||
## withMetadata
|
|
||||||
|
|
||||||
Include all 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 unless a custom
|
|
||||||
output profile is provided.
|
|
||||||
|
|
||||||
The default behaviour, when `withMetadata` is not used, is to convert to the device-independent
|
|
||||||
sRGB colour space and strip all metadata, including the removal of any ICC profile.
|
|
||||||
|
|
||||||
EXIF metadata is unsupported for TIFF output.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][6]?** 
|
|
||||||
|
|
||||||
* `options.orientation` **[number][12]?** value between 1 and 8, used to update the EXIF `Orientation` tag.
|
|
||||||
* `options.icc` **[string][2]?** filesystem path to output ICC profile, defaults to sRGB.
|
|
||||||
* `options.exif` **[Object][6]<[Object][6]>** Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. (optional, default `{}`)
|
|
||||||
* `options.density` **[number][12]?** Number of pixels per inch (DPI).
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
sharp('input.jpg')
|
|
||||||
.withMetadata()
|
|
||||||
.toFile('output-with-metadata.jpg')
|
|
||||||
.then(info => { ... });
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Set "IFD0-Copyright" in output EXIF metadata
|
|
||||||
const data = await sharp(input)
|
|
||||||
.withMetadata({
|
|
||||||
exif: {
|
|
||||||
IFD0: {
|
|
||||||
Copyright: 'Wernham Hogg'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Set output metadata to 96 DPI
|
|
||||||
const data = await sharp(input)
|
|
||||||
.withMetadata({ density: 96 })
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][4]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## toFormat
|
|
||||||
|
|
||||||
Force output to a given format.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `format` **([string][2] | [Object][6])** as a string or an Object with an 'id' attribute
|
|
||||||
* `options` **[Object][6]** output options
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Convert any input to PNG output
|
|
||||||
const data = await sharp(input)
|
|
||||||
.toFormat('png')
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][4]** unsupported format or options
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## jpeg
|
|
||||||
|
|
||||||
Use these JPEG options for output image.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][6]?** output options
|
|
||||||
|
|
||||||
* `options.quality` **[number][12]** quality, integer 1-100 (optional, default `80`)
|
|
||||||
* `options.progressive` **[boolean][10]** use progressive (interlace) scan (optional, default `false`)
|
|
||||||
* `options.chromaSubsampling` **[string][2]** set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling (optional, default `'4:2:0'`)
|
|
||||||
* `options.optimiseCoding` **[boolean][10]** optimise Huffman coding tables (optional, default `true`)
|
|
||||||
* `options.optimizeCoding` **[boolean][10]** alternative spelling of optimiseCoding (optional, default `true`)
|
|
||||||
* `options.mozjpeg` **[boolean][10]** use mozjpeg defaults, equivalent to `{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }` (optional, default `false`)
|
|
||||||
* `options.trellisQuantisation` **[boolean][10]** apply trellis quantisation (optional, default `false`)
|
|
||||||
* `options.overshootDeringing` **[boolean][10]** apply overshoot deringing (optional, default `false`)
|
|
||||||
* `options.optimiseScans` **[boolean][10]** optimise progressive scans, forces progressive (optional, default `false`)
|
|
||||||
* `options.optimizeScans` **[boolean][10]** alternative spelling of optimiseScans (optional, default `false`)
|
|
||||||
* `options.quantisationTable` **[number][12]** quantization table to use, integer 0-8 (optional, default `0`)
|
|
||||||
* `options.quantizationTable` **[number][12]** alternative spelling of quantisationTable (optional, default `0`)
|
|
||||||
* `options.force` **[boolean][10]** force JPEG output, otherwise attempt to use input format (optional, default `true`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Convert any input to very high quality JPEG output
|
|
||||||
const data = await sharp(input)
|
|
||||||
.jpeg({
|
|
||||||
quality: 100,
|
|
||||||
chromaSubsampling: '4:4:4'
|
|
||||||
})
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Use mozjpeg to reduce output JPEG file size (slower)
|
|
||||||
const data = await sharp(input)
|
|
||||||
.jpeg({ mozjpeg: true })
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][4]** Invalid options
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## png
|
|
||||||
|
|
||||||
Use these PNG options for output image.
|
|
||||||
|
|
||||||
By default, PNG output is full colour at 8 or 16 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.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][6]?** 
|
|
||||||
|
|
||||||
* `options.progressive` **[boolean][10]** use progressive (interlace) scan (optional, default `false`)
|
|
||||||
* `options.compressionLevel` **[number][12]** zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest) (optional, default `6`)
|
|
||||||
* `options.adaptiveFiltering` **[boolean][10]** use adaptive row filtering (optional, default `false`)
|
|
||||||
* `options.palette` **[boolean][10]** quantise to a palette-based image with alpha transparency support (optional, default `false`)
|
|
||||||
* `options.quality` **[number][12]** use the lowest number of colours needed to achieve given quality, sets `palette` to `true` (optional, default `100`)
|
|
||||||
* `options.effort` **[number][12]** CPU effort, between 1 (fastest) and 10 (slowest), sets `palette` to `true` (optional, default `7`)
|
|
||||||
* `options.colours` **[number][12]** maximum number of palette entries, sets `palette` to `true` (optional, default `256`)
|
|
||||||
* `options.colors` **[number][12]** alternative spelling of `options.colours`, sets `palette` to `true` (optional, default `256`)
|
|
||||||
* `options.dither` **[number][12]** level of Floyd-Steinberg error diffusion, sets `palette` to `true` (optional, default `1.0`)
|
|
||||||
* `options.force` **[boolean][10]** force PNG output, otherwise attempt to use input format (optional, default `true`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Convert any input to full colour PNG output
|
|
||||||
const data = await sharp(input)
|
|
||||||
.png()
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Convert any input to indexed PNG output (slower)
|
|
||||||
const data = await sharp(input)
|
|
||||||
.png({ palette: true })
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][4]** Invalid options
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## webp
|
|
||||||
|
|
||||||
Use these WebP options for output image.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][6]?** output options
|
|
||||||
|
|
||||||
* `options.quality` **[number][12]** quality, integer 1-100 (optional, default `80`)
|
|
||||||
* `options.alphaQuality` **[number][12]** quality of alpha layer, integer 0-100 (optional, default `100`)
|
|
||||||
* `options.lossless` **[boolean][10]** use lossless compression mode (optional, default `false`)
|
|
||||||
* `options.nearLossless` **[boolean][10]** use near\_lossless compression mode (optional, default `false`)
|
|
||||||
* `options.smartSubsample` **[boolean][10]** use high quality chroma subsampling (optional, default `false`)
|
|
||||||
* `options.effort` **[number][12]** CPU effort, between 0 (fastest) and 6 (slowest) (optional, default `4`)
|
|
||||||
* `options.loop` **[number][12]** number of animation iterations, use 0 for infinite animation (optional, default `0`)
|
|
||||||
* `options.delay` **([number][12] | [Array][13]<[number][12]>)?** delay(s) between animation frames (in milliseconds)
|
|
||||||
* `options.minSize` **[boolean][10]** prevent use of animation key frames to minimise file size (slow) (optional, default `false`)
|
|
||||||
* `options.mixed` **[boolean][10]** allow mixture of lossy and lossless animation frames (slow) (optional, default `false`)
|
|
||||||
* `options.force` **[boolean][10]** force WebP output, otherwise attempt to use input format (optional, default `true`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Convert any input to lossless WebP output
|
|
||||||
const data = await sharp(input)
|
|
||||||
.webp({ lossless: true })
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Optimise the file size of an animated WebP
|
|
||||||
const outputWebp = await sharp(inputWebp, { animated: true })
|
|
||||||
.webp({ effort: 6 })
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][4]** Invalid options
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## gif
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][6]?** output options
|
|
||||||
|
|
||||||
* `options.reoptimise` **[boolean][10]** always generate new palettes (slow), re-use existing by default (optional, default `false`)
|
|
||||||
* `options.reoptimize` **[boolean][10]** alternative spelling of `options.reoptimise` (optional, default `false`)
|
|
||||||
* `options.colours` **[number][12]** maximum number of palette entries, including transparency, between 2 and 256 (optional, default `256`)
|
|
||||||
* `options.colors` **[number][12]** alternative spelling of `options.colours` (optional, default `256`)
|
|
||||||
* `options.effort` **[number][12]** CPU effort, between 1 (fastest) and 10 (slowest) (optional, default `7`)
|
|
||||||
* `options.dither` **[number][12]** level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) (optional, default `1.0`)
|
|
||||||
* `options.loop` **[number][12]** number of animation iterations, use 0 for infinite animation (optional, default `0`)
|
|
||||||
* `options.delay` **([number][12] | [Array][13]<[number][12]>)?** delay(s) between animation frames (in milliseconds)
|
|
||||||
* `options.force` **[boolean][10]** force GIF output, otherwise attempt to use input format (optional, default `true`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Convert PNG to GIF
|
|
||||||
await sharp(pngBuffer)
|
|
||||||
.gif()
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Convert animated WebP to animated GIF
|
|
||||||
await sharp('animated.webp', { animated: true })
|
|
||||||
.toFile('animated.gif');
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// 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();
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][4]** Invalid options
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
**Meta**
|
|
||||||
|
|
||||||
* **since**: 0.30.0
|
|
||||||
|
|
||||||
## jp2
|
|
||||||
|
|
||||||
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][14].
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][6]?** output options
|
|
||||||
|
|
||||||
* `options.quality` **[number][12]** quality, integer 1-100 (optional, default `80`)
|
|
||||||
* `options.lossless` **[boolean][10]** use lossless compression mode (optional, default `false`)
|
|
||||||
* `options.tileWidth` **[number][12]** horizontal tile size (optional, default `512`)
|
|
||||||
* `options.tileHeight` **[number][12]** vertical tile size (optional, default `512`)
|
|
||||||
* `options.chromaSubsampling` **[string][2]** set to '4:2:0' to use chroma subsampling (optional, default `'4:4:4'`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Convert any input to lossless JP2 output
|
|
||||||
const data = await sharp(input)
|
|
||||||
.jp2({ lossless: true })
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Convert any input to very high quality JP2 output
|
|
||||||
const data = await sharp(input)
|
|
||||||
.jp2({
|
|
||||||
quality: 100,
|
|
||||||
chromaSubsampling: '4:4:4'
|
|
||||||
})
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][4]** Invalid options
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
**Meta**
|
|
||||||
|
|
||||||
* **since**: 0.29.1
|
|
||||||
|
|
||||||
## tiff
|
|
||||||
|
|
||||||
Use these TIFF options for output image.
|
|
||||||
|
|
||||||
The `density` can be set in pixels/inch via [withMetadata][1] instead of providing `xres` and `yres` in pixels/mm.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][6]?** output options
|
|
||||||
|
|
||||||
* `options.quality` **[number][12]** quality, integer 1-100 (optional, default `80`)
|
|
||||||
* `options.force` **[boolean][10]** force TIFF output, otherwise attempt to use input format (optional, default `true`)
|
|
||||||
* `options.compression` **[string][2]** compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k (optional, default `'jpeg'`)
|
|
||||||
* `options.predictor` **[string][2]** compression predictor options: none, horizontal, float (optional, default `'horizontal'`)
|
|
||||||
* `options.pyramid` **[boolean][10]** write an image pyramid (optional, default `false`)
|
|
||||||
* `options.tile` **[boolean][10]** write a tiled tiff (optional, default `false`)
|
|
||||||
* `options.tileWidth` **[number][12]** horizontal tile size (optional, default `256`)
|
|
||||||
* `options.tileHeight` **[number][12]** vertical tile size (optional, default `256`)
|
|
||||||
* `options.xres` **[number][12]** horizontal resolution in pixels/mm (optional, default `1.0`)
|
|
||||||
* `options.yres` **[number][12]** vertical resolution in pixels/mm (optional, default `1.0`)
|
|
||||||
* `options.resolutionUnit` **[string][2]** resolution unit options: inch, cm (optional, default `'inch'`)
|
|
||||||
* `options.bitdepth` **[number][12]** reduce bitdepth to 1, 2 or 4 bit (optional, default `8`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// 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 => { ... });
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][4]** Invalid options
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## avif
|
|
||||||
|
|
||||||
Use these AVIF options for output image.
|
|
||||||
|
|
||||||
Whilst it is possible to create AVIF images smaller than 16x16 pixels,
|
|
||||||
most web browsers do not display these properly.
|
|
||||||
|
|
||||||
AVIF image sequences are not supported.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][6]?** output options
|
|
||||||
|
|
||||||
* `options.quality` **[number][12]** quality, integer 1-100 (optional, default `50`)
|
|
||||||
* `options.lossless` **[boolean][10]** use lossless compression (optional, default `false`)
|
|
||||||
* `options.effort` **[number][12]** CPU effort, between 0 (fastest) and 9 (slowest) (optional, default `4`)
|
|
||||||
* `options.chromaSubsampling` **[string][2]** set to '4:2:0' to use chroma subsampling (optional, default `'4:4:4'`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const data = await sharp(input)
|
|
||||||
.avif({ effort: 2 })
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const data = await sharp(input)
|
|
||||||
.avif({ lossless: true })
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][4]** Invalid options
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
**Meta**
|
|
||||||
|
|
||||||
* **since**: 0.27.0
|
|
||||||
|
|
||||||
## heif
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][6]?** output options
|
|
||||||
|
|
||||||
* `options.quality` **[number][12]** quality, integer 1-100 (optional, default `50`)
|
|
||||||
* `options.compression` **[string][2]** compression format: av1, hevc (optional, default `'av1'`)
|
|
||||||
* `options.lossless` **[boolean][10]** use lossless compression (optional, default `false`)
|
|
||||||
* `options.effort` **[number][12]** CPU effort, between 0 (fastest) and 9 (slowest) (optional, default `4`)
|
|
||||||
* `options.chromaSubsampling` **[string][2]** set to '4:2:0' to use chroma subsampling (optional, default `'4:4:4'`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const data = await sharp(input)
|
|
||||||
.heif({ compression: 'hevc' })
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][4]** Invalid options
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
**Meta**
|
|
||||||
|
|
||||||
* **since**: 0.23.0
|
|
||||||
|
|
||||||
## raw
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][6]?** output options
|
|
||||||
|
|
||||||
* `options.depth` **[string][2]** bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex (optional, default `'uchar'`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Extract raw, unsigned 8-bit RGB pixel data from JPEG input
|
|
||||||
const { data, info } = await sharp('input.jpg')
|
|
||||||
.raw()
|
|
||||||
.toBuffer({ resolveWithObject: true });
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// 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();
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][4]** Invalid options
|
|
||||||
|
|
||||||
## tile
|
|
||||||
|
|
||||||
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`.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][6]?** 
|
|
||||||
|
|
||||||
* `options.size` **[number][12]** tile size in pixels, a value between 1 and 8192. (optional, default `256`)
|
|
||||||
* `options.overlap` **[number][12]** tile overlap in pixels, a value between 0 and 8192. (optional, default `0`)
|
|
||||||
* `options.angle` **[number][12]** tile angle of rotation, must be a multiple of 90. (optional, default `0`)
|
|
||||||
* `options.background` **([string][2] | [Object][6])** background colour, parsed by the [color][15] module, defaults to white without transparency. (optional, default `{r:255,g:255,b:255,alpha:1}`)
|
|
||||||
* `options.depth` **[string][2]?** how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout.
|
|
||||||
* `options.skipBlanks` **[number][12]** threshold to skip tile generation, a value 0 - 255 for 8-bit images or 0 - 65535 for 16-bit images (optional, default `-1`)
|
|
||||||
* `options.container` **[string][2]** tile container, with value `fs` (filesystem) or `zip` (compressed file). (optional, default `'fs'`)
|
|
||||||
* `options.layout` **[string][2]** filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`. (optional, default `'dz'`)
|
|
||||||
* `options.centre` **[boolean][10]** centre image in tile. (optional, default `false`)
|
|
||||||
* `options.center` **[boolean][10]** alternative spelling of centre. (optional, default `false`)
|
|
||||||
* `options.id` **[string][2]** when `layout` is `iiif`/`iiif3`, sets the `@id`/`id` attribute of `info.json` (optional, default `'https://example.com/iiif'`)
|
|
||||||
* `options.basename` **[string][2]?** the name of the directory within the zip file when container is `zip`.
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
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
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const zipFileWithTiles = await sharp(input)
|
|
||||||
.tile({ basename: "tiles" })
|
|
||||||
.toBuffer();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const iiififier = sharp().tile({ layout: "iiif" });
|
|
||||||
readableStream
|
|
||||||
.pipe(iiififier)
|
|
||||||
.pipe(writeableStream);
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][4]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## timeout
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][6]** 
|
|
||||||
|
|
||||||
* `options.seconds` **[number][12]** Number of seconds after which processing will be stopped
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Ensure processing takes no longer than 3 seconds
|
|
||||||
try {
|
|
||||||
const data = await sharp(input)
|
|
||||||
.blur(1000)
|
|
||||||
.timeout({ seconds: 3 })
|
|
||||||
.toBuffer();
|
|
||||||
} catch (err) {
|
|
||||||
if (err.message.includes('timeout')) { ... }
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
**Meta**
|
|
||||||
|
|
||||||
* **since**: 0.29.2
|
|
||||||
|
|
||||||
[1]: #withmetadata
|
|
||||||
|
|
||||||
[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
|
|
||||||
|
|
||||||
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function
|
|
||||||
|
|
||||||
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
|
|
||||||
|
|
||||||
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise
|
|
||||||
|
|
||||||
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
|
|
||||||
|
|
||||||
[7]: #toformat
|
|
||||||
|
|
||||||
[8]: #jpeg
|
|
||||||
|
|
||||||
[9]: #png
|
|
||||||
|
|
||||||
[10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
|
|
||||||
|
|
||||||
[11]: https://nodejs.org/api/buffer.html
|
|
||||||
|
|
||||||
[12]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
|
|
||||||
|
|
||||||
[13]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
|
|
||||||
|
|
||||||
[14]: https://sharp.pixelplumbing.com/install#custom-libvips
|
|
||||||
|
|
||||||
[15]: https://www.npmjs.org/package/color
|
|
||||||
@@ -1,326 +0,0 @@
|
|||||||
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
|
|
||||||
|
|
||||||
## resize
|
|
||||||
|
|
||||||
Resize image to `width`, `height` or `width x height`.
|
|
||||||
|
|
||||||
When both a `width` and `height` are provided, the possible methods by which the image should **fit** these are:
|
|
||||||
|
|
||||||
* `cover`: (default) Preserving aspect ratio, ensure the image covers both provided dimensions by cropping/clipping to fit.
|
|
||||||
* `contain`: Preserving aspect ratio, contain within both provided dimensions using "letterboxing" where necessary.
|
|
||||||
* `fill`: Ignore the aspect ratio of the input and stretch to both provided dimensions.
|
|
||||||
* `inside`: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified.
|
|
||||||
* `outside`: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified.
|
|
||||||
|
|
||||||
Some of these values are based on the [object-fit][1] CSS property.
|
|
||||||
|
|
||||||
When using a `fit` of `cover` or `contain`, the default **position** is `centre`. Other options are:
|
|
||||||
|
|
||||||
* `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`.
|
|
||||||
* `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`.
|
|
||||||
* `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy.
|
|
||||||
|
|
||||||
Some of these values are based on the [object-position][2] CSS property.
|
|
||||||
|
|
||||||
The experimental strategy-based approach resizes so one dimension is at its target length
|
|
||||||
then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.
|
|
||||||
|
|
||||||
* `entropy`: focus on the region with the highest [Shannon entropy][3].
|
|
||||||
* `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
|
|
||||||
|
|
||||||
Possible interpolation kernels are:
|
|
||||||
|
|
||||||
* `nearest`: Use [nearest neighbour interpolation][4].
|
|
||||||
* `cubic`: Use a [Catmull-Rom spline][5].
|
|
||||||
* `mitchell`: Use a [Mitchell-Netravali spline][6].
|
|
||||||
* `lanczos2`: Use a [Lanczos kernel][7] with `a=2`.
|
|
||||||
* `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
|
|
||||||
|
|
||||||
Only one resize can occur per pipeline.
|
|
||||||
Previous calls to `resize` in the same pipeline will be ignored.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `width` **[number][8]?** pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height.
|
|
||||||
* `height` **[number][8]?** pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width.
|
|
||||||
* `options` **[Object][9]?** 
|
|
||||||
|
|
||||||
* `options.width` **[String][10]?** alternative means of specifying `width`. If both are present this take priority.
|
|
||||||
* `options.height` **[String][10]?** alternative means of specifying `height`. If both are present this take priority.
|
|
||||||
* `options.fit` **[String][10]** how the image should be resized to fit both provided dimensions, one of `cover`, `contain`, `fill`, `inside` or `outside`. (optional, default `'cover'`)
|
|
||||||
* `options.position` **[String][10]** position, gravity or strategy to use when `fit` is `cover` or `contain`. (optional, default `'centre'`)
|
|
||||||
* `options.background` **([String][10] | [Object][9])** background colour when `fit` is `contain`, parsed by the [color][11] module, defaults to black without transparency. (optional, default `{r:0,g:0,b:0,alpha:1}`)
|
|
||||||
* `options.kernel` **[String][10]** the kernel to use for image reduction. (optional, default `'lanczos3'`)
|
|
||||||
* `options.withoutEnlargement` **[Boolean][12]** do not enlarge if the width *or* height are already less than the specified dimensions, equivalent to GraphicsMagick's `>` geometry option. (optional, default `false`)
|
|
||||||
* `options.withoutReduction` **[Boolean][12]** do not reduce if the width *or* height are already greater than the specified dimensions, equivalent to GraphicsMagick's `<` geometry option. (optional, default `false`)
|
|
||||||
* `options.fastShrinkOnLoad` **[Boolean][12]** take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern on some images. (optional, default `true`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
sharp(input)
|
|
||||||
.resize({ width: 100 })
|
|
||||||
.toBuffer()
|
|
||||||
.then(data => {
|
|
||||||
// 100 pixels wide, auto-scaled height
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
sharp(input)
|
|
||||||
.resize({ height: 100 })
|
|
||||||
.toBuffer()
|
|
||||||
.then(data => {
|
|
||||||
// 100 pixels high, auto-scaled width
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
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
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
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);
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
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
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
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
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const scaleByHalf = await sharp(input)
|
|
||||||
.metadata()
|
|
||||||
.then(({ width }) => sharp(input)
|
|
||||||
.resize(Math.round(width * 0.5))
|
|
||||||
.toBuffer()
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][13]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## extend
|
|
||||||
|
|
||||||
Extends/pads the edges of the image with the provided background colour.
|
|
||||||
This operation will always occur after resizing and extraction, if any.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `extend` **([number][8] | [Object][9])** single pixel count to add to all edges or an Object with per-edge counts
|
|
||||||
|
|
||||||
* `extend.top` **[number][8]** (optional, default `0`)
|
|
||||||
* `extend.left` **[number][8]** (optional, default `0`)
|
|
||||||
* `extend.bottom` **[number][8]** (optional, default `0`)
|
|
||||||
* `extend.right` **[number][8]** (optional, default `0`)
|
|
||||||
* `extend.background` **([String][10] | [Object][9])** background colour, parsed by the [color][11] module, defaults to black without transparency. (optional, default `{r:0,g:0,b:0,alpha:1}`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// 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 }
|
|
||||||
})
|
|
||||||
...
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Add a row of 10 red pixels to the bottom
|
|
||||||
sharp(input)
|
|
||||||
.extend({
|
|
||||||
bottom: 10,
|
|
||||||
background: 'red'
|
|
||||||
})
|
|
||||||
...
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][13]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## extract
|
|
||||||
|
|
||||||
Extract/crop a region of the image.
|
|
||||||
|
|
||||||
* Use `extract` before `resize` for pre-resize extraction.
|
|
||||||
* Use `extract` after `resize` for post-resize extraction.
|
|
||||||
* Use `extract` before and after for both.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **[Object][9]** describes the region to extract using integral pixel values
|
|
||||||
|
|
||||||
* `options.left` **[number][8]** zero-indexed offset from left edge
|
|
||||||
* `options.top` **[number][8]** zero-indexed offset from top edge
|
|
||||||
* `options.width` **[number][8]** width of region to extract
|
|
||||||
* `options.height` **[number][8]** height of region to extract
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
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.
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
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
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][13]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## trim
|
|
||||||
|
|
||||||
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, obtained from callback of `.toFile()` or `.toBuffer()`,
|
|
||||||
will contain `trimOffsetLeft` and `trimOffsetTop` properties.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `trim` **([string][10] | [number][8] | [Object][9])** the specific background colour to trim, the threshold for doing so or an Object with both.
|
|
||||||
|
|
||||||
* `trim.background` **([string][10] | [Object][9])** background colour, parsed by the [color][11] module, defaults to that of the top-left pixel. (optional, default `'top-left pixel'`)
|
|
||||||
* `trim.threshold` **[number][8]** the allowed difference from the above colour, a positive number. (optional, default `10`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Trim pixels with a colour similar to that of the top-left pixel.
|
|
||||||
sharp(input)
|
|
||||||
.trim()
|
|
||||||
.toFile(output, function(err, info) {
|
|
||||||
...
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Trim pixels with the exact same colour as that of the top-left pixel.
|
|
||||||
sharp(input)
|
|
||||||
.trim(0)
|
|
||||||
.toFile(output, function(err, info) {
|
|
||||||
...
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Trim only pixels with a similar colour to red.
|
|
||||||
sharp(input)
|
|
||||||
.trim("#FF0000")
|
|
||||||
.toFile(output, function(err, info) {
|
|
||||||
...
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
|
|
||||||
sharp(input)
|
|
||||||
.trim({
|
|
||||||
background: "yellow",
|
|
||||||
threshold: 42,
|
|
||||||
})
|
|
||||||
.toFile(output, function(err, info) {
|
|
||||||
...
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
* Throws **[Error][13]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
[1]: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
|
|
||||||
|
|
||||||
[2]: https://developer.mozilla.org/en-US/docs/Web/CSS/object-position
|
|
||||||
|
|
||||||
[3]: https://en.wikipedia.org/wiki/Entropy_%28information_theory%29
|
|
||||||
|
|
||||||
[4]: http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation
|
|
||||||
|
|
||||||
[5]: https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline
|
|
||||||
|
|
||||||
[6]: https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf
|
|
||||||
|
|
||||||
[7]: https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel
|
|
||||||
|
|
||||||
[8]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
|
|
||||||
|
|
||||||
[9]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
|
|
||||||
|
|
||||||
[10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
|
|
||||||
|
|
||||||
[11]: https://www.npmjs.org/package/color
|
|
||||||
|
|
||||||
[12]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
|
|
||||||
|
|
||||||
[13]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
|
|
||||||
@@ -1,216 +0,0 @@
|
|||||||
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
|
|
||||||
|
|
||||||
## format
|
|
||||||
|
|
||||||
An Object containing nested boolean values representing the available input and output formats/methods.
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
console.log(sharp.format);
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **[Object][1]** 
|
|
||||||
|
|
||||||
## interpolators
|
|
||||||
|
|
||||||
An Object containing the available interpolators and their proper values
|
|
||||||
|
|
||||||
Type: [string][2]
|
|
||||||
|
|
||||||
### nearest
|
|
||||||
|
|
||||||
[Nearest neighbour interpolation][3]. Suitable for image enlargement only.
|
|
||||||
|
|
||||||
### bilinear
|
|
||||||
|
|
||||||
[Bilinear interpolation][4]. Faster than bicubic but with less smooth results.
|
|
||||||
|
|
||||||
### bicubic
|
|
||||||
|
|
||||||
[Bicubic interpolation][5] (the default).
|
|
||||||
|
|
||||||
### locallyBoundedBicubic
|
|
||||||
|
|
||||||
[LBB interpolation][6]. Prevents some "[acutance][7]" but typically reduces performance by a factor of 2.
|
|
||||||
|
|
||||||
### nohalo
|
|
||||||
|
|
||||||
[Nohalo interpolation][8]. Prevents acutance but typically reduces performance by a factor of 3.
|
|
||||||
|
|
||||||
### vertexSplitQuadraticBasisSpline
|
|
||||||
|
|
||||||
[VSQBS interpolation][9]. Prevents "staircasing" when enlarging.
|
|
||||||
|
|
||||||
## versions
|
|
||||||
|
|
||||||
An Object containing the version numbers of libvips and its dependencies.
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
console.log(sharp.versions);
|
|
||||||
```
|
|
||||||
|
|
||||||
## vendor
|
|
||||||
|
|
||||||
An Object containing the platform and architecture
|
|
||||||
of the current and installed vendored binaries.
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
console.log(sharp.vendor);
|
|
||||||
```
|
|
||||||
|
|
||||||
## cache
|
|
||||||
|
|
||||||
Gets or, when options are provided, sets the limits of *libvips'* operation cache.
|
|
||||||
Existing entries in the cache will be trimmed after any change in limits.
|
|
||||||
This method always returns cache statistics,
|
|
||||||
useful for determining how much working memory is required for a particular task.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `options` **([Object][1] | [boolean][10])** Object with the following attributes, or boolean where true uses default cache settings and false removes all caching (optional, default `true`)
|
|
||||||
|
|
||||||
* `options.memory` **[number][11]** is the maximum memory in MB to use for this cache (optional, default `50`)
|
|
||||||
* `options.files` **[number][11]** is the maximum number of files to hold open (optional, default `20`)
|
|
||||||
* `options.items` **[number][11]** is the maximum number of operations to cache (optional, default `100`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const stats = sharp.cache();
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
sharp.cache( { items: 200 } );
|
|
||||||
sharp.cache( { files: 0 } );
|
|
||||||
sharp.cache(false);
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **[Object][1]** 
|
|
||||||
|
|
||||||
## concurrency
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
The maximum number of images that sharp can process in parallel
|
|
||||||
is controlled by libuv's `UV_THREADPOOL_SIZE` environment variable,
|
|
||||||
which defaults to 4.
|
|
||||||
|
|
||||||
[https://nodejs.org/api/cli.html#uv\_threadpool\_sizesize][12]
|
|
||||||
|
|
||||||
For example, by default, a machine with 8 CPU cores will process
|
|
||||||
4 images in parallel and use up to 8 threads per image,
|
|
||||||
so there will be up to 32 concurrent threads.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `concurrency` **[number][11]?** 
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const threads = sharp.concurrency(); // 4
|
|
||||||
sharp.concurrency(2); // 2
|
|
||||||
sharp.concurrency(0); // 4
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **[number][11]** concurrency
|
|
||||||
|
|
||||||
## queue
|
|
||||||
|
|
||||||
An EventEmitter that emits a `change` event when a task is either:
|
|
||||||
|
|
||||||
* queued, waiting for *libuv* to provide a worker thread
|
|
||||||
* complete
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
sharp.queue.on('change', function(queueLength) {
|
|
||||||
console.log('Queue contains ' + queueLength + ' task(s)');
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
## counters
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const counters = sharp.counters(); // { queue: 2, process: 4 }
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **[Object][1]** 
|
|
||||||
|
|
||||||
## simd
|
|
||||||
|
|
||||||
Get and set use of SIMD vector unit instructions.
|
|
||||||
Requires libvips to have been compiled with liborc 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.
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `simd` **[boolean][10]** (optional, default `true`)
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const simd = sharp.simd();
|
|
||||||
// simd is `true` if the runtime use of liborc is currently enabled
|
|
||||||
```
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const simd = sharp.simd(false);
|
|
||||||
// prevent libvips from using liborc at runtime
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns **[boolean][10]** 
|
|
||||||
|
|
||||||
[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
|
|
||||||
|
|
||||||
[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
|
|
||||||
|
|
||||||
[3]: http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation
|
|
||||||
|
|
||||||
[4]: http://en.wikipedia.org/wiki/Bilinear_interpolation
|
|
||||||
|
|
||||||
[5]: http://en.wikipedia.org/wiki/Bicubic_interpolation
|
|
||||||
|
|
||||||
[6]: https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100
|
|
||||||
|
|
||||||
[7]: http://en.wikipedia.org/wiki/Acutance
|
|
||||||
|
|
||||||
[8]: http://eprints.soton.ac.uk/268086/
|
|
||||||
|
|
||||||
[9]: https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48
|
|
||||||
|
|
||||||
[10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
|
|
||||||
|
|
||||||
[11]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
|
|
||||||
|
|
||||||
[12]: https://nodejs.org/api/cli.html#uv_threadpool_sizesize
|
|
||||||
79
docs/astro.config.mjs
Normal 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' }
|
||||||
|
]
|
||||||
|
})
|
||||||
|
]
|
||||||
|
});
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
const fs = require('fs').promises;
|
|
||||||
const path = require('path');
|
|
||||||
|
|
||||||
[
|
|
||||||
'constructor',
|
|
||||||
'input',
|
|
||||||
'resize',
|
|
||||||
'composite',
|
|
||||||
'operation',
|
|
||||||
'colour',
|
|
||||||
'channel',
|
|
||||||
'output',
|
|
||||||
'utility'
|
|
||||||
].forEach(async (m) => {
|
|
||||||
const documentation = await import('documentation');
|
|
||||||
|
|
||||||
const input = path.join('lib', `${m}.js`);
|
|
||||||
const output = path.join('docs', `api-${m}.md`);
|
|
||||||
|
|
||||||
const ast = await documentation.build(input, { shallow: true });
|
|
||||||
const markdown = await documentation.formats.md(ast, { markdownToc: false });
|
|
||||||
|
|
||||||
await fs.writeFile(output, markdown);
|
|
||||||
});
|
|
||||||
42
docs/build.mjs
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
// Copyright 2013 Lovell Fuller and others.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
import fs from 'node:fs/promises';
|
||||||
|
import path from 'node:path';
|
||||||
|
import jsdoc2md from 'jsdoc-to-markdown';
|
||||||
|
|
||||||
|
const pages = {
|
||||||
|
constructor: 'Constructor',
|
||||||
|
input: 'Input metadata',
|
||||||
|
resize: 'Resizing images',
|
||||||
|
composite: 'Compositing images',
|
||||||
|
operation: 'Image operations',
|
||||||
|
colour: 'Colour manipulation',
|
||||||
|
channel: 'Channel manipulation',
|
||||||
|
output: 'Output options',
|
||||||
|
utility: 'Global properties'
|
||||||
|
};
|
||||||
|
|
||||||
|
Object.keys(pages).forEach(async (m) => {
|
||||||
|
const input = path.join('lib', `${m}.js`);
|
||||||
|
const output = path.join('docs', 'src', 'content', 'docs', `api-${m}.md`);
|
||||||
|
|
||||||
|
const ast = await jsdoc2md.getTemplateData({ files: input });
|
||||||
|
const markdown = await jsdoc2md.render({
|
||||||
|
data: ast,
|
||||||
|
'global-index-format': 'none',
|
||||||
|
'module-index-format': 'none'
|
||||||
|
});
|
||||||
|
|
||||||
|
const cleanMarkdown =
|
||||||
|
`---\n# This file was auto-generated from JSDoc in lib/${m}.js\ntitle: ${pages[m]}\n---\n\n` +
|
||||||
|
markdown
|
||||||
|
.replace(/(## )([A-Za-z0-9]+)([^\n]*)/g, '$1$2\n> $2$3\n') // simplify headings
|
||||||
|
.replace(/<a name="[A-Za-z0-9+]+"><\/a>/g, '') // remove anchors
|
||||||
|
.replace(/\*\*Kind\*\*: global[^\n]+/g, '') // remove all "global" Kind labels (requires JSDoc refactoring)
|
||||||
|
.trim();
|
||||||
|
|
||||||
|
await fs.writeFile(output, cleanMarkdown);
|
||||||
|
});
|
||||||
1
docs/docute.min.js
vendored
@@ -1,14 +1,7 @@
|
|||||||
{
|
{
|
||||||
"hosting": {
|
"hosting": {
|
||||||
"site": "pixelplumbing-sharp",
|
"site": "pixelplumbing-sharp",
|
||||||
"public": ".",
|
"public": "dist",
|
||||||
"ignore": [
|
|
||||||
".*",
|
|
||||||
"build.js",
|
|
||||||
"firebase.json",
|
|
||||||
"image/**",
|
|
||||||
"search-index/**"
|
|
||||||
],
|
|
||||||
"headers": [
|
"headers": [
|
||||||
{
|
{
|
||||||
"source": "**",
|
"source": "**",
|
||||||
@@ -18,99 +11,6 @@
|
|||||||
{ "key": "X-Frame-Options", "value": "SAMEORIGIN" }
|
{ "key": "X-Frame-Options", "value": "SAMEORIGIN" }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
|
||||||
"redirects": [
|
|
||||||
{
|
|
||||||
"source": "**/install/**",
|
|
||||||
"destination": "/install",
|
|
||||||
"type": 301
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": "/page/install",
|
|
||||||
"destination": "/install",
|
|
||||||
"type": 301
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": "**/api-constructor/**",
|
|
||||||
"destination": "/api-constructor",
|
|
||||||
"type": 301
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": "**/api-input/**",
|
|
||||||
"destination": "/api-input",
|
|
||||||
"type": 301
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": "**/api-output/**",
|
|
||||||
"destination": "/api-output",
|
|
||||||
"type": 301
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": "**/api-resize/**",
|
|
||||||
"destination": "/api-resize",
|
|
||||||
"type": 301
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": "**/api-compsite/**",
|
|
||||||
"destination": "/api-compsite",
|
|
||||||
"type": 301
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": "**/api-operation/**",
|
|
||||||
"destination": "/api-operation",
|
|
||||||
"type": 301
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": "**/api-colour/**",
|
|
||||||
"destination": "/api-colour",
|
|
||||||
"type": 301
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": "**/api-channel/**",
|
|
||||||
"destination": "/api-channel",
|
|
||||||
"type": 301
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": "**/api-utility/**",
|
|
||||||
"destination": "/api-utility",
|
|
||||||
"type": 301
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": "/page/api",
|
|
||||||
"destination": "/api-constructor",
|
|
||||||
"type": 301
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": "**/performance/**",
|
|
||||||
"destination": "/performance",
|
|
||||||
"type": 301
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": "/page/performance",
|
|
||||||
"destination": "/performance",
|
|
||||||
"type": 301
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": "**/changelog/**",
|
|
||||||
"destination": "/changelog",
|
|
||||||
"type": 301
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": "/page/changelog",
|
|
||||||
"destination": "/changelog",
|
|
||||||
"type": 301
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": "/en/**",
|
|
||||||
"destination": "/",
|
|
||||||
"type": 301
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"rewrites": [
|
|
||||||
{
|
|
||||||
"source": "**",
|
|
||||||
"destination": "/index.html"
|
|
||||||
}
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 661 B |
206
docs/index.html
353
docs/install.md
@@ -1,353 +0,0 @@
|
|||||||
# Installation
|
|
||||||
|
|
||||||
```sh
|
|
||||||
npm install sharp
|
|
||||||
```
|
|
||||||
|
|
||||||
```sh
|
|
||||||
yarn add sharp
|
|
||||||
```
|
|
||||||
|
|
||||||
## Prerequisites
|
|
||||||
|
|
||||||
* Node.js >= 14.15.0
|
|
||||||
|
|
||||||
## Prebuilt binaries
|
|
||||||
|
|
||||||
Ready-compiled sharp and libvips binaries are provided for use on the most common platforms:
|
|
||||||
|
|
||||||
* macOS x64 (>= 10.13)
|
|
||||||
* macOS ARM64
|
|
||||||
* Linux x64 (glibc >= 2.17, musl >= 1.1.24, CPU with SSE4.2)
|
|
||||||
* Linux ARM64 (glibc >= 2.17, musl >= 1.1.24)
|
|
||||||
* Windows x64
|
|
||||||
* Windows x86
|
|
||||||
|
|
||||||
A ~7MB tarball containing libvips and its most commonly used dependencies
|
|
||||||
is downloaded via HTTPS, verified via Subresource Integrity
|
|
||||||
and decompressed into `node_modules/sharp/vendor` during `npm install`.
|
|
||||||
|
|
||||||
This provides support for the
|
|
||||||
JPEG, PNG, WebP, AVIF, TIFF, GIF and SVG (input) image formats.
|
|
||||||
|
|
||||||
The following platforms have prebuilt libvips but not sharp:
|
|
||||||
|
|
||||||
* Linux ARMv7 (glibc >= 2.28)
|
|
||||||
* Linux ARMv6 (glibc >= 2.28)
|
|
||||||
* Windows ARM64
|
|
||||||
|
|
||||||
The following platforms require compilation of both libvips and sharp from source:
|
|
||||||
|
|
||||||
* Linux x86
|
|
||||||
* Linux ARMv7 (glibc <= 2.27, musl)
|
|
||||||
* Linux ARMv6 (glibc <= 2.27, musl)
|
|
||||||
* Linux PowerPC
|
|
||||||
* FreeBSD
|
|
||||||
* OpenBSD
|
|
||||||
|
|
||||||
## Common problems
|
|
||||||
|
|
||||||
The architecture and platform of Node.js used for `npm install`
|
|
||||||
must be the same as the architecture and platform of Node.js used at runtime.
|
|
||||||
See the [cross-platform](#cross-platform) section if this is not the case.
|
|
||||||
|
|
||||||
When using npm v6 or earlier, the `npm install --unsafe-perm` flag must be used when installing as `root` or a `sudo` user.
|
|
||||||
|
|
||||||
When using npm v7 or later, the user running `npm install` must own the directory it is run in.
|
|
||||||
|
|
||||||
The `npm install --ignore-scripts=false` flag must be used when `npm` has been configured to ignore installation scripts.
|
|
||||||
|
|
||||||
Check the output of running `npm install --verbose --foreground-scripts sharp` for useful error messages.
|
|
||||||
|
|
||||||
## Apple M1
|
|
||||||
|
|
||||||
Prebuilt sharp and libvips binaries have been provided for macOS on ARM64 since sharp v0.29.0.
|
|
||||||
|
|
||||||
## Cross-platform
|
|
||||||
|
|
||||||
At `npm install` time, prebuilt binaries are automatically selected for the
|
|
||||||
current OS platform and CPU architecture, where available.
|
|
||||||
|
|
||||||
The target platform and/or architecture can be manually selected using the following flags.
|
|
||||||
|
|
||||||
```sh
|
|
||||||
npm install --platform=... --arch=... --arm-version=... sharp
|
|
||||||
```
|
|
||||||
|
|
||||||
* `--platform`: one of `linux`, `darwin` or `win32`.
|
|
||||||
* `--arch`: one of `x64`, `ia32`, `arm` or `arm64`.
|
|
||||||
* `--arm-version`: one of `6`, `7` or `8` (`arm` defaults to `6`, `arm64` defaults to `8`).
|
|
||||||
* `--libc`: one of `glibc` or `musl`. This option only works with platform `linux`, defaults to `glibc`
|
|
||||||
* `--sharp-install-force`: skip version compatibility and Subresource Integrity checks.
|
|
||||||
|
|
||||||
These values can also be set via environment variables,
|
|
||||||
`npm_config_platform`, `npm_config_arch`, `npm_config_arm_version`, `npm_config_libc`
|
|
||||||
and `SHARP_INSTALL_FORCE` respectively.
|
|
||||||
|
|
||||||
For example, if the target machine has a 64-bit ARM CPU and is running Alpine Linux,
|
|
||||||
use the following flags:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
npm install --arch=arm64 --platform=linux --libc=musl sharp
|
|
||||||
```
|
|
||||||
|
|
||||||
If the current machine is Alpine Linux and the target machine is Debian Linux on x64 cpu,
|
|
||||||
use the following flags:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
npm install --arch=x64 --platform=linux --libc=glibc sharp
|
|
||||||
```
|
|
||||||
|
|
||||||
Multiple platforms and architectures can be supported within the same installation tree.
|
|
||||||
The following example for macOS installs x64 binaries then adds (via a rebuild) arm64 binaries:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
npm install --platform=darwin --arch=x64 sharp
|
|
||||||
npm rebuild --platform=darwin --arch=arm64 sharp
|
|
||||||
```
|
|
||||||
|
|
||||||
## Custom libvips
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
## Building from source
|
|
||||||
|
|
||||||
This module will be compiled from source at `npm install` time when:
|
|
||||||
|
|
||||||
* a globally-installed libvips is detected (set the `SHARP_IGNORE_GLOBAL_LIBVIPS` environment variable to skip this),
|
|
||||||
* prebuilt sharp binaries do not exist for the current platform, or
|
|
||||||
* when the `npm install --build-from-source` flag is used.
|
|
||||||
|
|
||||||
Building from source requires:
|
|
||||||
|
|
||||||
* C++11 compiler
|
|
||||||
* [node-gyp](https://github.com/nodejs/node-gyp#installation) and its dependencies
|
|
||||||
|
|
||||||
## Custom prebuilt binaries
|
|
||||||
|
|
||||||
This is an advanced approach that most people will not require.
|
|
||||||
|
|
||||||
### Prebuilt sharp binaries
|
|
||||||
|
|
||||||
To install the prebuilt sharp binaries from a custom URL,
|
|
||||||
set the `sharp_binary_host` npm config option
|
|
||||||
or the `npm_config_sharp_binary_host` environment variable.
|
|
||||||
|
|
||||||
To install the prebuilt sharp binaries from a directory on the local filesystem,
|
|
||||||
set the `sharp_local_prebuilds` npm config option
|
|
||||||
or the `npm_config_sharp_local_prebuilds` environment variable.
|
|
||||||
|
|
||||||
URL example:
|
|
||||||
if `sharp_binary_host` is set to `https://hostname/path`
|
|
||||||
and the sharp version is `1.2.3` then the resultant URL will be
|
|
||||||
`https://hostname/path/sharp-v1.2.3-napi-v5-platform-arch.tar.gz`.
|
|
||||||
|
|
||||||
Filename example:
|
|
||||||
if `sharp_local_prebuilds` is set to `/path`
|
|
||||||
and the sharp version is `1.2.3` then the resultant filename will be
|
|
||||||
`/path/sharp-v1.2.3-napi-v5-platform-arch.tar.gz`.
|
|
||||||
|
|
||||||
### Prebuilt libvips binaries
|
|
||||||
|
|
||||||
To install the prebuilt libvips binaries from a custom URL,
|
|
||||||
set the `sharp_libvips_binary_host` npm config option
|
|
||||||
or the `npm_config_sharp_libvips_binary_host` environment variable.
|
|
||||||
|
|
||||||
To install the prebuilt libvips binaries from a directory on the local filesystem,
|
|
||||||
set the `sharp_libvips_local_prebuilds` npm config option
|
|
||||||
or the `npm_config_sharp_libvips_local_prebuilds` environment variable.
|
|
||||||
|
|
||||||
The version subpath and filename are appended to these.
|
|
||||||
|
|
||||||
URL example:
|
|
||||||
if `sharp_libvips_binary_host` is set to `https://hostname/path`
|
|
||||||
and the libvips version is `4.5.6` then the resultant URL will be
|
|
||||||
`https://hostname/path/v4.5.6/libvips-4.5.6-platform-arch.tar.br`.
|
|
||||||
|
|
||||||
Filename example:
|
|
||||||
if `sharp_libvips_local_prebuilds` is set to `/path`
|
|
||||||
and the libvips version is `4.5.6` then the resultant filename will be
|
|
||||||
`/path/v4.5.6/libvips-4.5.6-platform-arch.tar.br`.
|
|
||||||
|
|
||||||
See the Chinese mirror below for a further example.
|
|
||||||
|
|
||||||
## Chinese mirror
|
|
||||||
|
|
||||||
A mirror site based in China, provided by Alibaba, contains binaries for both sharp and libvips.
|
|
||||||
|
|
||||||
To use this either set the following configuration:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
npm config set sharp_binary_host "https://npmmirror.com/mirrors/sharp"
|
|
||||||
npm config set sharp_libvips_binary_host "https://npmmirror.com/mirrors/sharp-libvips"
|
|
||||||
npm install sharp
|
|
||||||
```
|
|
||||||
|
|
||||||
or set the following environment variables:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
npm_config_sharp_binary_host="https://npmmirror.com/mirrors/sharp" \
|
|
||||||
npm_config_sharp_libvips_binary_host="https://npmmirror.com/mirrors/sharp-libvips" \
|
|
||||||
npm install 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.
|
|
||||||
|
|
||||||
## Heroku
|
|
||||||
|
|
||||||
Add the
|
|
||||||
[jemalloc buildpack](https://github.com/gaffneyc/heroku-buildpack-jemalloc)
|
|
||||||
to reduce the effects of memory fragmentation.
|
|
||||||
|
|
||||||
Set
|
|
||||||
[NODE_MODULES_CACHE](https://devcenter.heroku.com/articles/nodejs-support#cache-behavior)
|
|
||||||
to `false` when using the `yarn` package manager.
|
|
||||||
|
|
||||||
## 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 the Linux x64 platform.
|
|
||||||
|
|
||||||
When building your deployment package on machines other than Linux x64 (glibc),
|
|
||||||
run the following additional command after `npm install`:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
npm install
|
|
||||||
rm -rf node_modules/sharp
|
|
||||||
SHARP_IGNORE_GLOBAL_LIBVIPS=1 npm install --arch=x64 --platform=linux --libc=glibc sharp
|
|
||||||
```
|
|
||||||
|
|
||||||
To get the best performance select the largest memory available.
|
|
||||||
A 1536 MB function provides ~12x more CPU time than a 128 MB function.
|
|
||||||
|
|
||||||
## 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 --arch=x64 --platform=linux sharp
|
|
||||||
```
|
|
||||||
|
|
||||||
## Fonts
|
|
||||||
|
|
||||||
When creating text images or rendering SVG images that contain text elements,
|
|
||||||
`fontconfig` is used to find the relevant fonts.
|
|
||||||
|
|
||||||
On Windows and macOS systems, all system fonts are available for use.
|
|
||||||
|
|
||||||
On macOS systems using Homebrew, you may need to set the
|
|
||||||
`PANGOCAIRO_BACKEND` environment variable to a value of `fontconfig`
|
|
||||||
to ensure it is used for font discovery instead of Core Text.
|
|
||||||
|
|
||||||
On Linux systems, fonts that include the relevant
|
|
||||||
[`fontconfig` configuration](https://www.freedesktop.org/software/fontconfig/fontconfig-user.html)
|
|
||||||
when installed via package manager are available for use.
|
|
||||||
|
|
||||||
If `fontconfig` configuration is not found, the following error will occur:
|
|
||||||
```
|
|
||||||
Fontconfig error: Cannot load default config file
|
|
||||||
```
|
|
||||||
|
|
||||||
In serverless environments where there is no control over font packages,
|
|
||||||
use the `FONTCONFIG_PATH` environment variable to point to a custom location.
|
|
||||||
|
|
||||||
Embedded SVG fonts are unsupported.
|
|
||||||
|
|
||||||
## Worker threads
|
|
||||||
|
|
||||||
On some platforms, including glibc-based Linux,
|
|
||||||
the main thread must call `require('sharp')`
|
|
||||||
_before_ worker threads are created.
|
|
||||||
This is to ensure shared libraries remain loaded in memory
|
|
||||||
until after all threads are complete.
|
|
||||||
|
|
||||||
Without this, the following error may occur:
|
|
||||||
```
|
|
||||||
Module did not self-register
|
|
||||||
```
|
|
||||||
|
|
||||||
## Known conflicts
|
|
||||||
|
|
||||||
### Canvas and Windows
|
|
||||||
|
|
||||||
The prebuilt binaries provided by `canvas` for Windows depend on the unmaintained GTK 2, last updated in 2011.
|
|
||||||
|
|
||||||
These conflict with the modern, up-to-date binaries provided by sharp.
|
|
||||||
|
|
||||||
If both modules are used in the same Windows process, the following error will occur:
|
|
||||||
```
|
|
||||||
The specified procedure could not be found.
|
|
||||||
```
|
|
||||||
17
docs/package.json
Normal 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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
# Performance
|
|
||||||
|
|
||||||
A test to benchmark the performance of this module relative to alternatives.
|
|
||||||
|
|
||||||
## The contenders
|
|
||||||
|
|
||||||
* [jimp](https://www.npmjs.com/package/jimp) v0.16.1 - Image processing in pure JavaScript. Provides bicubic interpolation.
|
|
||||||
* [mapnik](https://www.npmjs.org/package/mapnik) v4.5.9 - Whilst primarily a map renderer, Mapnik contains bitmap image utilities.
|
|
||||||
* [imagemagick](https://www.npmjs.com/package/imagemagick) v0.1.3 - Supports filesystem only and "*has been unmaintained for a long time*".
|
|
||||||
* [gm](https://www.npmjs.com/package/gm) v1.23.1 - Fully featured wrapper around GraphicsMagick's `gm` command line utility.
|
|
||||||
* [@squoosh/lib](https://www.npmjs.com/package/@squoosh/lib) v0.4.0 - Image libraries transpiled to WebAssembly, includes GPLv3 code.
|
|
||||||
* [@squoosh/cli](https://www.npmjs.com/package/@squoosh/cli) v0.7.2 - Command line wrapper around `@squoosh/lib`, avoids GPLv3 by spawning process.
|
|
||||||
* sharp v0.31.0 / libvips v8.13.1 - Caching within libvips disabled to ensure a fair comparison.
|
|
||||||
|
|
||||||
## The task
|
|
||||||
|
|
||||||
Decompress a 2725x2225 JPEG image,
|
|
||||||
resize to 720x588 using Lanczos 3 resampling (where available),
|
|
||||||
then compress to JPEG at a "quality" setting of 80.
|
|
||||||
|
|
||||||
## Test environment
|
|
||||||
|
|
||||||
* AWS EC2 eu-west-1 [c6a.xlarge](https://aws.amazon.com/ec2/instance-types/c6a/) (4x AMD EPYC 7R13)
|
|
||||||
* Ubuntu 22.04 (ami-051f7c00cb18501ee)
|
|
||||||
* Node.js 16.17.0
|
|
||||||
|
|
||||||
## Results
|
|
||||||
|
|
||||||
| Module | Input | Output | Ops/sec | Speed-up |
|
|
||||||
| :----------------- | :----- | :----- | ------: | -------: |
|
|
||||||
| jimp | buffer | buffer | 0.96 | 1.0 |
|
|
||||||
| squoosh-cli | file | file | 1.10 | 1.1 |
|
|
||||||
| squoosh-lib | buffer | buffer | 1.87 | 1.9 |
|
|
||||||
| mapnik | buffer | buffer | 3.48 | 3.6 |
|
|
||||||
| gm | buffer | buffer | 8.53 | 8.9 |
|
|
||||||
| gm | file | file | 8.60 | 9.0 |
|
|
||||||
| imagemagick | file | file | 9.30 | 9.7 |
|
|
||||||
| sharp | stream | stream | 32.86 | 34.2 |
|
|
||||||
| sharp | file | file | 34.82 | 36.3 |
|
|
||||||
| sharp | buffer | buffer | 35.41 | 36.9 |
|
|
||||||
|
|
||||||
Greater libvips performance can be expected with caching enabled (default)
|
|
||||||
and using 8+ core machines, especially those with larger L1/L2 CPU caches.
|
|
||||||
|
|
||||||
The I/O limits of the relevant (de)compression library will generally determine maximum throughput.
|
|
||||||
|
|
||||||
## Running the benchmark test
|
|
||||||
|
|
||||||
Requires Docker.
|
|
||||||
|
|
||||||
```sh
|
|
||||||
git clone https://github.com/lovell/sharp.git
|
|
||||||
cd sharp/test/bench
|
|
||||||
./run-with-docker.sh
|
|
||||||
```
|
|
||||||
61
docs/public/api-resize-fit.svg
Normal 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 |
|
Before Width: | Height: | Size: 508 B After Width: | Height: | Size: 508 B |
@@ -28,7 +28,7 @@ Name: Brandon Aaron
|
|||||||
GitHub: https://github.com/brandonaaron
|
GitHub: https://github.com/brandonaaron
|
||||||
|
|
||||||
Name: Andreas Lind
|
Name: Andreas Lind
|
||||||
GitHub: https://github.com/papandreouGitHub:
|
GitHub: https://github.com/papandreou
|
||||||
|
|
||||||
Name: Maurus Cuelenaere
|
Name: Maurus Cuelenaere
|
||||||
GitHub: https://github.com/mcuelenaere
|
GitHub: https://github.com/mcuelenaere
|
||||||
@@ -260,3 +260,66 @@ GitHub: https://github.com/brahima
|
|||||||
|
|
||||||
Name: Anton Marsden
|
Name: Anton Marsden
|
||||||
GitHub: https://github.com/antonmarsden
|
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
@@ -0,0 +1,4 @@
|
|||||||
|
User-agent: *
|
||||||
|
Disallow:
|
||||||
|
|
||||||
|
Sitemap: https://sharp.pixelplumbing.com/sitemap-index.xml
|
||||||
|
Before Width: | Height: | Size: 929 B After Width: | Height: | Size: 929 B |
5
docs/public/sharp-logo.svg
Normal 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 |
@@ -1,2 +0,0 @@
|
|||||||
User-agent: *
|
|
||||||
Disallow:
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
const { extractDescription, extractKeywords, extractParameters } = require('./extract');
|
|
||||||
|
|
||||||
const searchIndex = [];
|
|
||||||
|
|
||||||
// Install
|
|
||||||
const contents = fs.readFileSync(path.join(__dirname, '..', 'install.md'), 'utf8');
|
|
||||||
const matches = contents.matchAll(
|
|
||||||
/## (?<title>[A-Za-z0-9 ]+)\n\n(?<body>[^#]+)/gs
|
|
||||||
);
|
|
||||||
for (const match of matches) {
|
|
||||||
const { title, body } = match.groups;
|
|
||||||
const description = extractDescription(body);
|
|
||||||
|
|
||||||
searchIndex.push({
|
|
||||||
t: title,
|
|
||||||
d: description,
|
|
||||||
k: extractKeywords(`${title} ${description}`),
|
|
||||||
l: `/install#${title.toLowerCase().replace(/ /g, '-')}`
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// API
|
|
||||||
[
|
|
||||||
'constructor',
|
|
||||||
'input',
|
|
||||||
'output',
|
|
||||||
'resize',
|
|
||||||
'composite',
|
|
||||||
'operation',
|
|
||||||
'channel',
|
|
||||||
'colour',
|
|
||||||
'utility'
|
|
||||||
].forEach((section) => {
|
|
||||||
const contents = fs.readFileSync(path.join(__dirname, '..', `api-${section}.md`), 'utf8');
|
|
||||||
const matches = contents.matchAll(
|
|
||||||
/\n## (?<title>[A-Za-z]+)\n\n(?<firstparagraph>.+?)\n\n(?<parameters>### Parameters.+?Returns)?/gs
|
|
||||||
);
|
|
||||||
for (const match of matches) {
|
|
||||||
const { title, firstparagraph, parameters } = match.groups;
|
|
||||||
const description = firstparagraph.startsWith('###')
|
|
||||||
? 'Constructor'
|
|
||||||
: extractDescription(firstparagraph);
|
|
||||||
const parameterNames = parameters ? extractParameters(parameters) : '';
|
|
||||||
|
|
||||||
searchIndex.push({
|
|
||||||
t: title,
|
|
||||||
d: description,
|
|
||||||
k: extractKeywords(`${title} ${description} ${parameterNames}`),
|
|
||||||
l: `/api-${section}#${title.toLowerCase()}`
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
fs.writeFileSync(
|
|
||||||
path.join(__dirname, '..', 'search-index.json'),
|
|
||||||
JSON.stringify(searchIndex)
|
|
||||||
);
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
const stopWords = require('./stop-words');
|
|
||||||
|
|
||||||
const extractDescription = (str) =>
|
|
||||||
str
|
|
||||||
.replace(/### Examples.*/sg, '')
|
|
||||||
.replace(/\(http[^)]+/g, '')
|
|
||||||
.replace(/\s+/g, ' ')
|
|
||||||
.replace(/[^A-Za-z0-9_/\-,. ]/g, '')
|
|
||||||
.replace(/\s+/g, ' ')
|
|
||||||
.substring(0, 200)
|
|
||||||
.trim();
|
|
||||||
|
|
||||||
const extractParameters = (str) =>
|
|
||||||
[...str.matchAll(/options\.(?<name>[^.`]+)/gs)]
|
|
||||||
.map((match) => match.groups.name)
|
|
||||||
.join(' ');
|
|
||||||
|
|
||||||
const extractKeywords = (str) =>
|
|
||||||
[
|
|
||||||
...new Set(
|
|
||||||
str
|
|
||||||
.split(/[ -/]/)
|
|
||||||
.map((word) => word.toLowerCase().replace(/[^a-z]/g, ''))
|
|
||||||
.filter((word) => word.length > 2 && word.length < 15 && !stopWords.includes(word))
|
|
||||||
)
|
|
||||||
].join(' ');
|
|
||||||
|
|
||||||
module.exports = { extractDescription, extractKeywords, extractParameters };
|
|
||||||
@@ -1,120 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
module.exports = [
|
|
||||||
'about',
|
|
||||||
'after',
|
|
||||||
'all',
|
|
||||||
'allows',
|
|
||||||
'already',
|
|
||||||
'also',
|
|
||||||
'alternative',
|
|
||||||
'always',
|
|
||||||
'and',
|
|
||||||
'any',
|
|
||||||
'are',
|
|
||||||
'based',
|
|
||||||
'been',
|
|
||||||
'before',
|
|
||||||
'both',
|
|
||||||
'call',
|
|
||||||
'callback',
|
|
||||||
'can',
|
|
||||||
'containing',
|
|
||||||
'contains',
|
|
||||||
'created',
|
|
||||||
'current',
|
|
||||||
'date',
|
|
||||||
'default',
|
|
||||||
'does',
|
|
||||||
'each',
|
|
||||||
'either',
|
|
||||||
'ensure',
|
|
||||||
'entirely',
|
|
||||||
'etc',
|
|
||||||
'every',
|
|
||||||
'except',
|
|
||||||
'following',
|
|
||||||
'for',
|
|
||||||
'from',
|
|
||||||
'get',
|
|
||||||
'gets',
|
|
||||||
'given',
|
|
||||||
'has',
|
|
||||||
'have',
|
|
||||||
'how',
|
|
||||||
'image',
|
|
||||||
'implies',
|
|
||||||
'include',
|
|
||||||
'including',
|
|
||||||
'involve',
|
|
||||||
'its',
|
|
||||||
'last',
|
|
||||||
'least',
|
|
||||||
'lots',
|
|
||||||
'make',
|
|
||||||
'may',
|
|
||||||
'more',
|
|
||||||
'most',
|
|
||||||
'much',
|
|
||||||
'must',
|
|
||||||
'non',
|
|
||||||
'not',
|
|
||||||
'occur',
|
|
||||||
'occurs',
|
|
||||||
'options',
|
|
||||||
'other',
|
|
||||||
'out',
|
|
||||||
'over',
|
|
||||||
'perform',
|
|
||||||
'performs',
|
|
||||||
'produce',
|
|
||||||
'provide',
|
|
||||||
'provided',
|
|
||||||
'ready',
|
|
||||||
'requires',
|
|
||||||
'requiresharp',
|
|
||||||
'returned',
|
|
||||||
'same',
|
|
||||||
'see',
|
|
||||||
'set',
|
|
||||||
'sets',
|
|
||||||
'should',
|
|
||||||
'since',
|
|
||||||
'site',
|
|
||||||
'some',
|
|
||||||
'specified',
|
|
||||||
'spelling',
|
|
||||||
'such',
|
|
||||||
'support',
|
|
||||||
'supported',
|
|
||||||
'sure',
|
|
||||||
'take',
|
|
||||||
'task',
|
|
||||||
'than',
|
|
||||||
'that',
|
|
||||||
'the',
|
|
||||||
'their',
|
|
||||||
'then',
|
|
||||||
'there',
|
|
||||||
'therefore',
|
|
||||||
'these',
|
|
||||||
'this',
|
|
||||||
'under',
|
|
||||||
'unless',
|
|
||||||
'unmaintained',
|
|
||||||
'unsuitable',
|
|
||||||
'until',
|
|
||||||
'use',
|
|
||||||
'used',
|
|
||||||
'using',
|
|
||||||
'value',
|
|
||||||
'values',
|
|
||||||
'were',
|
|
||||||
'when',
|
|
||||||
'which',
|
|
||||||
'while',
|
|
||||||
'will',
|
|
||||||
'with',
|
|
||||||
'without',
|
|
||||||
'you'
|
|
||||||
];
|
|
||||||
5
docs/src/assets/sharp-logo.svg
Normal 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 |
7
docs/src/content.config.ts
Normal 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() }),
|
||||||
|
};
|
||||||
@@ -1,14 +1,18 @@
|
|||||||
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
|
---
|
||||||
|
# This file was auto-generated from JSDoc in lib/channel.js
|
||||||
|
title: Channel manipulation
|
||||||
|
---
|
||||||
|
|
||||||
## removeAlpha
|
## removeAlpha
|
||||||
|
> removeAlpha() ⇒ <code>Sharp</code>
|
||||||
|
|
||||||
Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel.
|
Remove alpha channels, if any. This is a no-op if the image does not have an alpha channel.
|
||||||
|
|
||||||
See also [flatten][1].
|
See also [flatten](/api-operation#flatten).
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```javascript
|
**Example**
|
||||||
|
```js
|
||||||
sharp('rgba.png')
|
sharp('rgba.png')
|
||||||
.removeAlpha()
|
.removeAlpha()
|
||||||
.toFile('rgb.png', function(err, info) {
|
.toFile('rgb.png', function(err, info) {
|
||||||
@@ -16,61 +20,66 @@ sharp('rgba.png')
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## ensureAlpha
|
## ensureAlpha
|
||||||
|
> ensureAlpha([alpha]) ⇒ <code>Sharp</code>
|
||||||
|
|
||||||
Ensure the output image has an alpha transparency channel.
|
Ensure the output image has an alpha transparency channel.
|
||||||
If missing, the added alpha channel will have the specified
|
If missing, the added alpha channel will have the specified
|
||||||
transparency level, defaulting to fully-opaque (1).
|
transparency level, defaulting to fully-opaque (1).
|
||||||
This is a no-op if the image already has an alpha channel.
|
This is a no-op if the image already has an alpha channel.
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `alpha` **[number][2]** alpha transparency level (0=fully-transparent, 1=fully-opaque) (optional, default `1`)
|
**Throws**:
|
||||||
|
|
||||||
### Examples
|
- <code>Error</code> Invalid alpha transparency level
|
||||||
|
|
||||||
```javascript
|
**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
|
// rgba.png will be a 4 channel image with a fully-opaque alpha channel
|
||||||
await sharp('rgb.jpg')
|
await sharp('rgb.jpg')
|
||||||
.ensureAlpha()
|
.ensureAlpha()
|
||||||
.toFile('rgba.png')
|
.toFile('rgba.png')
|
||||||
```
|
```
|
||||||
|
**Example**
|
||||||
```javascript
|
```js
|
||||||
// rgba is a 4 channel image with a fully-transparent alpha channel
|
// rgba is a 4 channel image with a fully-transparent alpha channel
|
||||||
const rgba = await sharp(rgb)
|
const rgba = await sharp(rgb)
|
||||||
.ensureAlpha(0)
|
.ensureAlpha(0)
|
||||||
.toBuffer();
|
.toBuffer();
|
||||||
```
|
```
|
||||||
|
|
||||||
* Throws **[Error][3]** Invalid alpha transparency level
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
**Meta**
|
|
||||||
|
|
||||||
* **since**: 0.21.2
|
|
||||||
|
|
||||||
## extractChannel
|
## extractChannel
|
||||||
|
> extractChannel(channel) ⇒ <code>Sharp</code>
|
||||||
|
|
||||||
Extract a single channel from a multi-channel image.
|
Extract a single channel from a multi-channel image.
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `channel` **([number][2] | [string][4])** zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`.
|
**Throws**:
|
||||||
|
|
||||||
### Examples
|
- <code>Error</code> Invalid channel
|
||||||
|
|
||||||
```javascript
|
|
||||||
|
| 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
|
// green.jpg is a greyscale image containing the green channel of the input
|
||||||
await sharp(input)
|
await sharp(input)
|
||||||
.extractChannel('green')
|
.extractChannel('green')
|
||||||
.toFile('green.jpg');
|
.toFile('green.jpg');
|
||||||
```
|
```
|
||||||
|
**Example**
|
||||||
```javascript
|
```js
|
||||||
// red1 is the red value of the first pixel, red2 the second pixel etc.
|
// red1 is the red value of the first pixel, red2 the second pixel etc.
|
||||||
const [red1, red2, ...] = await sharp(input)
|
const [red1, red2, ...] = await sharp(input)
|
||||||
.extractChannel(0)
|
.extractChannel(0)
|
||||||
@@ -78,45 +87,50 @@ const [red1, red2, ...] = await sharp(input)
|
|||||||
.toBuffer();
|
.toBuffer();
|
||||||
```
|
```
|
||||||
|
|
||||||
* Throws **[Error][3]** Invalid channel
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## joinChannel
|
## joinChannel
|
||||||
|
> joinChannel(images, options) ⇒ <code>Sharp</code>
|
||||||
|
|
||||||
Join one or more channels to the image.
|
Join one or more channels to the image.
|
||||||
The meaning of the added channels depends on the output colourspace, set with `toColourspace()`.
|
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.
|
By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.
|
||||||
Channel ordering follows vips convention:
|
Channel ordering follows vips convention:
|
||||||
|
- sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha.
|
||||||
* sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha.
|
- CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha.
|
||||||
* CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha.
|
|
||||||
|
|
||||||
Buffers may be any of the image formats supported by sharp.
|
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.
|
For raw pixel input, the `options` object should contain a `raw` attribute, which follows the format of the attribute of the same name in the `sharp()` constructor.
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `images` **([Array][5]<([string][4] | [Buffer][6])> | [string][4] | [Buffer][6])** one or more images (file paths, Buffers).
|
**Throws**:
|
||||||
* `options` **[Object][7]** image options, see `sharp()` constructor.
|
|
||||||
|
|
||||||
<!---->
|
- <code>Error</code> Invalid parameters
|
||||||
|
|
||||||
|
|
||||||
|
| Param | Type | Description |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| images | <code>Array.<(string\|Buffer)></code> \| <code>string</code> \| <code>Buffer</code> | one or more images (file paths, Buffers). |
|
||||||
|
| options | <code>Object</code> | image options, see `sharp()` constructor. |
|
||||||
|
|
||||||
* Throws **[Error][3]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
## bandbool
|
## bandbool
|
||||||
|
> bandbool(boolOp) ⇒ <code>Sharp</code>
|
||||||
|
|
||||||
Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image.
|
Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image.
|
||||||
|
|
||||||
### Parameters
|
|
||||||
|
|
||||||
* `boolOp` **[string][4]** one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.
|
**Throws**:
|
||||||
|
|
||||||
### Examples
|
- <code>Error</code> Invalid parameters
|
||||||
|
|
||||||
```javascript
|
|
||||||
|
| 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')
|
sharp('3-channel-rgb-input.png')
|
||||||
.bandbool(sharp.bool.and)
|
.bandbool(sharp.bool.and)
|
||||||
.toFile('1-channel-output.png', function (err, info) {
|
.toFile('1-channel-output.png', function (err, info) {
|
||||||
@@ -124,22 +138,4 @@ sharp('3-channel-rgb-input.png')
|
|||||||
// If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]`
|
// If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]`
|
||||||
// then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`.
|
// then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`.
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
* Throws **[Error][3]** Invalid parameters
|
|
||||||
|
|
||||||
Returns **Sharp** 
|
|
||||||
|
|
||||||
[1]: /api-operation#flatten
|
|
||||||
|
|
||||||
[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
|
|
||||||
|
|
||||||
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
|
|
||||||
|
|
||||||
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
|
|
||||||
|
|
||||||
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
|
|
||||||
|
|
||||||
[6]: https://nodejs.org/api/buffer.html
|
|
||||||
|
|
||||||
[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
|
|
||||||
150
docs/src/content/docs/api-colour.md
Normal 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. |
|
||||||
103
docs/src/content/docs/api-composite.md
Normal 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.<Object></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>"'left'"</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>'over'</code> | how to blend this image with the image below. |
|
||||||
|
| [images[].gravity] | <code>String</code> | <code>'centre'</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>"'warning'"</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!
|
||||||
|
});
|
||||||
|
```
|
||||||
274
docs/src/content/docs/api-constructor.md
Normal 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>"'warning'"</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>"'left'"</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>"'word'"</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>"'left'"</code> | horizontal alignment style for images joined horizontally (`'left'`, `'centre'`, `'center'`, `'right'`). |
|
||||||
|
| [options.join.valign] | <code>string</code> | <code>"'top'"</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) {}
|
||||||
|
});
|
||||||
|
```
|
||||||
139
docs/src/content/docs/api-input.md
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
---
|
||||||
|
# This file was auto-generated from JSDoc in lib/input.js
|
||||||
|
title: Input metadata
|
||||||
|
---
|
||||||
|
|
||||||
|
## metadata
|
||||||
|
> metadata([callback]) ⇒ <code>Promise.<Object></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
|
||||||
|
- `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.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
| 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.<Object></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();
|
||||||
|
```
|
||||||
723
docs/src/content/docs/api-operation.md
Normal 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>"\"#000000\""</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.<Array.<number>></code> \| <code>Array.<number></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>"#000000"</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>"'integer'"</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>"{r: 0, g: 0, b: 0}"</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.<number></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.<number></code> | <code>[]</code> | multiplier |
|
||||||
|
| [b] | <code>number</code> \| <code>Array.<number></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.<Array.<number>></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();
|
||||||
|
```
|
||||||
902
docs/src/content/docs/api-output.md
Normal 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.<Object></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.<Object></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.<Buffer></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.<Buffer></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.<string, Object.<string, string>></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.<string, Object.<string, string>></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>"'4:2:0'"</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>"'default'"</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.<number></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.<number></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>"'4:4:4'"</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>"'jpeg'"</code> | compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k |
|
||||||
|
| [options.predictor] | <code>string</code> | <code>"'horizontal'"</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>"'inch'"</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>"'4:4:4'"</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>"'4:4:4'"</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.<number></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>"'uchar'"</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>"{r: 255, g: 255, b: 255, alpha: 1}"</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>"'fs'"</code> | tile container, with value `fs` (filesystem) or `zip` (compressed file). |
|
||||||
|
| [options.layout] | <code>string</code> | <code>"'dz'"</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>"'https://example.com/iiif'"</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')) { ... }
|
||||||
|
}
|
||||||
|
```
|
||||||
323
docs/src/content/docs/api-resize.md
Normal 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>'cover'</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>'centre'</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>'lanczos3'</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>'background'</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>"'top-left pixel'"</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();
|
||||||
|
```
|
||||||
232
docs/src/content/docs/api-utility.md
Normal 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>"nearest"</code> | [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. |
|
||||||
|
| bilinear | <code>string</code> | <code>"bilinear"</code> | [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. |
|
||||||
|
| bicubic | <code>string</code> | <code>"bicubic"</code> | [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). |
|
||||||
|
| locallyBoundedBicubic | <code>string</code> | <code>"lbb"</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>"nohalo"</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>"vsqbs"</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.<string></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.<string></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']
|
||||||
|
});
|
||||||
|
```
|
||||||
@@ -1,8 +1,520 @@
|
|||||||
# Changelog
|
---
|
||||||
|
title: Changelog
|
||||||
|
---
|
||||||
|
|
||||||
|
## v0.34 - *hat*
|
||||||
|
|
||||||
|
Requires libvips v8.17.1
|
||||||
|
|
||||||
|
### v0.34.3 - 10th July 2025
|
||||||
|
|
||||||
|
* Upgrade to libvips v8.17.1 for upstream bug fixes.
|
||||||
|
|
||||||
|
* Add "Magic Kernel Sharp" (no relation) to resizing kernels.
|
||||||
|
|
||||||
|
* Deprecate top-level, format-specific constructor parameters, e.g. `subifd` becomes `tiff.subifd`.
|
||||||
|
|
||||||
|
* Expose `stylesheet` and `highBitdepth` SVG input parameters.
|
||||||
|
|
||||||
|
* Expose `keepDuplicateFrames` GIF output parameter.
|
||||||
|
|
||||||
|
* Add support for RAW digital camera image input. Requires libvips compiled with libraw support.
|
||||||
|
|
||||||
|
* Provide XMP metadata as a string, as well as a Buffer, where possible.
|
||||||
|
|
||||||
|
* Add `pageHeight` option to `create` and `raw` input for animated images.
|
||||||
|
[#3236](https://github.com/lovell/sharp/issues/3236)
|
||||||
|
|
||||||
|
* Expose JPEG 2000 `oneshot` decoder option.
|
||||||
|
[#4262](https://github.com/lovell/sharp/pull/4262)
|
||||||
|
[@mbklein](https://github.com/mbklein)
|
||||||
|
|
||||||
|
* Support composite operation with non-sRGB pipeline colourspace.
|
||||||
|
[#4412](https://github.com/lovell/sharp/pull/4412)
|
||||||
|
[@kleisauke](https://github.com/kleisauke)
|
||||||
|
|
||||||
|
* Add `keepXmp` and `withXmp` for control over output XMP metadata.
|
||||||
|
[#4416](https://github.com/lovell/sharp/pull/4416)
|
||||||
|
[@tpatel](https://github.com/tpatel)
|
||||||
|
|
||||||
|
### v0.34.2 - 20th May 2025
|
||||||
|
|
||||||
|
* Ensure animated GIF to WebP conversion retains loop (regression in 0.34.0).
|
||||||
|
[#3394](https://github.com/lovell/sharp/issues/3394)
|
||||||
|
|
||||||
|
* Ensure `pdfBackground` constructor property is used.
|
||||||
|
[#4207](https://github.com/lovell/sharp/pull/4207)
|
||||||
|
[#4398](https://github.com/lovell/sharp/issues/4398)
|
||||||
|
|
||||||
|
* Add experimental support for prebuilt Windows ARM64 binaries.
|
||||||
|
[#4375](https://github.com/lovell/sharp/pull/4375)
|
||||||
|
[@hans00](https://github.com/hans00)
|
||||||
|
|
||||||
|
* Ensure resizing with a `fit` of `contain` supports multiple alpha channels.
|
||||||
|
[#4382](https://github.com/lovell/sharp/issues/4382)
|
||||||
|
|
||||||
|
* TypeScript: Ensure `metadata` response more closely matches reality.
|
||||||
|
[#4383](https://github.com/lovell/sharp/issues/4383)
|
||||||
|
|
||||||
|
* TypeScript: Ensure `smartDeblock` property is included in WebP definition.
|
||||||
|
[#4387](https://github.com/lovell/sharp/pull/4387)
|
||||||
|
[@Stephen-X](https://github.com/Stephen-X)
|
||||||
|
|
||||||
|
* Ensure support for wide-character filenames on Windows (regression in 0.34.0).
|
||||||
|
[#4391](https://github.com/lovell/sharp/issues/4391)
|
||||||
|
|
||||||
|
### v0.34.1 - 7th April 2025
|
||||||
|
|
||||||
|
* TypeScript: Ensure new `autoOrient` property is optional.
|
||||||
|
[#4362](https://github.com/lovell/sharp/pull/4362)
|
||||||
|
[@styfle](https://github.com/styfle)
|
||||||
|
|
||||||
|
### v0.34.0 - 4th April 2025
|
||||||
|
|
||||||
|
* Breaking: Support array of input images to be joined or animated.
|
||||||
|
[#1580](https://github.com/lovell/sharp/issues/1580)
|
||||||
|
|
||||||
|
* Breaking: Ensure `removeAlpha` removes all alpha channels.
|
||||||
|
[#2266](https://github.com/lovell/sharp/issues/2266)
|
||||||
|
|
||||||
|
* Breaking: Non-animated GIF output defaults to no-loop instead of loop-forever.
|
||||||
|
[#3394](https://github.com/lovell/sharp/issues/3394)
|
||||||
|
|
||||||
|
* Breaking: Support `info.size` on wide-character systems via upgrade to C++17.
|
||||||
|
[#3943](https://github.com/lovell/sharp/issues/3943)
|
||||||
|
|
||||||
|
* Breaking: Ensure `background` metadata can be parsed by `color` package.
|
||||||
|
[#4090](https://github.com/lovell/sharp/issues/4090)
|
||||||
|
|
||||||
|
* Add `isPalette` and `bitsPerSample` to metadata, deprecate `paletteBitDepth`.
|
||||||
|
|
||||||
|
* Expose WebP `smartDeblock` output option.
|
||||||
|
|
||||||
|
* Prevent use of linux-x64 binaries with v1 microarchitecture.
|
||||||
|
|
||||||
|
* Add `autoOrient` operation and constructor option.
|
||||||
|
[#4151](https://github.com/lovell/sharp/pull/4151)
|
||||||
|
[@happycollision](https://github.com/happycollision)
|
||||||
|
|
||||||
|
* TypeScript: Ensure channel counts use the correct range.
|
||||||
|
[#4197](https://github.com/lovell/sharp/pull/4197)
|
||||||
|
[@DavidVaness](https://github.com/DavidVaness)
|
||||||
|
|
||||||
|
* Improve support for ppc64le architecture.
|
||||||
|
[#4203](https://github.com/lovell/sharp/pull/4203)
|
||||||
|
[@sumitd2](https://github.com/sumitd2)
|
||||||
|
|
||||||
|
* Add `pdfBackground` constructor property.
|
||||||
|
[#4207](https://github.com/lovell/sharp/pull/4207)
|
||||||
|
[@calebmer](https://github.com/calebmer)
|
||||||
|
|
||||||
|
* Expose erode and dilate operations.
|
||||||
|
[#4243](https://github.com/lovell/sharp/pull/4243)
|
||||||
|
[@qpincon](https://github.com/qpincon)
|
||||||
|
|
||||||
|
* Add support for RGBE images. Requires libvips compiled with radiance support.
|
||||||
|
[#4316](https://github.com/lovell/sharp/pull/4316)
|
||||||
|
[@florentzabera](https://github.com/florentzabera)
|
||||||
|
|
||||||
|
* Allow wide-gamut HEIF output at higher bitdepths.
|
||||||
|
[#4344](https://github.com/lovell/sharp/issues/4344)
|
||||||
|
|
||||||
|
## v0.33 - *gauge*
|
||||||
|
|
||||||
|
Requires libvips v8.15.3
|
||||||
|
|
||||||
|
### v0.33.5 - 16th August 2024
|
||||||
|
|
||||||
|
* Upgrade to libvips v8.15.3 for upstream bug fixes.
|
||||||
|
|
||||||
|
* Add `pageHeight` and `pages` to response of multi-page output.
|
||||||
|
[#3411](https://github.com/lovell/sharp/issues/3411)
|
||||||
|
|
||||||
|
* Ensure option to force use of a globally-installed libvips works correctly.
|
||||||
|
[#4111](https://github.com/lovell/sharp/pull/4111)
|
||||||
|
[@project0](https://github.com/project0)
|
||||||
|
|
||||||
|
* Minimise use of `engines` property to improve yarn v1 support.
|
||||||
|
[#4130](https://github.com/lovell/sharp/issues/4130)
|
||||||
|
|
||||||
|
* Ensure `sharp.format.heif` includes only AVIF when using prebuilt binaries.
|
||||||
|
[#4132](https://github.com/lovell/sharp/issues/4132)
|
||||||
|
|
||||||
|
* Add support to recomb operation for 4x4 matrices.
|
||||||
|
[#4147](https://github.com/lovell/sharp/pull/4147)
|
||||||
|
[@ton11797](https://github.com/ton11797)
|
||||||
|
|
||||||
|
* Expose PNG text chunks as `comments` metadata.
|
||||||
|
[#4157](https://github.com/lovell/sharp/pull/4157)
|
||||||
|
[@nkeynes](https://github.com/nkeynes)
|
||||||
|
|
||||||
|
* Expose optional `precision` and `minAmplitude` parameters of `blur` operation.
|
||||||
|
[#4168](https://github.com/lovell/sharp/pull/4168)
|
||||||
|
[#4172](https://github.com/lovell/sharp/pull/4172)
|
||||||
|
[@marcosc90](https://github.com/marcosc90)
|
||||||
|
|
||||||
|
* Ensure `keepIccProfile` avoids colour transformation where possible.
|
||||||
|
[#4186](https://github.com/lovell/sharp/issues/4186)
|
||||||
|
|
||||||
|
* TypeScript: `chromaSubsampling` metadata is optional.
|
||||||
|
[#4191](https://github.com/lovell/sharp/pull/4191)
|
||||||
|
[@DavidVaness](https://github.com/DavidVaness)
|
||||||
|
|
||||||
|
### v0.33.4 - 16th May 2024
|
||||||
|
|
||||||
|
* Remove experimental status from `pipelineColourspace`.
|
||||||
|
|
||||||
|
* Reduce default concurrency when musl thread over-subscription detected.
|
||||||
|
|
||||||
|
* TypeScript: add missing definitions for `OverlayOptions`.
|
||||||
|
[#4048](https://github.com/lovell/sharp/pull/4048)
|
||||||
|
[@ike-gg](https://github.com/ike-gg)
|
||||||
|
|
||||||
|
* Install: add advanced option to force use of a globally-installed libvips.
|
||||||
|
[#4060](https://github.com/lovell/sharp/issues/4060)
|
||||||
|
|
||||||
|
* Expose `bilinear` resizing kernel (and interpolator).
|
||||||
|
[#4061](https://github.com/lovell/sharp/issues/4061)
|
||||||
|
|
||||||
|
* Ensure `extend` operation stays sequential for multi-page TIFF (regression in 0.32.0).
|
||||||
|
[#4069](https://github.com/lovell/sharp/issues/4069)
|
||||||
|
|
||||||
|
* Tighten validation of constructor `text` integer properties.
|
||||||
|
[#4071](https://github.com/lovell/sharp/issues/4071)
|
||||||
|
|
||||||
|
* Simplify internal StaySequential logic.
|
||||||
|
[#4074](https://github.com/lovell/sharp/pull/4074)
|
||||||
|
[@kleisauke](https://github.com/kleisauke)
|
||||||
|
|
||||||
|
* Ensure negate operation occurs after profile conversion.
|
||||||
|
[#4096](https://github.com/lovell/sharp/pull/4096)
|
||||||
|
[@adriaanmeuris](https://github.com/adriaanmeuris)
|
||||||
|
|
||||||
|
### v0.33.3 - 23rd March 2024
|
||||||
|
|
||||||
|
* Upgrade to libvips v8.15.2 for upstream bug fixes.
|
||||||
|
|
||||||
|
* Ensure `keepIccProfile` retains P3 and CMYK input profiles.
|
||||||
|
[#3906](https://github.com/lovell/sharp/issues/3906)
|
||||||
|
[#4008](https://github.com/lovell/sharp/issues/4008)
|
||||||
|
|
||||||
|
* Ensure `text.wrap` property can accept `word-char` as value.
|
||||||
|
[#4028](https://github.com/lovell/sharp/pull/4028)
|
||||||
|
[@yolopunk](https://github.com/yolopunk)
|
||||||
|
|
||||||
|
* Ensure `clone` takes a deep copy of existing options.
|
||||||
|
[#4029](https://github.com/lovell/sharp/issues/4029)
|
||||||
|
|
||||||
|
* Add `bitdepth` option to `heif` output (prebuilt binaries support 8-bit only).
|
||||||
|
[#4036](https://github.com/lovell/sharp/pull/4036)
|
||||||
|
[@mertalev](https://github.com/mertalev)
|
||||||
|
|
||||||
|
### v0.33.2 - 12th January 2024
|
||||||
|
|
||||||
|
* Upgrade to libvips v8.15.1 for upstream bug fixes.
|
||||||
|
|
||||||
|
* TypeScript: add definition for `keepMetadata`.
|
||||||
|
[#3914](https://github.com/lovell/sharp/pull/3914)
|
||||||
|
[@abhi0498](https://github.com/abhi0498)
|
||||||
|
|
||||||
|
* Ensure `extend` operation stays sequential when copying (regression in 0.32.0).
|
||||||
|
[#3928](https://github.com/lovell/sharp/issues/3928)
|
||||||
|
|
||||||
|
* Improve error handling for unsupported multi-page rotation.
|
||||||
|
[#3940](https://github.com/lovell/sharp/issues/3940)
|
||||||
|
|
||||||
|
### v0.33.1 - 17th December 2023
|
||||||
|
|
||||||
|
* Add support for Yarn Plug'n'Play filesystem layout.
|
||||||
|
[#3888](https://github.com/lovell/sharp/issues/3888)
|
||||||
|
|
||||||
|
* Emit warning when attempting to use invalid ICC profiles.
|
||||||
|
[#3895](https://github.com/lovell/sharp/issues/3895)
|
||||||
|
|
||||||
|
* Ensure `VIPS_NOVECTOR` environment variable is respected.
|
||||||
|
[#3897](https://github.com/lovell/sharp/pull/3897)
|
||||||
|
[@icetee](https://github.com/icetee)
|
||||||
|
|
||||||
|
### v0.33.0 - 29th November 2023
|
||||||
|
|
||||||
|
* Drop support for Node.js 14 and 16, now requires Node.js ^18.17.0 or >= 20.3.0
|
||||||
|
|
||||||
|
* Prebuilt binaries distributed via npm registry and installed via package manager.
|
||||||
|
|
||||||
|
* Building from source requires dependency on `node-addon-api`.
|
||||||
|
|
||||||
|
* Remove `sharp.vendor`.
|
||||||
|
|
||||||
|
* Partially deprecate `withMetadata()`, use `withExif()` and `withIccProfile()`.
|
||||||
|
|
||||||
|
* Add experimental support for WebAssembly-based runtimes.
|
||||||
|
[@RReverser](https://github.com/RReverser)
|
||||||
|
|
||||||
|
* Options for `trim` operation must be an Object, add new `lineArt` option.
|
||||||
|
[#2363](https://github.com/lovell/sharp/issues/2363)
|
||||||
|
|
||||||
|
* Improve luminance of `tint` operation with weighting function.
|
||||||
|
[#3338](https://github.com/lovell/sharp/issues/3338)
|
||||||
|
[@jcupitt](https://github.com/jcupitt)
|
||||||
|
|
||||||
|
* Ensure all `Error` objects contain a `stack` property.
|
||||||
|
[#3653](https://github.com/lovell/sharp/issues/3653)
|
||||||
|
|
||||||
|
* Make `compression` option of `heif` mandatory to help reduce HEIF vs HEIC confusion.
|
||||||
|
[#3740](https://github.com/lovell/sharp/issues/3740)
|
||||||
|
|
||||||
|
* Ensure correct interpretation of 16-bit raw input.
|
||||||
|
[#3808](https://github.com/lovell/sharp/issues/3808)
|
||||||
|
|
||||||
|
* Add support for `miniswhite` when using TIFF output.
|
||||||
|
[#3812](https://github.com/lovell/sharp/pull/3812)
|
||||||
|
[@dnsbty](https://github.com/dnsbty)
|
||||||
|
|
||||||
|
* TypeScript: add missing definition for `withMetadata` boolean.
|
||||||
|
[#3823](https://github.com/lovell/sharp/pull/3823)
|
||||||
|
[@uhthomas](https://github.com/uhthomas)
|
||||||
|
|
||||||
|
* Add more fine-grained control over output metadata.
|
||||||
|
[#3824](https://github.com/lovell/sharp/issues/3824)
|
||||||
|
|
||||||
|
* Ensure multi-page extract remains sequential.
|
||||||
|
[#3837](https://github.com/lovell/sharp/issues/3837)
|
||||||
|
|
||||||
|
## v0.32 - *flow*
|
||||||
|
|
||||||
|
Requires libvips v8.14.5
|
||||||
|
|
||||||
|
### v0.32.6 - 18th September 2023
|
||||||
|
|
||||||
|
* Upgrade to libvips v8.14.5 for upstream bug fixes.
|
||||||
|
|
||||||
|
* Ensure composite tile images are fully decoded (regression in 0.32.0).
|
||||||
|
[#3767](https://github.com/lovell/sharp/issues/3767)
|
||||||
|
|
||||||
|
* Ensure `withMetadata` can add ICC profiles to RGB16 output.
|
||||||
|
[#3773](https://github.com/lovell/sharp/issues/3773)
|
||||||
|
|
||||||
|
* Ensure `withMetadata` does not reduce 16-bit images to 8-bit (regression in 0.32.5).
|
||||||
|
[#3773](https://github.com/lovell/sharp/issues/3773)
|
||||||
|
|
||||||
|
* TypeScript: Add definitions for block and unblock.
|
||||||
|
[#3799](https://github.com/lovell/sharp/pull/3799)
|
||||||
|
[@ldrick](https://github.com/ldrick)
|
||||||
|
|
||||||
|
### v0.32.5 - 15th August 2023
|
||||||
|
|
||||||
|
* Upgrade to libvips v8.14.4 for upstream bug fixes.
|
||||||
|
|
||||||
|
* TypeScript: Add missing `WebpPresetEnum` to definitions.
|
||||||
|
[#3748](https://github.com/lovell/sharp/pull/3748)
|
||||||
|
[@pilotso11](https://github.com/pilotso11)
|
||||||
|
|
||||||
|
* Ensure compilation using musl v1.2.4.
|
||||||
|
[#3755](https://github.com/lovell/sharp/pull/3755)
|
||||||
|
[@kleisauke](https://github.com/kleisauke)
|
||||||
|
|
||||||
|
* Ensure resize with a `fit` of `inside` respects 90/270 degree rotation.
|
||||||
|
[#3756](https://github.com/lovell/sharp/issues/3756)
|
||||||
|
|
||||||
|
* TypeScript: Ensure `minSize` property of `WebpOptions` is boolean.
|
||||||
|
[#3758](https://github.com/lovell/sharp/pull/3758)
|
||||||
|
[@sho-xizz](https://github.com/sho-xizz)
|
||||||
|
|
||||||
|
* Ensure `withMetadata` adds default sRGB profile.
|
||||||
|
[#3761](https://github.com/lovell/sharp/issues/3761)
|
||||||
|
|
||||||
|
### v0.32.4 - 21st July 2023
|
||||||
|
|
||||||
|
* Upgrade to libvips v8.14.3 for upstream bug fixes.
|
||||||
|
|
||||||
|
* Expose ability to (un)block low-level libvips operations by name.
|
||||||
|
|
||||||
|
* Prebuilt binaries: restore support for tile-based output.
|
||||||
|
[#3581](https://github.com/lovell/sharp/issues/3581)
|
||||||
|
|
||||||
|
### v0.32.3 - 14th July 2023
|
||||||
|
|
||||||
|
* Expose `preset` option for WebP output.
|
||||||
|
[#3639](https://github.com/lovell/sharp/issues/3639)
|
||||||
|
|
||||||
|
* Ensure decoding remains sequential for all operations (regression in 0.32.2).
|
||||||
|
[#3725](https://github.com/lovell/sharp/issues/3725)
|
||||||
|
|
||||||
|
### v0.32.2 - 11th July 2023
|
||||||
|
|
||||||
|
* Limit HEIF output dimensions to 16384x16384, matches libvips.
|
||||||
|
|
||||||
|
* Ensure exceptions are not thrown when terminating.
|
||||||
|
[#3569](https://github.com/lovell/sharp/issues/3569)
|
||||||
|
|
||||||
|
* Ensure the same access method is used for all inputs (regression in 0.32.0).
|
||||||
|
[#3669](https://github.com/lovell/sharp/issues/3669)
|
||||||
|
|
||||||
|
* Improve detection of jp2 filename extensions.
|
||||||
|
[#3674](https://github.com/lovell/sharp/pull/3674)
|
||||||
|
[@bianjunjie1981](https://github.com/bianjunjie1981)
|
||||||
|
|
||||||
|
* Guard use of smartcrop premultiplied option to prevent warning (regression in 0.32.1).
|
||||||
|
[#3710](https://github.com/lovell/sharp/issues/3710)
|
||||||
|
|
||||||
|
* Prevent over-compute in affine-based rotate before resize.
|
||||||
|
[#3722](https://github.com/lovell/sharp/issues/3722)
|
||||||
|
|
||||||
|
* Allow sequential read for EXIF-based auto-orientation.
|
||||||
|
[#3725](https://github.com/lovell/sharp/issues/3725)
|
||||||
|
|
||||||
|
### v0.32.1 - 27th April 2023
|
||||||
|
|
||||||
|
* Add experimental `unflatten` operation.
|
||||||
|
[#3461](https://github.com/lovell/sharp/pull/3461)
|
||||||
|
[@antonmarsden](https://github.com/antonmarsden)
|
||||||
|
|
||||||
|
* Ensure use of `flip` operation forces random access read (regression in 0.32.0).
|
||||||
|
[#3600](https://github.com/lovell/sharp/issues/3600)
|
||||||
|
|
||||||
|
* Ensure `linear` operation works with 16-bit input (regression in 0.31.3).
|
||||||
|
[#3605](https://github.com/lovell/sharp/issues/3605)
|
||||||
|
|
||||||
|
* Install: ensure proxy URLs are logged correctly.
|
||||||
|
[#3615](https://github.com/lovell/sharp/pull/3615)
|
||||||
|
[@TomWis97](https://github.com/TomWis97)
|
||||||
|
|
||||||
|
* Ensure profile-less CMYK to CMYK roundtrip skips colourspace conversion.
|
||||||
|
[#3620](https://github.com/lovell/sharp/issues/3620)
|
||||||
|
|
||||||
|
* Add support for `modulate` operation when using non-sRGB pipeline colourspace.
|
||||||
|
[#3620](https://github.com/lovell/sharp/issues/3620)
|
||||||
|
|
||||||
|
* Ensure `trim` operation works with CMYK images (regression in 0.31.0).
|
||||||
|
[#3636](https://github.com/lovell/sharp/issues/3636)
|
||||||
|
|
||||||
|
* Install: coerce libc version to semver.
|
||||||
|
[#3641](https://github.com/lovell/sharp/issues/3641)
|
||||||
|
|
||||||
|
### v0.32.0 - 24th March 2023
|
||||||
|
|
||||||
|
* Default to using sequential rather than random access read where possible.
|
||||||
|
|
||||||
|
* Replace GIF output `optimise` / `optimize` option with `reuse`.
|
||||||
|
|
||||||
|
* Add `progressive` option to GIF output for interlacing.
|
||||||
|
|
||||||
|
* Add `wrap` option to text image creation.
|
||||||
|
|
||||||
|
* Add `formatMagick` property to metadata of images loaded via *magick.
|
||||||
|
|
||||||
|
* Prefer integer (un)premultiply for faster resizing of RGBA images.
|
||||||
|
|
||||||
|
* Add `ignoreIcc` input option to ignore embedded ICC profile.
|
||||||
|
|
||||||
|
* Allow use of GPS (IFD3) EXIF metadata.
|
||||||
|
[#2767](https://github.com/lovell/sharp/issues/2767)
|
||||||
|
|
||||||
|
* TypeScript definitions are now maintained and published directly, deprecating the `@types/sharp` package.
|
||||||
|
[#3369](https://github.com/lovell/sharp/issues/3369)
|
||||||
|
|
||||||
|
* Prebuilt binaries: ensure macOS 10.13+ support, as documented.
|
||||||
|
[#3438](https://github.com/lovell/sharp/issues/3438)
|
||||||
|
|
||||||
|
* Prebuilt binaries: prevent use of glib slice allocator, improves QEMU support.
|
||||||
|
[#3448](https://github.com/lovell/sharp/issues/3448)
|
||||||
|
|
||||||
|
* Add focus point coordinates to output when using attention based crop.
|
||||||
|
[#3470](https://github.com/lovell/sharp/pull/3470)
|
||||||
|
[@ejoebstl](https://github.com/ejoebstl)
|
||||||
|
|
||||||
|
* Expose sharp version as `sharp.versions.sharp`.
|
||||||
|
[#3471](https://github.com/lovell/sharp/issues/3471)
|
||||||
|
|
||||||
|
* Respect `fastShrinkOnLoad` resize option for WebP input.
|
||||||
|
[#3516](https://github.com/lovell/sharp/issues/3516)
|
||||||
|
|
||||||
|
* Reduce sharpen `sigma` maximum from 10000 to 10.
|
||||||
|
[#3521](https://github.com/lovell/sharp/issues/3521)
|
||||||
|
|
||||||
|
* Add support for `ArrayBuffer` input.
|
||||||
|
[#3548](https://github.com/lovell/sharp/pull/3548)
|
||||||
|
[@kapouer](https://github.com/kapouer)
|
||||||
|
|
||||||
|
* Add support to `extend` operation for `extendWith` to allow copy/mirror/repeat.
|
||||||
|
[#3556](https://github.com/lovell/sharp/pull/3556)
|
||||||
|
[@janaz](https://github.com/janaz)
|
||||||
|
|
||||||
|
* Ensure all async JS callbacks are wrapped to help avoid possible race condition.
|
||||||
|
[#3569](https://github.com/lovell/sharp/issues/3569)
|
||||||
|
|
||||||
|
* Prebuilt binaries: support for tile-based output temporarily removed due to licensing issue.
|
||||||
|
[#3581](https://github.com/lovell/sharp/issues/3581)
|
||||||
|
|
||||||
|
* Add support to `normalise` for `lower` and `upper` percentiles.
|
||||||
|
[#3583](https://github.com/lovell/sharp/pull/3583)
|
||||||
|
[@LachlanNewman](https://github.com/LachlanNewman)
|
||||||
|
|
||||||
## v0.31 - *eagle*
|
## v0.31 - *eagle*
|
||||||
|
|
||||||
Requires libvips v8.13.1
|
Requires libvips v8.13.3
|
||||||
|
|
||||||
|
### v0.31.3 - 21st December 2022
|
||||||
|
|
||||||
|
* Add experimental support for JPEG-XL images. Requires libvips compiled with libjxl.
|
||||||
|
[#2731](https://github.com/lovell/sharp/issues/2731)
|
||||||
|
|
||||||
|
* Add runtime detection of V8 memory cage, ensures compatibility with Electron 21 onwards.
|
||||||
|
[#3384](https://github.com/lovell/sharp/issues/3384)
|
||||||
|
|
||||||
|
* Expose `interFrameMaxError` and `interPaletteMaxError` GIF optimisation properties.
|
||||||
|
[#3401](https://github.com/lovell/sharp/issues/3401)
|
||||||
|
|
||||||
|
* Allow installation on Linux with glibc patch versions e.g. Fedora 38.
|
||||||
|
[#3423](https://github.com/lovell/sharp/issues/3423)
|
||||||
|
|
||||||
|
* Expand range of existing `sharpen` parameters to match libvips.
|
||||||
|
[#3427](https://github.com/lovell/sharp/issues/3427)
|
||||||
|
|
||||||
|
* Prevent possible race condition awaiting metadata of Stream-based input.
|
||||||
|
[#3451](https://github.com/lovell/sharp/issues/3451)
|
||||||
|
|
||||||
|
* Improve `extractChannel` support for 16-bit output colourspaces.
|
||||||
|
[#3453](https://github.com/lovell/sharp/issues/3453)
|
||||||
|
|
||||||
|
* Ignore `sequentialRead` option when calculating image statistics.
|
||||||
|
[#3462](https://github.com/lovell/sharp/issues/3462)
|
||||||
|
|
||||||
|
* Small performance improvement for operations that introduce a non-opaque background.
|
||||||
|
[#3465](https://github.com/lovell/sharp/issues/3465)
|
||||||
|
|
||||||
|
* Ensure integral output of `linear` operation.
|
||||||
|
[#3468](https://github.com/lovell/sharp/issues/3468)
|
||||||
|
|
||||||
|
### v0.31.2 - 4th November 2022
|
||||||
|
|
||||||
|
* Upgrade to libvips v8.13.3 for upstream bug fixes.
|
||||||
|
|
||||||
|
* Ensure manual flip, rotate, resize operation ordering (regression in 0.31.1)
|
||||||
|
[#3391](https://github.com/lovell/sharp/issues/3391)
|
||||||
|
|
||||||
|
* Ensure auto-rotation works without resize (regression in 0.31.1)
|
||||||
|
[#3422](https://github.com/lovell/sharp/issues/3422)
|
||||||
|
|
||||||
|
### v0.31.1 - 29th September 2022
|
||||||
|
|
||||||
|
* Upgrade to libvips v8.13.2 for upstream bug fixes.
|
||||||
|
|
||||||
|
* Ensure `close` event occurs after `end` event for Stream-based output.
|
||||||
|
[#3313](https://github.com/lovell/sharp/issues/3313)
|
||||||
|
|
||||||
|
* Ensure `limitInputPixels` constructor option uses uint64.
|
||||||
|
[#3349](https://github.com/lovell/sharp/pull/3349)
|
||||||
|
[@marcosc90](https://github.com/marcosc90)
|
||||||
|
|
||||||
|
* Ensure auto-rotation works with shrink-on-load and extract (regression in 0.31.0).
|
||||||
|
[#3352](https://github.com/lovell/sharp/issues/3352)
|
||||||
|
|
||||||
|
* Ensure AVIF output is always 8-bit.
|
||||||
|
[#3358](https://github.com/lovell/sharp/issues/3358)
|
||||||
|
|
||||||
|
* Ensure greyscale images can be trimmed (regression in 0.31.0).
|
||||||
|
[#3386](https://github.com/lovell/sharp/issues/3386)
|
||||||
|
|
||||||
### v0.31.0 - 5th September 2022
|
### v0.31.0 - 5th September 2022
|
||||||
|
|
||||||
@@ -1,11 +1,17 @@
|
|||||||
# sharp
|
---
|
||||||
|
title: "High performance Node.js image processing"
|
||||||
|
---
|
||||||
|
|
||||||
<img src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right">
|
<img src="/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right">
|
||||||
|
|
||||||
The typical use case for this high speed Node.js module
|
The typical use case for this high speed Node-API module
|
||||||
is to convert large images in common formats to
|
is to convert large images in common formats to
|
||||||
smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions.
|
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
|
Resizing an image is typically 4x-5x faster than using the
|
||||||
quickest ImageMagick and GraphicsMagick settings
|
quickest ImageMagick and GraphicsMagick settings
|
||||||
due to its use of [libvips](https://github.com/libvips/libvips).
|
due to its use of [libvips](https://github.com/libvips/libvips).
|
||||||
@@ -16,10 +22,14 @@ Lanczos resampling ensures quality is not sacrificed for speed.
|
|||||||
As well as image resizing, operations such as
|
As well as image resizing, operations such as
|
||||||
rotation, extraction, compositing and gamma correction are available.
|
rotation, extraction, compositing and gamma correction are available.
|
||||||
|
|
||||||
Most modern macOS, Windows and Linux systems running Node.js >= 14.15.0
|
Most modern macOS, Windows and Linux systems
|
||||||
do not require any additional install or runtime dependencies.
|
do not require any additional install or runtime dependencies.
|
||||||
|
|
||||||
### Formats
|
```sh
|
||||||
|
npm install sharp
|
||||||
|
```
|
||||||
|
|
||||||
|
## Formats
|
||||||
|
|
||||||
This module supports reading JPEG, PNG, WebP, GIF, AVIF, TIFF and SVG images.
|
This module supports reading JPEG, PNG, WebP, GIF, AVIF, TIFF and SVG images.
|
||||||
|
|
||||||
@@ -33,7 +43,7 @@ Deep Zoom image pyramids can be generated,
|
|||||||
suitable for use with "slippy map" tile viewers like
|
suitable for use with "slippy map" tile viewers like
|
||||||
[OpenSeadragon](https://github.com/openseadragon/openseadragon).
|
[OpenSeadragon](https://github.com/openseadragon/openseadragon).
|
||||||
|
|
||||||
### Fast
|
## Fast
|
||||||
|
|
||||||
This module is powered by the blazingly fast
|
This module is powered by the blazingly fast
|
||||||
[libvips](https://github.com/libvips/libvips) image processing library,
|
[libvips](https://github.com/libvips/libvips) image processing library,
|
||||||
@@ -48,7 +58,7 @@ taking full advantage of multiple CPU cores and L1/L2/L3 cache.
|
|||||||
Everything remains non-blocking thanks to _libuv_,
|
Everything remains non-blocking thanks to _libuv_,
|
||||||
no child processes are spawned and Promises/async/await are supported.
|
no child processes are spawned and Promises/async/await are supported.
|
||||||
|
|
||||||
### Optimal
|
## Optimal
|
||||||
|
|
||||||
The features of `mozjpeg` and `pngquant` can be used
|
The features of `mozjpeg` and `pngquant` can be used
|
||||||
to optimise the file size of JPEG and PNG images respectively,
|
to optimise the file size of JPEG and PNG images respectively,
|
||||||
@@ -67,14 +77,14 @@ The file size of animated GIF output is optimised
|
|||||||
without having to use separate command line tools such as
|
without having to use separate command line tools such as
|
||||||
[gifsicle](https://www.lcdf.org/gifsicle/).
|
[gifsicle](https://www.lcdf.org/gifsicle/).
|
||||||
|
|
||||||
### Contributing
|
## Contributing
|
||||||
|
|
||||||
A [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md)
|
A [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md)
|
||||||
covers reporting bugs, requesting features and submitting code changes.
|
covers reporting bugs, requesting features and submitting code changes.
|
||||||
|
|
||||||
### Licensing
|
## Licensing
|
||||||
|
|
||||||
Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Lovell Fuller and contributors.
|
Copyright 2013 Lovell Fuller and others.
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
357
docs/src/content/docs/install.md
Normal 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.
|
||||||
|
```
|
||||||
137
docs/src/content/docs/performance.md
Normal 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
|
||||||
|
```
|
||||||
45
docs/src/styles/custom.css
Normal 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
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"extends": "astro/tsconfigs/strict",
|
||||||
|
"include": [".astro/types.d.ts", "**/*"],
|
||||||
|
"exclude": ["dist"]
|
||||||
|
}
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
const libvips = require('../lib/libvips');
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (!(libvips.useGlobalLibvips() || libvips.hasVendoredLibvips())) {
|
|
||||||
process.exitCode = 1;
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
process.exitCode = 1;
|
|
||||||
}
|
|
||||||
41
install/check.js
Normal 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}`);
|
||||||
|
}
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
|
|
||||||
const libvips = require('../lib/libvips');
|
|
||||||
const platform = require('../lib/platform');
|
|
||||||
|
|
||||||
const minimumLibvipsVersion = libvips.minimumLibvipsVersion;
|
|
||||||
|
|
||||||
const platformAndArch = platform();
|
|
||||||
|
|
||||||
if (platformAndArch.startsWith('win32')) {
|
|
||||||
const buildReleaseDir = path.join(__dirname, '..', 'build', 'Release');
|
|
||||||
libvips.log(`Creating ${buildReleaseDir}`);
|
|
||||||
try {
|
|
||||||
libvips.mkdirSync(buildReleaseDir);
|
|
||||||
} catch (err) {}
|
|
||||||
const vendorLibDir = path.join(__dirname, '..', 'vendor', minimumLibvipsVersion, platformAndArch, 'lib');
|
|
||||||
libvips.log(`Copying DLLs from ${vendorLibDir} to ${buildReleaseDir}`);
|
|
||||||
try {
|
|
||||||
fs
|
|
||||||
.readdirSync(vendorLibDir)
|
|
||||||
.filter(function (filename) {
|
|
||||||
return /\.dll$/.test(filename);
|
|
||||||
})
|
|
||||||
.forEach(function (filename) {
|
|
||||||
fs.copyFileSync(
|
|
||||||
path.join(vendorLibDir, filename),
|
|
||||||
path.join(buildReleaseDir, filename)
|
|
||||||
);
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
libvips.log(err);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,215 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
const fs = require('fs');
|
|
||||||
const os = require('os');
|
|
||||||
const path = require('path');
|
|
||||||
const stream = require('stream');
|
|
||||||
const zlib = require('zlib');
|
|
||||||
const { createHash } = require('crypto');
|
|
||||||
|
|
||||||
const detectLibc = require('detect-libc');
|
|
||||||
const semverLessThan = require('semver/functions/lt');
|
|
||||||
const semverSatisfies = require('semver/functions/satisfies');
|
|
||||||
const simpleGet = require('simple-get');
|
|
||||||
const tarFs = require('tar-fs');
|
|
||||||
|
|
||||||
const agent = require('../lib/agent');
|
|
||||||
const libvips = require('../lib/libvips');
|
|
||||||
const platform = require('../lib/platform');
|
|
||||||
|
|
||||||
const minimumGlibcVersionByArch = {
|
|
||||||
arm: '2.28',
|
|
||||||
arm64: '2.17',
|
|
||||||
x64: '2.17'
|
|
||||||
};
|
|
||||||
|
|
||||||
const hasSharpPrebuild = [
|
|
||||||
'darwin-x64',
|
|
||||||
'darwin-arm64',
|
|
||||||
'linux-arm64',
|
|
||||||
'linux-x64',
|
|
||||||
'linuxmusl-x64',
|
|
||||||
'linuxmusl-arm64',
|
|
||||||
'win32-ia32',
|
|
||||||
'win32-x64'
|
|
||||||
];
|
|
||||||
|
|
||||||
const { minimumLibvipsVersion, minimumLibvipsVersionLabelled } = libvips;
|
|
||||||
const localLibvipsDir = process.env.npm_config_sharp_libvips_local_prebuilds || '';
|
|
||||||
const distHost = process.env.npm_config_sharp_libvips_binary_host || 'https://github.com/lovell/sharp-libvips/releases/download';
|
|
||||||
const distBaseUrl = process.env.npm_config_sharp_dist_base_url || process.env.SHARP_DIST_BASE_URL || `${distHost}/v${minimumLibvipsVersionLabelled}/`;
|
|
||||||
const installationForced = !!(process.env.npm_config_sharp_install_force || process.env.SHARP_INSTALL_FORCE);
|
|
||||||
|
|
||||||
const fail = function (err) {
|
|
||||||
libvips.log(err);
|
|
||||||
if (err.code === 'EACCES') {
|
|
||||||
libvips.log('Are you trying to install as a root or sudo user?');
|
|
||||||
libvips.log('- For npm <= v6, try again with the "--unsafe-perm" flag');
|
|
||||||
libvips.log('- For npm >= v8, the user must own the directory "npm install" is run in');
|
|
||||||
}
|
|
||||||
libvips.log('Please see https://sharp.pixelplumbing.com/install for required dependencies');
|
|
||||||
process.exit(1);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleError = function (err) {
|
|
||||||
if (installationForced) {
|
|
||||||
libvips.log(`Installation warning: ${err.message}`);
|
|
||||||
} else {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const verifyIntegrity = function (platformAndArch) {
|
|
||||||
const expected = libvips.integrity(platformAndArch);
|
|
||||||
if (installationForced || !expected) {
|
|
||||||
libvips.log(`Integrity check skipped for ${platformAndArch}`);
|
|
||||||
return new stream.PassThrough();
|
|
||||||
}
|
|
||||||
const hash = createHash('sha512');
|
|
||||||
return new stream.Transform({
|
|
||||||
transform: function (chunk, _encoding, done) {
|
|
||||||
hash.update(chunk);
|
|
||||||
done(null, chunk);
|
|
||||||
},
|
|
||||||
flush: function (done) {
|
|
||||||
const digest = `sha512-${hash.digest('base64')}`;
|
|
||||||
if (expected !== digest) {
|
|
||||||
libvips.removeVendoredLibvips();
|
|
||||||
libvips.log(`Integrity expected: ${expected}`);
|
|
||||||
libvips.log(`Integrity received: ${digest}`);
|
|
||||||
done(new Error(`Integrity check failed for ${platformAndArch}`));
|
|
||||||
} else {
|
|
||||||
libvips.log(`Integrity check passed for ${platformAndArch}`);
|
|
||||||
done();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const extractTarball = function (tarPath, platformAndArch) {
|
|
||||||
const versionedVendorPath = path.join(__dirname, '..', 'vendor', minimumLibvipsVersion, platformAndArch);
|
|
||||||
libvips.mkdirSync(versionedVendorPath);
|
|
||||||
|
|
||||||
const ignoreVendorInclude = hasSharpPrebuild.includes(platformAndArch) && !process.env.npm_config_build_from_source;
|
|
||||||
const ignore = function (name) {
|
|
||||||
return ignoreVendorInclude && name.includes('include/');
|
|
||||||
};
|
|
||||||
|
|
||||||
stream.pipeline(
|
|
||||||
fs.createReadStream(tarPath),
|
|
||||||
verifyIntegrity(platformAndArch),
|
|
||||||
new zlib.BrotliDecompress(),
|
|
||||||
tarFs.extract(versionedVendorPath, { ignore }),
|
|
||||||
function (err) {
|
|
||||||
if (err) {
|
|
||||||
if (/unexpected end of file/.test(err.message)) {
|
|
||||||
fail(new Error(`Please delete ${tarPath} as it is not a valid tarball`));
|
|
||||||
}
|
|
||||||
fail(err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const useGlobalLibvips = libvips.useGlobalLibvips();
|
|
||||||
|
|
||||||
if (useGlobalLibvips) {
|
|
||||||
const globalLibvipsVersion = libvips.globalLibvipsVersion();
|
|
||||||
libvips.log(`Detected globally-installed libvips v${globalLibvipsVersion}`);
|
|
||||||
libvips.log('Building from source via node-gyp');
|
|
||||||
process.exit(1);
|
|
||||||
} else if (libvips.hasVendoredLibvips()) {
|
|
||||||
libvips.log(`Using existing vendored libvips v${minimumLibvipsVersion}`);
|
|
||||||
} else {
|
|
||||||
// Is this arch/platform supported?
|
|
||||||
const arch = process.env.npm_config_arch || process.arch;
|
|
||||||
const platformAndArch = platform();
|
|
||||||
if (arch === 'ia32' && !platformAndArch.startsWith('win32')) {
|
|
||||||
throw new Error(`Intel Architecture 32-bit systems require manual installation of libvips >= ${minimumLibvipsVersion}`);
|
|
||||||
}
|
|
||||||
if (platformAndArch === 'darwin-arm64') {
|
|
||||||
throw new Error("Please run 'brew install vips' to install libvips on Apple M1 (ARM64) systems");
|
|
||||||
}
|
|
||||||
if (platformAndArch === 'freebsd-x64' || platformAndArch === 'openbsd-x64' || platformAndArch === 'sunos-x64') {
|
|
||||||
throw new Error(`BSD/SunOS systems require manual installation of libvips >= ${minimumLibvipsVersion}`);
|
|
||||||
}
|
|
||||||
// Linux libc version check
|
|
||||||
const libcFamily = detectLibc.familySync();
|
|
||||||
const libcVersion = detectLibc.versionSync();
|
|
||||||
if (libcFamily === detectLibc.GLIBC && libcVersion && minimumGlibcVersionByArch[arch]) {
|
|
||||||
if (semverLessThan(`${libcVersion}.0`, `${minimumGlibcVersionByArch[arch]}.0`)) {
|
|
||||||
handleError(new Error(`Use with glibc ${libcVersion} requires manual installation of libvips >= ${minimumLibvipsVersion}`));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (libcFamily === detectLibc.MUSL && libcVersion) {
|
|
||||||
if (semverLessThan(libcVersion, '1.1.24')) {
|
|
||||||
handleError(new Error(`Use with musl ${libcVersion} requires manual installation of libvips >= ${minimumLibvipsVersion}`));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Node.js minimum version check
|
|
||||||
const supportedNodeVersion = process.env.npm_package_engines_node || require('../package.json').engines.node;
|
|
||||||
if (!semverSatisfies(process.versions.node, supportedNodeVersion)) {
|
|
||||||
handleError(new Error(`Expected Node.js version ${supportedNodeVersion} but found ${process.versions.node}`));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Download to per-process temporary file
|
|
||||||
const tarFilename = ['libvips', minimumLibvipsVersionLabelled, platformAndArch].join('-') + '.tar.br';
|
|
||||||
const tarPathCache = path.join(libvips.cachePath(), tarFilename);
|
|
||||||
if (fs.existsSync(tarPathCache)) {
|
|
||||||
libvips.log(`Using cached ${tarPathCache}`);
|
|
||||||
extractTarball(tarPathCache, platformAndArch);
|
|
||||||
} else if (localLibvipsDir) {
|
|
||||||
// If localLibvipsDir is given try to use binaries from local directory
|
|
||||||
const tarPathLocal = path.join(path.resolve(localLibvipsDir), `v${minimumLibvipsVersionLabelled}`, tarFilename);
|
|
||||||
libvips.log(`Using local libvips from ${tarPathLocal}`);
|
|
||||||
extractTarball(tarPathLocal, platformAndArch);
|
|
||||||
} else {
|
|
||||||
const url = distBaseUrl + tarFilename;
|
|
||||||
libvips.log(`Downloading ${url}`);
|
|
||||||
simpleGet({ url: url, agent: agent() }, function (err, response) {
|
|
||||||
if (err) {
|
|
||||||
fail(err);
|
|
||||||
} else if (response.statusCode === 404) {
|
|
||||||
fail(new Error(`Prebuilt libvips ${minimumLibvipsVersion} binaries are not yet available for ${platformAndArch}`));
|
|
||||||
} else if (response.statusCode !== 200) {
|
|
||||||
fail(new Error(`Status ${response.statusCode} ${response.statusMessage}`));
|
|
||||||
} else {
|
|
||||||
const tarPathTemp = path.join(os.tmpdir(), `${process.pid}-${tarFilename}`);
|
|
||||||
const tmpFileStream = fs.createWriteStream(tarPathTemp);
|
|
||||||
response
|
|
||||||
.on('error', function (err) {
|
|
||||||
tmpFileStream.destroy(err);
|
|
||||||
})
|
|
||||||
.on('close', function () {
|
|
||||||
if (!response.complete) {
|
|
||||||
tmpFileStream.destroy(new Error('Download incomplete (connection was terminated)'));
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.pipe(tmpFileStream);
|
|
||||||
tmpFileStream
|
|
||||||
.on('error', function (err) {
|
|
||||||
// Clean up temporary file
|
|
||||||
try {
|
|
||||||
fs.unlinkSync(tarPathTemp);
|
|
||||||
} catch (e) {}
|
|
||||||
fail(err);
|
|
||||||
})
|
|
||||||
.on('close', function () {
|
|
||||||
try {
|
|
||||||
// Attempt to rename
|
|
||||||
fs.renameSync(tarPathTemp, tarPathCache);
|
|
||||||
} catch (err) {
|
|
||||||
// Fall back to copy and unlink
|
|
||||||
fs.copyFileSync(tarPathTemp, tarPathCache);
|
|
||||||
fs.unlinkSync(tarPathTemp);
|
|
||||||
}
|
|
||||||
extractTarball(tarPathCache, platformAndArch);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
fail(err);
|
|
||||||
}
|
|
||||||
40
lib/agent.js
@@ -1,40 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
const url = require('url');
|
|
||||||
const tunnelAgent = require('tunnel-agent');
|
|
||||||
|
|
||||||
const is = require('./is');
|
|
||||||
|
|
||||||
const proxies = [
|
|
||||||
'HTTPS_PROXY',
|
|
||||||
'https_proxy',
|
|
||||||
'HTTP_PROXY',
|
|
||||||
'http_proxy',
|
|
||||||
'npm_config_https_proxy',
|
|
||||||
'npm_config_proxy'
|
|
||||||
];
|
|
||||||
|
|
||||||
function env (key) {
|
|
||||||
return process.env[key];
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = function () {
|
|
||||||
try {
|
|
||||||
const proxy = new url.URL(proxies.map(env).find(is.string));
|
|
||||||
const tunnel = proxy.protocol === 'https:'
|
|
||||||
? tunnelAgent.httpsOverHttps
|
|
||||||
: tunnelAgent.httpsOverHttp;
|
|
||||||
const proxyAuth = proxy.username && proxy.password
|
|
||||||
? `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`
|
|
||||||
: null;
|
|
||||||
return tunnel({
|
|
||||||
proxy: {
|
|
||||||
port: Number(proxy.port),
|
|
||||||
host: proxy.hostname,
|
|
||||||
proxyAuth
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,3 +1,6 @@
|
|||||||
|
// Copyright 2013 Lovell Fuller and others.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const is = require('./is');
|
const is = require('./is');
|
||||||
@@ -13,7 +16,7 @@ const bool = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel.
|
* Remove alpha channels, if any. This is a no-op if the image does not have an alpha channel.
|
||||||
*
|
*
|
||||||
* See also {@link /api-operation#flatten|flatten}.
|
* See also {@link /api-operation#flatten|flatten}.
|
||||||
*
|
*
|
||||||
@@ -98,7 +101,7 @@ function extractChannel (channel) {
|
|||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('channel', 'integer or one of: red, green, blue, alpha', channel);
|
throw is.invalidParameterError('channel', 'integer or one of: red, green, blue, alpha', channel);
|
||||||
}
|
}
|
||||||
return this.toColourspace('b-w');
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -155,6 +158,7 @@ function bandbool (boolOp) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Decorate the Sharp prototype with channel-related functions.
|
* Decorate the Sharp prototype with channel-related functions.
|
||||||
|
* @module Sharp
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
module.exports = function (Sharp) {
|
module.exports = function (Sharp) {
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
// Copyright 2013 Lovell Fuller and others.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const color = require('color');
|
const color = require('color');
|
||||||
@@ -16,7 +19,7 @@ const colourspace = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tint the image using the provided chroma while preserving the image luminance.
|
* Tint the image using the provided colour.
|
||||||
* An alpha channel may be present and will be unchanged by the operation.
|
* An alpha channel may be present and will be unchanged by the operation.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
@@ -24,23 +27,21 @@ const colourspace = {
|
|||||||
* .tint({ r: 255, g: 240, b: 16 })
|
* .tint({ r: 255, g: 240, b: 16 })
|
||||||
* .toBuffer();
|
* .toBuffer();
|
||||||
*
|
*
|
||||||
* @param {string|Object} rgb - parsed by the [color](https://www.npmjs.org/package/color) module to extract chroma values.
|
* @param {string|Object} tint - Parsed by the [color](https://www.npmjs.org/package/color) module.
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid parameter
|
* @throws {Error} Invalid parameter
|
||||||
*/
|
*/
|
||||||
function tint (rgb) {
|
function tint (tint) {
|
||||||
const colour = color(rgb);
|
this._setBackgroundColourOption('tint', tint);
|
||||||
this.options.tintA = colour.a();
|
|
||||||
this.options.tintB = colour.b();
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert to 8-bit greyscale; 256 shades of grey.
|
* Convert to 8-bit greyscale; 256 shades of grey.
|
||||||
* This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results.
|
* This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results.
|
||||||
* By default the output image will be web-friendly sRGB and contain three (identical) color channels.
|
* By default the output image will be web-friendly sRGB and contain three (identical) colour channels.
|
||||||
* This may be overridden by other sharp operations such as `toColourspace('b-w')`,
|
* This may be overridden by other sharp operations such as `toColourspace('b-w')`,
|
||||||
* which will produce an output image containing one color channel.
|
* which will produce an output image containing one colour channel.
|
||||||
* An alpha channel may be present, and will be unchanged by the operation.
|
* An alpha channel may be present, and will be unchanged by the operation.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
@@ -67,9 +68,8 @@ function grayscale (grayscale) {
|
|||||||
* Set the pipeline colourspace.
|
* Set the pipeline colourspace.
|
||||||
*
|
*
|
||||||
* The input image will be converted to the provided colourspace at the start of the pipeline.
|
* 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}.
|
* All operations will use this colourspace before converting to the output colourspace,
|
||||||
*
|
* as defined by {@link #tocolourspace|toColourspace}.
|
||||||
* This feature is experimental and has not yet been fully-tested with all operations.
|
|
||||||
*
|
*
|
||||||
* @since 0.29.0
|
* @since 0.29.0
|
||||||
*
|
*
|
||||||
@@ -88,7 +88,7 @@ function pipelineColourspace (colourspace) {
|
|||||||
if (!is.string(colourspace)) {
|
if (!is.string(colourspace)) {
|
||||||
throw is.invalidParameterError('colourspace', 'string', colourspace);
|
throw is.invalidParameterError('colourspace', 'string', colourspace);
|
||||||
}
|
}
|
||||||
this.options.colourspaceInput = colourspace;
|
this.options.colourspacePipeline = colourspace;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,6 +134,26 @@ function toColorspace (colorspace) {
|
|||||||
return this.toColourspace(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.
|
* Update a colour attribute of the this.options Object.
|
||||||
* @private
|
* @private
|
||||||
@@ -143,22 +163,13 @@ function toColorspace (colorspace) {
|
|||||||
*/
|
*/
|
||||||
function _setBackgroundColourOption (key, value) {
|
function _setBackgroundColourOption (key, value) {
|
||||||
if (is.defined(value)) {
|
if (is.defined(value)) {
|
||||||
if (is.object(value) || is.string(value)) {
|
this.options[key] = _getBackgroundColourOption(value);
|
||||||
const colour = color(value);
|
|
||||||
this.options[key] = [
|
|
||||||
colour.red(),
|
|
||||||
colour.green(),
|
|
||||||
colour.blue(),
|
|
||||||
Math.round(colour.alpha() * 255)
|
|
||||||
];
|
|
||||||
} else {
|
|
||||||
throw is.invalidParameterError('background', 'object or string', value);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decorate the Sharp prototype with colour-related functions.
|
* Decorate the Sharp prototype with colour-related functions.
|
||||||
|
* @module Sharp
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
module.exports = function (Sharp) {
|
module.exports = function (Sharp) {
|
||||||
@@ -172,6 +183,7 @@ module.exports = function (Sharp) {
|
|||||||
toColourspace,
|
toColourspace,
|
||||||
toColorspace,
|
toColorspace,
|
||||||
// Private
|
// Private
|
||||||
|
_getBackgroundColourOption,
|
||||||
_setBackgroundColourOption
|
_setBackgroundColourOption
|
||||||
});
|
});
|
||||||
// Class attributes
|
// Class attributes
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
// Copyright 2013 Lovell Fuller and others.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const is = require('./is');
|
const is = require('./is');
|
||||||
@@ -43,8 +46,8 @@ const blend = {
|
|||||||
* The images to composite must be the same size or smaller than the processed image.
|
* The images to composite must be the same size or smaller than the processed image.
|
||||||
* If both `top` and `left` options are provided, they take precedence over `gravity`.
|
* If both `top` and `left` options are provided, they take precedence over `gravity`.
|
||||||
*
|
*
|
||||||
* Any resize or rotate operations in the same processing pipeline
|
* Other operations in the same processing pipeline (e.g. resize, rotate, flip,
|
||||||
* will always be applied to the input image before composition.
|
* flop, extract) will always be applied to the input image before composition.
|
||||||
*
|
*
|
||||||
* The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`,
|
* The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`,
|
||||||
* `dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`,
|
* `dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`,
|
||||||
@@ -105,14 +108,15 @@ const blend = {
|
|||||||
* @param {string} [images[].input.text.align='left'] - text alignment (`'left'`, `'centre'`, `'center'`, `'right'`).
|
* @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 {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 {number} [images[].input.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified.
|
||||||
* @param {boolean} [images[].input.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`.
|
* @param {boolean} [images[].input.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like `<span foreground="red">Red!</span>`.
|
||||||
* @param {number} [images[].input.text.spacing=0] - text line height in points. Will use the font line height if none is specified.
|
* @param {number} [images[].input.text.spacing=0] - text line height in points. Will use the font line height if none is specified.
|
||||||
|
* @param {Boolean} [images[].autoOrient=false] - set to true to use EXIF orientation data, if present, to orient the image.
|
||||||
* @param {String} [images[].blend='over'] - how to blend this image with the image below.
|
* @param {String} [images[].blend='over'] - how to blend this image with the image below.
|
||||||
* @param {String} [images[].gravity='centre'] - gravity at which to place the overlay.
|
* @param {String} [images[].gravity='centre'] - gravity at which to place the overlay.
|
||||||
* @param {Number} [images[].top] - the pixel offset from the top edge.
|
* @param {Number} [images[].top] - the pixel offset from the top edge.
|
||||||
* @param {Number} [images[].left] - the pixel offset from the left 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[].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 premultipling the image below. Equivalent to the `--premultiplied` vips option.
|
* @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 {Number} [images[].density=72] - number representing the DPI for vector overlay image.
|
||||||
* @param {Object} [images[].raw] - describes overlay when using raw pixel data.
|
* @param {Object} [images[].raw] - describes overlay when using raw pixel data.
|
||||||
* @param {Number} [images[].raw.width]
|
* @param {Number} [images[].raw.width]
|
||||||
@@ -199,6 +203,7 @@ function composite (images) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Decorate the Sharp prototype with composite-related functions.
|
* Decorate the Sharp prototype with composite-related functions.
|
||||||
|
* @module Sharp
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
module.exports = function (Sharp) {
|
module.exports = function (Sharp) {
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
|
// Copyright 2013 Lovell Fuller and others.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const util = require('util');
|
const util = require('node:util');
|
||||||
const stream = require('stream');
|
const stream = require('node:stream');
|
||||||
const is = require('./is');
|
const is = require('./is');
|
||||||
|
|
||||||
require('./libvips').hasVendoredLibvips();
|
|
||||||
require('./sharp');
|
require('./sharp');
|
||||||
|
|
||||||
// Use NODE_DEBUG=sharp to enable libvips warnings
|
// Use NODE_DEBUG=sharp to enable libvips warnings
|
||||||
@@ -20,6 +22,10 @@ const debuglog = util.debuglog('sharp');
|
|||||||
*
|
*
|
||||||
* Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.
|
* 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
|
* @constructs Sharp
|
||||||
*
|
*
|
||||||
* @emits Sharp#info
|
* @emits Sharp#info
|
||||||
@@ -34,19 +40,21 @@ const debuglog = util.debuglog('sharp');
|
|||||||
* });
|
* });
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* // Read image data from readableStream,
|
* // Read image data from remote URL,
|
||||||
* // resize to 300 pixels wide,
|
* // resize to 300 pixels wide,
|
||||||
* // emit an 'info' event with calculated dimensions
|
* // emit an 'info' event with calculated dimensions
|
||||||
* // and finally write image data to writableStream
|
* // and finally write image data to writableStream
|
||||||
* var transformer = sharp()
|
* const { body } = fetch('https://...');
|
||||||
|
* const readableStream = Readable.fromWeb(body);
|
||||||
|
* const transformer = sharp()
|
||||||
* .resize(300)
|
* .resize(300)
|
||||||
* .on('info', function(info) {
|
* .on('info', ({ height }) => {
|
||||||
* console.log('Image height is ' + info.height);
|
* console.log(`Image height is ${height}`);
|
||||||
* });
|
* });
|
||||||
* readableStream.pipe(transformer).pipe(writableStream);
|
* readableStream.pipe(transformer).pipe(writableStream);
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* // Create a blank 300x200 PNG image of semi-transluent red pixels
|
* // Create a blank 300x200 PNG image of semi-translucent red pixels
|
||||||
* sharp({
|
* sharp({
|
||||||
* create: {
|
* create: {
|
||||||
* width: 300,
|
* width: 300,
|
||||||
@@ -113,51 +121,86 @@ const debuglog = util.debuglog('sharp');
|
|||||||
* }
|
* }
|
||||||
* }).toFile('text_rgba.png');
|
* }).toFile('text_rgba.png');
|
||||||
*
|
*
|
||||||
* @param {(Buffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string)} [input] - if present, can be
|
* @example
|
||||||
* a Buffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or
|
* // 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 TypedArray containing raw pixel image data, or
|
||||||
* a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file.
|
* a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file.
|
||||||
|
* An array of inputs can be provided, and these will be joined together.
|
||||||
* JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present.
|
* JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present.
|
||||||
* @param {Object} [options] - if present, is an Object with optional attributes.
|
* @param {Object} [options] - if present, is an Object with optional attributes.
|
||||||
* @param {string} [options.failOn='warning'] - level of sensitivity to invalid images, one of (in order of sensitivity): 'none' (least), 'truncated', 'error' or 'warning' (most), highers level imply lower levels.
|
* @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
|
* @param {number|boolean} [options.limitInputPixels=268402689] - Do not process input images where the number of pixels
|
||||||
* (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted.
|
* (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted.
|
||||||
* An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF).
|
* An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF).
|
||||||
* @param {boolean} [options.unlimited=false] - Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF).
|
* @param {boolean} [options.unlimited=false] - Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF).
|
||||||
* @param {boolean} [options.sequentialRead=false] - Set this to `true` to use sequential rather than random access where possible.
|
* @param {boolean} [options.autoOrient=false] - Set this to `true` to rotate/flip the image to match EXIF `Orientation`, if any.
|
||||||
* This can reduce memory usage and might improve performance on some systems.
|
* @param {boolean} [options.sequentialRead=true] - Set this to `false` to use random access rather than sequential read. Some operations will do this automatically.
|
||||||
* @param {number} [options.density=72] - number representing the DPI for vector images in the range 1 to 100000.
|
* @param {number} [options.density=72] - number representing the DPI for vector images in the range 1 to 100000.
|
||||||
* @param {number} [options.pages=1] - number of pages to extract for multi-page input (GIF, WebP, AVIF, TIFF, PDF), use -1 for all pages.
|
* @param {number} [options.ignoreIcc=false] - should the embedded ICC profile, if any, be ignored.
|
||||||
* @param {number} [options.page=0] - page number to start extracting from for multi-page input (GIF, WebP, AVIF, TIFF, PDF), zero based.
|
* @param {number} [options.pages=1] - Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages.
|
||||||
* @param {number} [options.subifd=-1] - subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image.
|
* @param {number} [options.page=0] - Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based.
|
||||||
* @param {number} [options.level=0] - level to extract from a multi-level input (OpenSlide), zero based.
|
* @param {boolean} [options.animated=false] - Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`.
|
||||||
* @param {boolean} [options.animated=false] - Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`).
|
|
||||||
* @param {Object} [options.raw] - describes raw pixel input image data. See `raw()` for pixel ordering.
|
* @param {Object} [options.raw] - describes raw pixel input image data. See `raw()` for pixel ordering.
|
||||||
* @param {number} [options.raw.width] - integral number of pixels wide.
|
* @param {number} [options.raw.width] - integral number of pixels wide.
|
||||||
* @param {number} [options.raw.height] - integral number of pixels high.
|
* @param {number} [options.raw.height] - integral number of pixels high.
|
||||||
* @param {number} [options.raw.channels] - integral number of channels, between 1 and 4.
|
* @param {number} [options.raw.channels] - integral number of channels, between 1 and 4.
|
||||||
* @param {boolean} [options.raw.premultiplied] - specifies that the raw input has already been premultiplied, set to `true`
|
* @param {boolean} [options.raw.premultiplied] - specifies that the raw input has already been premultiplied, set to `true`
|
||||||
* to avoid sharp premultiplying the image. (optional, default `false`)
|
* to avoid sharp premultiplying the image. (optional, default `false`)
|
||||||
|
* @param {number} [options.raw.pageHeight] - The pixel height of each page/frame for animated images, must be an integral factor of `raw.height`.
|
||||||
* @param {Object} [options.create] - describes a new image to be created.
|
* @param {Object} [options.create] - describes a new image to be created.
|
||||||
* @param {number} [options.create.width] - integral number of pixels wide.
|
* @param {number} [options.create.width] - integral number of pixels wide.
|
||||||
* @param {number} [options.create.height] - integral number of pixels high.
|
* @param {number} [options.create.height] - integral number of pixels high.
|
||||||
* @param {number} [options.create.channels] - integral number of channels, either 3 (RGB) or 4 (RGBA).
|
* @param {number} [options.create.channels] - integral number of channels, either 3 (RGB) or 4 (RGBA).
|
||||||
* @param {string|Object} [options.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
|
* @param {string|Object} [options.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
|
||||||
|
* @param {number} [options.create.pageHeight] - The pixel height of each page/frame for animated images, must be an integral factor of `create.height`.
|
||||||
* @param {Object} [options.create.noise] - describes a noise to be created.
|
* @param {Object} [options.create.noise] - describes a noise to be created.
|
||||||
* @param {string} [options.create.noise.type] - type of generated noise, currently only `gaussian` is supported.
|
* @param {string} [options.create.noise.type] - type of generated noise, currently only `gaussian` is supported.
|
||||||
* @param {number} [options.create.noise.mean] - mean of pixels in generated noise.
|
* @param {number} [options.create.noise.mean=128] - Mean value of pixels in the generated noise.
|
||||||
* @param {number} [options.create.noise.sigma] - standard deviation of pixels in generated noise.
|
* @param {number} [options.create.noise.sigma=30] - Standard deviation of pixel values in the generated noise.
|
||||||
* @param {Object} [options.text] - describes a new text image to be created.
|
* @param {Object} [options.text] - describes a new text image to be created.
|
||||||
* @param {string} [options.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.
|
* @param {string} [options.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.
|
||||||
* @param {string} [options.text.font] - font name to render with.
|
* @param {string} [options.text.font] - font name to render with.
|
||||||
* @param {string} [options.text.fontfile] - absolute filesystem path to a font file that can be used by `font`.
|
* @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.width=0] - Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries.
|
||||||
* @param {number} [options.text.height=0] - integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0.
|
* @param {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'] - text alignment (`'left'`, `'centre'`, `'center'`, `'right'`).
|
* @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 {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 {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 {boolean} [options.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`.
|
||||||
* @param {number} [options.text.spacing=0] - text line height in points. Will use the font line height if none is specified.
|
* @param {number} [options.text.spacing=0] - text line height in points. Will use the font line height if none is specified.
|
||||||
|
* @param {string} [options.text.wrap='word'] - word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'.
|
||||||
|
* @param {Object} [options.join] - describes how an array of input images should be joined.
|
||||||
|
* @param {number} [options.join.across=1] - number of images to join horizontally.
|
||||||
|
* @param {boolean} [options.join.animated=false] - set this to `true` to join the images as an animated image.
|
||||||
|
* @param {number} [options.join.shim=0] - number of pixels to insert between joined images.
|
||||||
|
* @param {string|Object} [options.join.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
|
||||||
|
* @param {string} [options.join.halign='left'] - horizontal alignment style for images joined horizontally (`'left'`, `'centre'`, `'center'`, `'right'`).
|
||||||
|
* @param {string} [options.join.valign='top'] - vertical alignment style for images joined vertically (`'top'`, `'centre'`, `'center'`, `'bottom'`).
|
||||||
|
* @param {Object} [options.tiff] - Describes TIFF specific options.
|
||||||
|
* @param {number} [options.tiff.subifd=-1] - Sub Image File Directory to extract for OME-TIFF, defaults to main image.
|
||||||
|
* @param {Object} [options.svg] - Describes SVG specific options.
|
||||||
|
* @param {string} [options.svg.stylesheet] - Custom CSS for SVG input, applied with a User Origin during the CSS cascade.
|
||||||
|
* @param {boolean} [options.svg.highBitdepth=false] - Set to `true` to render SVG input at 32-bits per channel (128-bit) instead of 8-bits per channel (32-bit) RGBA.
|
||||||
|
* @param {Object} [options.pdf] - Describes PDF specific options. Requires the use of a globally-installed libvips compiled with support for PDFium, Poppler, ImageMagick or GraphicsMagick.
|
||||||
|
* @param {string|Object} [options.pdf.background] - Background colour to use when PDF is partially transparent. Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
|
||||||
|
* @param {Object} [options.openSlide] - Describes OpenSlide specific options. Requires the use of a globally-installed libvips compiled with support for OpenSlide.
|
||||||
|
* @param {number} [options.openSlide.level=0] - Level to extract from a multi-level input, zero based.
|
||||||
|
* @param {Object} [options.jp2] - Describes JPEG 2000 specific options. Requires the use of a globally-installed libvips compiled with support for OpenJPEG.
|
||||||
|
* @param {boolean} [options.jp2.oneshot=false] - Set to `true` to decode tiled JPEG 2000 images in a single operation, improving compatibility.
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid parameters
|
* @throws {Error} Invalid parameters
|
||||||
*/
|
*/
|
||||||
@@ -184,7 +227,6 @@ const Sharp = function (input, options) {
|
|||||||
canvas: 'crop',
|
canvas: 'crop',
|
||||||
position: 0,
|
position: 0,
|
||||||
resizeBackground: [0, 0, 0, 255],
|
resizeBackground: [0, 0, 0, 255],
|
||||||
useExifOrientation: false,
|
|
||||||
angle: 0,
|
angle: 0,
|
||||||
rotationAngle: 0,
|
rotationAngle: 0,
|
||||||
rotationBackground: [0, 0, 0, 255],
|
rotationBackground: [0, 0, 0, 255],
|
||||||
@@ -196,6 +238,7 @@ const Sharp = function (input, options) {
|
|||||||
extendLeft: 0,
|
extendLeft: 0,
|
||||||
extendRight: 0,
|
extendRight: 0,
|
||||||
extendBackground: [0, 0, 0, 255],
|
extendBackground: [0, 0, 0, 255],
|
||||||
|
extendWith: 'background',
|
||||||
withoutEnlargement: false,
|
withoutEnlargement: false,
|
||||||
withoutReduction: false,
|
withoutReduction: false,
|
||||||
affineMatrix: [],
|
affineMatrix: [],
|
||||||
@@ -208,14 +251,16 @@ const Sharp = function (input, options) {
|
|||||||
kernel: 'lanczos3',
|
kernel: 'lanczos3',
|
||||||
fastShrinkOnLoad: true,
|
fastShrinkOnLoad: true,
|
||||||
// operations
|
// operations
|
||||||
tintA: 128,
|
tint: [-1, 0, 0, 0],
|
||||||
tintB: 128,
|
|
||||||
flatten: false,
|
flatten: false,
|
||||||
flattenBackground: [0, 0, 0],
|
flattenBackground: [0, 0, 0],
|
||||||
|
unflatten: false,
|
||||||
negate: false,
|
negate: false,
|
||||||
negateAlpha: true,
|
negateAlpha: true,
|
||||||
medianSize: 0,
|
medianSize: 0,
|
||||||
blurSigma: 0,
|
blurSigma: 0,
|
||||||
|
precision: 'integer',
|
||||||
|
minAmpl: 0.2,
|
||||||
sharpenSigma: 0,
|
sharpenSigma: 0,
|
||||||
sharpenM1: 1,
|
sharpenM1: 1,
|
||||||
sharpenM2: 2,
|
sharpenM2: 2,
|
||||||
@@ -225,11 +270,16 @@ const Sharp = function (input, options) {
|
|||||||
threshold: 0,
|
threshold: 0,
|
||||||
thresholdGrayscale: true,
|
thresholdGrayscale: true,
|
||||||
trimBackground: [],
|
trimBackground: [],
|
||||||
trimThreshold: 0,
|
trimThreshold: -1,
|
||||||
|
trimLineArt: false,
|
||||||
|
dilateWidth: 0,
|
||||||
|
erodeWidth: 0,
|
||||||
gamma: 0,
|
gamma: 0,
|
||||||
gammaOut: 0,
|
gammaOut: 0,
|
||||||
greyscale: false,
|
greyscale: false,
|
||||||
normalise: false,
|
normalise: false,
|
||||||
|
normaliseLower: 1,
|
||||||
|
normaliseUpper: 99,
|
||||||
claheWidth: 0,
|
claheWidth: 0,
|
||||||
claheHeight: 0,
|
claheHeight: 0,
|
||||||
claheMaxSlope: 3,
|
claheMaxSlope: 3,
|
||||||
@@ -244,18 +294,22 @@ const Sharp = function (input, options) {
|
|||||||
removeAlpha: false,
|
removeAlpha: false,
|
||||||
ensureAlpha: -1,
|
ensureAlpha: -1,
|
||||||
colourspace: 'srgb',
|
colourspace: 'srgb',
|
||||||
colourspaceInput: 'last',
|
colourspacePipeline: 'last',
|
||||||
composite: [],
|
composite: [],
|
||||||
// output
|
// output
|
||||||
fileOut: '',
|
fileOut: '',
|
||||||
formatOut: 'input',
|
formatOut: 'input',
|
||||||
streamOut: false,
|
streamOut: false,
|
||||||
withMetadata: false,
|
keepMetadata: 0,
|
||||||
withMetadataOrientation: -1,
|
withMetadataOrientation: -1,
|
||||||
withMetadataDensity: 0,
|
withMetadataDensity: 0,
|
||||||
withMetadataIcc: '',
|
withIccProfile: '',
|
||||||
withMetadataStrs: {},
|
withExif: {},
|
||||||
|
withExifMerge: true,
|
||||||
|
withXmp: '',
|
||||||
resolveWithObject: false,
|
resolveWithObject: false,
|
||||||
|
loop: -1,
|
||||||
|
delay: [],
|
||||||
// output format
|
// output format
|
||||||
jpegQuality: 80,
|
jpegQuality: 80,
|
||||||
jpegProgressive: false,
|
jpegProgressive: false,
|
||||||
@@ -283,17 +337,24 @@ const Sharp = function (input, options) {
|
|||||||
webpLossless: false,
|
webpLossless: false,
|
||||||
webpNearLossless: false,
|
webpNearLossless: false,
|
||||||
webpSmartSubsample: false,
|
webpSmartSubsample: false,
|
||||||
|
webpSmartDeblock: false,
|
||||||
|
webpPreset: 'default',
|
||||||
webpEffort: 4,
|
webpEffort: 4,
|
||||||
webpMinSize: false,
|
webpMinSize: false,
|
||||||
webpMixed: false,
|
webpMixed: false,
|
||||||
gifBitdepth: 8,
|
gifBitdepth: 8,
|
||||||
gifEffort: 7,
|
gifEffort: 7,
|
||||||
gifDither: 1,
|
gifDither: 1,
|
||||||
gifReoptimise: false,
|
gifInterFrameMaxError: 0,
|
||||||
|
gifInterPaletteMaxError: 3,
|
||||||
|
gifKeepDuplicateFrames: false,
|
||||||
|
gifReuse: true,
|
||||||
|
gifProgressive: false,
|
||||||
tiffQuality: 80,
|
tiffQuality: 80,
|
||||||
tiffCompression: 'jpeg',
|
tiffCompression: 'jpeg',
|
||||||
tiffPredictor: 'horizontal',
|
tiffPredictor: 'horizontal',
|
||||||
tiffPyramid: false,
|
tiffPyramid: false,
|
||||||
|
tiffMiniswhite: false,
|
||||||
tiffBitdepth: 8,
|
tiffBitdepth: 8,
|
||||||
tiffTile: false,
|
tiffTile: false,
|
||||||
tiffTileHeight: 256,
|
tiffTileHeight: 256,
|
||||||
@@ -306,6 +367,11 @@ const Sharp = function (input, options) {
|
|||||||
heifCompression: 'av1',
|
heifCompression: 'av1',
|
||||||
heifEffort: 4,
|
heifEffort: 4,
|
||||||
heifChromaSubsampling: '4:4:4',
|
heifChromaSubsampling: '4:4:4',
|
||||||
|
heifBitdepth: 8,
|
||||||
|
jxlDistance: 1,
|
||||||
|
jxlDecodingTier: 0,
|
||||||
|
jxlEffort: 7,
|
||||||
|
jxlLossless: false,
|
||||||
rawDepth: 'uchar',
|
rawDepth: 'uchar',
|
||||||
tileSize: 256,
|
tileSize: 256,
|
||||||
tileOverlap: 0,
|
tileOverlap: 0,
|
||||||
@@ -322,6 +388,7 @@ const Sharp = function (input, options) {
|
|||||||
timeoutSeconds: 0,
|
timeoutSeconds: 0,
|
||||||
linearA: [],
|
linearA: [],
|
||||||
linearB: [],
|
linearB: [],
|
||||||
|
pdfBackground: [255, 255, 255, 255],
|
||||||
// Function to notify of libvips warnings
|
// Function to notify of libvips warnings
|
||||||
debuglog: warning => {
|
debuglog: warning => {
|
||||||
this.emit('warning', warning);
|
this.emit('warning', warning);
|
||||||
@@ -402,13 +469,16 @@ Object.setPrototypeOf(Sharp, stream.Duplex);
|
|||||||
function clone () {
|
function clone () {
|
||||||
// Clone existing options
|
// Clone existing options
|
||||||
const clone = this.constructor.call();
|
const clone = this.constructor.call();
|
||||||
clone.options = Object.assign({}, this.options);
|
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
|
// Pass 'finish' event to clone for Stream-based input
|
||||||
if (this._isStreamInput()) {
|
if (this._isStreamInput()) {
|
||||||
this.on('finish', () => {
|
this.on('finish', () => {
|
||||||
// Clone inherits input data
|
// Clone inherits input data
|
||||||
this._flattenBufferIn();
|
this._flattenBufferIn();
|
||||||
clone.options.bufferIn = this.options.bufferIn;
|
clone.options.input.buffer = this.options.input.buffer;
|
||||||
clone.emit('finish');
|
clone.emit('finish');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -418,6 +488,7 @@ Object.assign(Sharp.prototype, { clone });
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Export constructor.
|
* Export constructor.
|
||||||
|
* @module Sharp
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
module.exports = Sharp;
|
module.exports = Sharp;
|
||||||
|
|||||||
1963
lib/index.d.ts
vendored
Normal file
@@ -1,3 +1,6 @@
|
|||||||
|
// Copyright 2013 Lovell Fuller and others.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const Sharp = require('./constructor');
|
const Sharp = require('./constructor');
|
||||||
|
|||||||
336
lib/input.js
@@ -1,29 +1,48 @@
|
|||||||
|
// Copyright 2013 Lovell Fuller and others.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const color = require('color');
|
|
||||||
const is = require('./is');
|
const is = require('./is');
|
||||||
const sharp = require('./sharp');
|
const sharp = require('./sharp');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Justication alignment
|
* Justification alignment
|
||||||
* @member
|
* @member
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
const align = {
|
const align = {
|
||||||
left: 'low',
|
left: 'low',
|
||||||
|
top: 'low',
|
||||||
|
low: 'low',
|
||||||
center: 'centre',
|
center: 'centre',
|
||||||
centre: 'centre',
|
centre: 'centre',
|
||||||
right: 'high'
|
right: 'high',
|
||||||
|
bottom: 'high',
|
||||||
|
high: 'high'
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const inputStreamParameters = [
|
||||||
|
// Limits and error handling
|
||||||
|
'failOn', 'limitInputPixels', 'unlimited',
|
||||||
|
// Format-generic
|
||||||
|
'animated', 'autoOrient', 'density', 'ignoreIcc', 'page', 'pages', 'sequentialRead',
|
||||||
|
// Format-specific
|
||||||
|
'jp2', 'openSlide', 'pdf', 'raw', 'svg', 'tiff',
|
||||||
|
// Deprecated
|
||||||
|
'failOnError', 'openSlideLevel', 'pdfBackground', 'tiffSubifd'
|
||||||
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Extract input options, if any, from an object.
|
* Extract input options, if any, from an object.
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
function _inputOptionsFromObject (obj) {
|
function _inputOptionsFromObject (obj) {
|
||||||
const { raw, density, limitInputPixels, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd } = obj;
|
const params = inputStreamParameters
|
||||||
return [raw, density, limitInputPixels, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd].some(is.defined)
|
.filter(p => is.defined(obj[p]))
|
||||||
? { raw, density, limitInputPixels, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd }
|
.map(p => ([p, obj[p]]));
|
||||||
|
return params.length
|
||||||
|
? Object.fromEntries(params)
|
||||||
: undefined;
|
: undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,10 +52,12 @@ function _inputOptionsFromObject (obj) {
|
|||||||
*/
|
*/
|
||||||
function _createInputDescriptor (input, inputOptions, containerOptions) {
|
function _createInputDescriptor (input, inputOptions, containerOptions) {
|
||||||
const inputDescriptor = {
|
const inputDescriptor = {
|
||||||
|
autoOrient: false,
|
||||||
failOn: 'warning',
|
failOn: 'warning',
|
||||||
limitInputPixels: Math.pow(0x3FFF, 2),
|
limitInputPixels: Math.pow(0x3FFF, 2),
|
||||||
|
ignoreIcc: false,
|
||||||
unlimited: false,
|
unlimited: false,
|
||||||
sequentialRead: false
|
sequentialRead: true
|
||||||
};
|
};
|
||||||
if (is.string(input)) {
|
if (is.string(input)) {
|
||||||
// filesystem
|
// filesystem
|
||||||
@@ -47,6 +68,11 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
|||||||
throw Error('Input Buffer is empty');
|
throw Error('Input Buffer is empty');
|
||||||
}
|
}
|
||||||
inputDescriptor.buffer = input;
|
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)) {
|
} else if (is.typedArray(input)) {
|
||||||
if (input.length === 0) {
|
if (input.length === 0) {
|
||||||
throw Error('Input Bit Array is empty');
|
throw Error('Input Bit Array is empty');
|
||||||
@@ -62,6 +88,18 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
|||||||
} else if (!is.defined(input) && !is.defined(inputOptions) && is.object(containerOptions) && containerOptions.allowStream) {
|
} else if (!is.defined(input) && !is.defined(inputOptions) && is.object(containerOptions) && containerOptions.allowStream) {
|
||||||
// Stream without options
|
// Stream without options
|
||||||
inputDescriptor.buffer = [];
|
inputDescriptor.buffer = [];
|
||||||
|
} else if (Array.isArray(input)) {
|
||||||
|
if (input.length > 1) {
|
||||||
|
// Join images together
|
||||||
|
if (!this.options.joining) {
|
||||||
|
this.options.joining = true;
|
||||||
|
this.options.join = input.map(i => this._createInputDescriptor(i));
|
||||||
|
} else {
|
||||||
|
throw new Error('Recursive join is unsupported');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new Error('Expected at least two images to join');
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
throw new Error(`Unsupported input '${input}' of type ${typeof input}${
|
throw new Error(`Unsupported input '${input}' of type ${typeof input}${
|
||||||
is.defined(inputOptions) ? ` when also providing options of type ${typeof inputOptions}` : ''
|
is.defined(inputOptions) ? ` when also providing options of type ${typeof inputOptions}` : ''
|
||||||
@@ -84,6 +122,14 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
|||||||
throw is.invalidParameterError('failOn', 'one of: none, truncated, error, warning', inputOptions.failOn);
|
throw is.invalidParameterError('failOn', 'one of: none, truncated, error, warning', inputOptions.failOn);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// autoOrient
|
||||||
|
if (is.defined(inputOptions.autoOrient)) {
|
||||||
|
if (is.bool(inputOptions.autoOrient)) {
|
||||||
|
inputDescriptor.autoOrient = inputOptions.autoOrient;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('autoOrient', 'boolean', inputOptions.autoOrient);
|
||||||
|
}
|
||||||
|
}
|
||||||
// Density
|
// Density
|
||||||
if (is.defined(inputOptions.density)) {
|
if (is.defined(inputOptions.density)) {
|
||||||
if (is.inRange(inputOptions.density, 1, 100000)) {
|
if (is.inRange(inputOptions.density, 1, 100000)) {
|
||||||
@@ -92,6 +138,14 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
|||||||
throw is.invalidParameterError('density', 'number between 1 and 100000', inputOptions.density);
|
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
|
// limitInputPixels
|
||||||
if (is.defined(inputOptions.limitInputPixels)) {
|
if (is.defined(inputOptions.limitInputPixels)) {
|
||||||
if (is.bool(inputOptions.limitInputPixels)) {
|
if (is.bool(inputOptions.limitInputPixels)) {
|
||||||
@@ -131,8 +185,6 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
|||||||
inputDescriptor.rawWidth = inputOptions.raw.width;
|
inputDescriptor.rawWidth = inputOptions.raw.width;
|
||||||
inputDescriptor.rawHeight = inputOptions.raw.height;
|
inputDescriptor.rawHeight = inputOptions.raw.height;
|
||||||
inputDescriptor.rawChannels = inputOptions.raw.channels;
|
inputDescriptor.rawChannels = inputOptions.raw.channels;
|
||||||
inputDescriptor.rawPremultiplied = !!inputOptions.raw.premultiplied;
|
|
||||||
|
|
||||||
switch (input.constructor) {
|
switch (input.constructor) {
|
||||||
case Uint8Array:
|
case Uint8Array:
|
||||||
case Uint8ClampedArray:
|
case Uint8ClampedArray:
|
||||||
@@ -166,6 +218,25 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
|||||||
} else {
|
} else {
|
||||||
throw new Error('Expected width, height and channels for raw pixel input');
|
throw new Error('Expected width, height and channels for raw pixel input');
|
||||||
}
|
}
|
||||||
|
inputDescriptor.rawPremultiplied = false;
|
||||||
|
if (is.defined(inputOptions.raw.premultiplied)) {
|
||||||
|
if (is.bool(inputOptions.raw.premultiplied)) {
|
||||||
|
inputDescriptor.rawPremultiplied = inputOptions.raw.premultiplied;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('raw.premultiplied', 'boolean', inputOptions.raw.premultiplied);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
inputDescriptor.rawPageHeight = 0;
|
||||||
|
if (is.defined(inputOptions.raw.pageHeight)) {
|
||||||
|
if (is.integer(inputOptions.raw.pageHeight) && inputOptions.raw.pageHeight > 0 && inputOptions.raw.pageHeight <= inputOptions.raw.height) {
|
||||||
|
if (inputOptions.raw.height % inputOptions.raw.pageHeight !== 0) {
|
||||||
|
throw new Error(`Expected raw.height ${inputOptions.raw.height} to be a multiple of raw.pageHeight ${inputOptions.raw.pageHeight}`);
|
||||||
|
}
|
||||||
|
inputDescriptor.rawPageHeight = inputOptions.raw.pageHeight;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('raw.pageHeight', 'positive integer', inputOptions.raw.pageHeight);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Multi-page input (GIF, TIFF, PDF)
|
// Multi-page input (GIF, TIFF, PDF)
|
||||||
if (is.defined(inputOptions.animated)) {
|
if (is.defined(inputOptions.animated)) {
|
||||||
@@ -189,22 +260,68 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
|||||||
throw is.invalidParameterError('page', 'integer between 0 and 100000', inputOptions.page);
|
throw is.invalidParameterError('page', 'integer between 0 and 100000', inputOptions.page);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Multi-level input (OpenSlide)
|
// OpenSlide specific options
|
||||||
if (is.defined(inputOptions.level)) {
|
if (is.object(inputOptions.openSlide) && is.defined(inputOptions.openSlide.level)) {
|
||||||
|
if (is.integer(inputOptions.openSlide.level) && is.inRange(inputOptions.openSlide.level, 0, 256)) {
|
||||||
|
inputDescriptor.openSlideLevel = inputOptions.openSlide.level;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('openSlide.level', 'integer between 0 and 256', inputOptions.openSlide.level);
|
||||||
|
}
|
||||||
|
} else if (is.defined(inputOptions.level)) {
|
||||||
|
// Deprecated
|
||||||
if (is.integer(inputOptions.level) && is.inRange(inputOptions.level, 0, 256)) {
|
if (is.integer(inputOptions.level) && is.inRange(inputOptions.level, 0, 256)) {
|
||||||
inputDescriptor.level = inputOptions.level;
|
inputDescriptor.openSlideLevel = inputOptions.level;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('level', 'integer between 0 and 256', inputOptions.level);
|
throw is.invalidParameterError('level', 'integer between 0 and 256', inputOptions.level);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Sub Image File Directory (TIFF)
|
// TIFF specific options
|
||||||
if (is.defined(inputOptions.subifd)) {
|
if (is.object(inputOptions.tiff) && is.defined(inputOptions.tiff.subifd)) {
|
||||||
|
if (is.integer(inputOptions.tiff.subifd) && is.inRange(inputOptions.tiff.subifd, -1, 100000)) {
|
||||||
|
inputDescriptor.tiffSubifd = inputOptions.tiff.subifd;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('tiff.subifd', 'integer between -1 and 100000', inputOptions.tiff.subifd);
|
||||||
|
}
|
||||||
|
} else if (is.defined(inputOptions.subifd)) {
|
||||||
|
// Deprecated
|
||||||
if (is.integer(inputOptions.subifd) && is.inRange(inputOptions.subifd, -1, 100000)) {
|
if (is.integer(inputOptions.subifd) && is.inRange(inputOptions.subifd, -1, 100000)) {
|
||||||
inputDescriptor.subifd = inputOptions.subifd;
|
inputDescriptor.tiffSubifd = inputOptions.subifd;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('subifd', 'integer between -1 and 100000', inputOptions.subifd);
|
throw is.invalidParameterError('subifd', 'integer between -1 and 100000', inputOptions.subifd);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// SVG specific options
|
||||||
|
if (is.object(inputOptions.svg)) {
|
||||||
|
if (is.defined(inputOptions.svg.stylesheet)) {
|
||||||
|
if (is.string(inputOptions.svg.stylesheet)) {
|
||||||
|
inputDescriptor.svgStylesheet = inputOptions.svg.stylesheet;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('svg.stylesheet', 'string', inputOptions.svg.stylesheet);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (is.defined(inputOptions.svg.highBitdepth)) {
|
||||||
|
if (is.bool(inputOptions.svg.highBitdepth)) {
|
||||||
|
inputDescriptor.svgHighBitdepth = inputOptions.svg.highBitdepth;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('svg.highBitdepth', 'boolean', inputOptions.svg.highBitdepth);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// PDF specific options
|
||||||
|
if (is.object(inputOptions.pdf) && is.defined(inputOptions.pdf.background)) {
|
||||||
|
inputDescriptor.pdfBackground = this._getBackgroundColourOption(inputOptions.pdf.background);
|
||||||
|
} else if (is.defined(inputOptions.pdfBackground)) {
|
||||||
|
// Deprecated
|
||||||
|
inputDescriptor.pdfBackground = this._getBackgroundColourOption(inputOptions.pdfBackground);
|
||||||
|
}
|
||||||
|
// JPEG 2000 specific options
|
||||||
|
if (is.object(inputOptions.jp2) && is.defined(inputOptions.jp2.oneshot)) {
|
||||||
|
if (is.bool(inputOptions.jp2.oneshot)) {
|
||||||
|
inputDescriptor.jp2Oneshot = inputOptions.jp2.oneshot;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('jp2.oneshot', 'boolean', inputOptions.jp2.oneshot);
|
||||||
|
}
|
||||||
|
}
|
||||||
// Create new image
|
// Create new image
|
||||||
if (is.defined(inputOptions.create)) {
|
if (is.defined(inputOptions.create)) {
|
||||||
if (
|
if (
|
||||||
@@ -216,39 +333,50 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
|||||||
inputDescriptor.createWidth = inputOptions.create.width;
|
inputDescriptor.createWidth = inputOptions.create.width;
|
||||||
inputDescriptor.createHeight = inputOptions.create.height;
|
inputDescriptor.createHeight = inputOptions.create.height;
|
||||||
inputDescriptor.createChannels = inputOptions.create.channels;
|
inputDescriptor.createChannels = inputOptions.create.channels;
|
||||||
|
inputDescriptor.createPageHeight = 0;
|
||||||
|
if (is.defined(inputOptions.create.pageHeight)) {
|
||||||
|
if (is.integer(inputOptions.create.pageHeight) && inputOptions.create.pageHeight > 0 && inputOptions.create.pageHeight <= inputOptions.create.height) {
|
||||||
|
if (inputOptions.create.height % inputOptions.create.pageHeight !== 0) {
|
||||||
|
throw new Error(`Expected create.height ${inputOptions.create.height} to be a multiple of create.pageHeight ${inputOptions.create.pageHeight}`);
|
||||||
|
}
|
||||||
|
inputDescriptor.createPageHeight = inputOptions.create.pageHeight;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('create.pageHeight', 'positive integer', inputOptions.create.pageHeight);
|
||||||
|
}
|
||||||
|
}
|
||||||
// Noise
|
// Noise
|
||||||
if (is.defined(inputOptions.create.noise)) {
|
if (is.defined(inputOptions.create.noise)) {
|
||||||
if (!is.object(inputOptions.create.noise)) {
|
if (!is.object(inputOptions.create.noise)) {
|
||||||
throw new Error('Expected noise to be an object');
|
throw new Error('Expected noise to be an object');
|
||||||
}
|
}
|
||||||
if (!is.inArray(inputOptions.create.noise.type, ['gaussian'])) {
|
if (inputOptions.create.noise.type !== 'gaussian') {
|
||||||
throw new Error('Only gaussian noise is supported at the moment');
|
throw new Error('Only gaussian noise is supported at the moment');
|
||||||
}
|
}
|
||||||
|
inputDescriptor.createNoiseType = inputOptions.create.noise.type;
|
||||||
if (!is.inRange(inputOptions.create.channels, 1, 4)) {
|
if (!is.inRange(inputOptions.create.channels, 1, 4)) {
|
||||||
throw is.invalidParameterError('create.channels', 'number between 1 and 4', inputOptions.create.channels);
|
throw is.invalidParameterError('create.channels', 'number between 1 and 4', inputOptions.create.channels);
|
||||||
}
|
}
|
||||||
inputDescriptor.createNoiseType = inputOptions.create.noise.type;
|
inputDescriptor.createNoiseMean = 128;
|
||||||
if (is.number(inputOptions.create.noise.mean) && is.inRange(inputOptions.create.noise.mean, 0, 10000)) {
|
if (is.defined(inputOptions.create.noise.mean)) {
|
||||||
inputDescriptor.createNoiseMean = inputOptions.create.noise.mean;
|
if (is.number(inputOptions.create.noise.mean) && is.inRange(inputOptions.create.noise.mean, 0, 10000)) {
|
||||||
} else {
|
inputDescriptor.createNoiseMean = inputOptions.create.noise.mean;
|
||||||
throw is.invalidParameterError('create.noise.mean', 'number between 0 and 10000', inputOptions.create.noise.mean);
|
} else {
|
||||||
|
throw is.invalidParameterError('create.noise.mean', 'number between 0 and 10000', inputOptions.create.noise.mean);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (is.number(inputOptions.create.noise.sigma) && is.inRange(inputOptions.create.noise.sigma, 0, 10000)) {
|
inputDescriptor.createNoiseSigma = 30;
|
||||||
inputDescriptor.createNoiseSigma = inputOptions.create.noise.sigma;
|
if (is.defined(inputOptions.create.noise.sigma)) {
|
||||||
} else {
|
if (is.number(inputOptions.create.noise.sigma) && is.inRange(inputOptions.create.noise.sigma, 0, 10000)) {
|
||||||
throw is.invalidParameterError('create.noise.sigma', 'number between 0 and 10000', inputOptions.create.noise.sigma);
|
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)) {
|
} else if (is.defined(inputOptions.create.background)) {
|
||||||
if (!is.inRange(inputOptions.create.channels, 3, 4)) {
|
if (!is.inRange(inputOptions.create.channels, 3, 4)) {
|
||||||
throw is.invalidParameterError('create.channels', 'number between 3 and 4', inputOptions.create.channels);
|
throw is.invalidParameterError('create.channels', 'number between 3 and 4', inputOptions.create.channels);
|
||||||
}
|
}
|
||||||
const background = color(inputOptions.create.background);
|
inputDescriptor.createBackground = this._getBackgroundColourOption(inputOptions.create.background);
|
||||||
inputDescriptor.createBackground = [
|
|
||||||
background.red(),
|
|
||||||
background.green(),
|
|
||||||
background.blue(),
|
|
||||||
Math.round(background.alpha() * 255)
|
|
||||||
];
|
|
||||||
} else {
|
} else {
|
||||||
throw new Error('Expected valid noise or background to create a new input image');
|
throw new Error('Expected valid noise or background to create a new input image');
|
||||||
}
|
}
|
||||||
@@ -279,17 +407,17 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(inputOptions.text.width)) {
|
if (is.defined(inputOptions.text.width)) {
|
||||||
if (is.number(inputOptions.text.width)) {
|
if (is.integer(inputOptions.text.width) && inputOptions.text.width > 0) {
|
||||||
inputDescriptor.textWidth = inputOptions.text.width;
|
inputDescriptor.textWidth = inputOptions.text.width;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('text.textWidth', 'number', inputOptions.text.width);
|
throw is.invalidParameterError('text.width', 'positive integer', inputOptions.text.width);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(inputOptions.text.height)) {
|
if (is.defined(inputOptions.text.height)) {
|
||||||
if (is.number(inputOptions.text.height)) {
|
if (is.integer(inputOptions.text.height) && inputOptions.text.height > 0) {
|
||||||
inputDescriptor.textHeight = inputOptions.text.height;
|
inputDescriptor.textHeight = inputOptions.text.height;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('text.height', 'number', inputOptions.text.height);
|
throw is.invalidParameterError('text.height', 'positive integer', inputOptions.text.height);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(inputOptions.text.align)) {
|
if (is.defined(inputOptions.text.align)) {
|
||||||
@@ -307,10 +435,10 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(inputOptions.text.dpi)) {
|
if (is.defined(inputOptions.text.dpi)) {
|
||||||
if (is.number(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 100000)) {
|
if (is.integer(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 1000000)) {
|
||||||
inputDescriptor.textDpi = inputOptions.text.dpi;
|
inputDescriptor.textDpi = inputOptions.text.dpi;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('text.dpi', 'number between 1 and 100000', inputOptions.text.dpi);
|
throw is.invalidParameterError('text.dpi', 'integer between 1 and 1000000', inputOptions.text.dpi);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(inputOptions.text.rgba)) {
|
if (is.defined(inputOptions.text.rgba)) {
|
||||||
@@ -321,10 +449,17 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(inputOptions.text.spacing)) {
|
if (is.defined(inputOptions.text.spacing)) {
|
||||||
if (is.number(inputOptions.text.spacing)) {
|
if (is.integer(inputOptions.text.spacing) && is.inRange(inputOptions.text.spacing, -1000000, 1000000)) {
|
||||||
inputDescriptor.textSpacing = inputOptions.text.spacing;
|
inputDescriptor.textSpacing = inputOptions.text.spacing;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('text.spacing', 'number', inputOptions.text.spacing);
|
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;
|
delete inputDescriptor.buffer;
|
||||||
@@ -332,6 +467,51 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
|||||||
throw new Error('Expected a valid string to create an image with text.');
|
throw new Error('Expected a valid string to create an image with text.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Join images together
|
||||||
|
if (is.defined(inputOptions.join)) {
|
||||||
|
if (is.defined(this.options.join)) {
|
||||||
|
if (is.defined(inputOptions.join.animated)) {
|
||||||
|
if (is.bool(inputOptions.join.animated)) {
|
||||||
|
inputDescriptor.joinAnimated = inputOptions.join.animated;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('join.animated', 'boolean', inputOptions.join.animated);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (is.defined(inputOptions.join.across)) {
|
||||||
|
if (is.integer(inputOptions.join.across) && is.inRange(inputOptions.join.across, 1, 1000000)) {
|
||||||
|
inputDescriptor.joinAcross = inputOptions.join.across;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('join.across', 'integer between 1 and 100000', inputOptions.join.across);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (is.defined(inputOptions.join.shim)) {
|
||||||
|
if (is.integer(inputOptions.join.shim) && is.inRange(inputOptions.join.shim, 0, 1000000)) {
|
||||||
|
inputDescriptor.joinShim = inputOptions.join.shim;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('join.shim', 'integer between 0 and 100000', inputOptions.join.shim);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (is.defined(inputOptions.join.background)) {
|
||||||
|
inputDescriptor.joinBackground = this._getBackgroundColourOption(inputOptions.join.background);
|
||||||
|
}
|
||||||
|
if (is.defined(inputOptions.join.halign)) {
|
||||||
|
if (is.string(inputOptions.join.halign) && is.string(this.constructor.align[inputOptions.join.halign])) {
|
||||||
|
inputDescriptor.joinHalign = this.constructor.align[inputOptions.join.halign];
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('join.halign', 'valid alignment', inputOptions.join.halign);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (is.defined(inputOptions.join.valign)) {
|
||||||
|
if (is.string(inputOptions.join.valign) && is.string(this.constructor.align[inputOptions.join.valign])) {
|
||||||
|
inputDescriptor.joinValign = this.constructor.align[inputOptions.join.valign];
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('join.valign', 'valid alignment', inputOptions.join.valign);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new Error('Expected input to be an array of images to join');
|
||||||
|
}
|
||||||
|
}
|
||||||
} else if (is.defined(inputOptions)) {
|
} else if (is.defined(inputOptions)) {
|
||||||
throw new Error('Invalid input options ' + inputOptions);
|
throw new Error('Invalid input options ' + inputOptions);
|
||||||
}
|
}
|
||||||
@@ -387,8 +567,9 @@ function _isStreamInput () {
|
|||||||
/**
|
/**
|
||||||
* Fast access to (uncached) image metadata without decoding any compressed pixel data.
|
* Fast access to (uncached) image metadata without decoding any compressed pixel data.
|
||||||
*
|
*
|
||||||
* This is taken from the header of the input image.
|
* This is read from the header of the input image.
|
||||||
* It does not include operations, such as resize, to be applied to the output image.
|
* It does not 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
|
* Dimensions in the response will respect the `page` and `pages` properties of the
|
||||||
* {@link /api-constructor#parameters|constructor parameters}.
|
* {@link /api-constructor#parameters|constructor parameters}.
|
||||||
@@ -405,6 +586,8 @@ function _isStreamInput () {
|
|||||||
* - `density`: Number of pixels per inch (DPI), if present
|
* - `density`: Number of pixels per inch (DPI), if present
|
||||||
* - `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK
|
* - `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK
|
||||||
* - `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan
|
* - `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan
|
||||||
|
* - `isPalette`: Boolean indicating whether the image is palette-based (GIF, PNG).
|
||||||
|
* - `bitsPerSample`: Number of bits per sample for each channel (GIF, PNG, HEIF).
|
||||||
* - `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP
|
* - `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP
|
||||||
* - `pageHeight`: Number of pixels high each page in a multi-page image will be.
|
* - `pageHeight`: Number of pixels high each page in a multi-page image will be.
|
||||||
* - `loop`: Number of times to loop an animated image, zero refers to a continuous loop.
|
* - `loop`: Number of times to loop an animated image, zero refers to a continuous loop.
|
||||||
@@ -412,7 +595,7 @@ function _isStreamInput () {
|
|||||||
* - `pagePrimary`: Number of the primary page in a HEIF image
|
* - `pagePrimary`: Number of the primary page in a HEIF image
|
||||||
* - `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide
|
* - `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide
|
||||||
* - `subifds`: Number of Sub Image File Directories in an OME-TIFF image
|
* - `subifds`: Number of Sub Image File Directories in an OME-TIFF image
|
||||||
* - `background`: Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value
|
* - `background`: Default background colour, if present, for PNG (bKGD) and GIF images
|
||||||
* - `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC)
|
* - `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC)
|
||||||
* - `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present
|
* - `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present
|
||||||
* - `hasProfile`: Boolean indicating the presence of an embedded ICC profile
|
* - `hasProfile`: Boolean indicating the presence of an embedded ICC profile
|
||||||
@@ -422,7 +605,10 @@ function _isStreamInput () {
|
|||||||
* - `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present
|
* - `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present
|
||||||
* - `iptc`: Buffer containing raw IPTC data, if present
|
* - `iptc`: Buffer containing raw IPTC data, if present
|
||||||
* - `xmp`: Buffer containing raw XMP data, if present
|
* - `xmp`: Buffer containing raw XMP data, if present
|
||||||
|
* - `xmpAsString`: String containing XMP data, if valid UTF-8.
|
||||||
* - `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present
|
* - `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present
|
||||||
|
* - `formatMagick`: String containing format for images loaded via *magick
|
||||||
|
* - `comments`: Array of keyword/text pairs representing PNG text blocks, if present.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* const metadata = await sharp(input).metadata();
|
* const metadata = await sharp(input).metadata();
|
||||||
@@ -442,49 +628,61 @@ function _isStreamInput () {
|
|||||||
* });
|
* });
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* // Based on EXIF rotation metadata, get the right-side-up width and height:
|
* // Get dimensions taking EXIF Orientation into account.
|
||||||
*
|
* const { autoOrient } = await sharp(input).metadata();
|
||||||
* const size = getNormalSize(await sharp(input).metadata());
|
* const { width, height } = autoOrient;
|
||||||
*
|
|
||||||
* function getNormalSize({ width, height, orientation }) {
|
|
||||||
* return (orientation || 0) >= 5
|
|
||||||
* ? { width: height, height: width }
|
|
||||||
* : { width, height };
|
|
||||||
* }
|
|
||||||
*
|
*
|
||||||
* @param {Function} [callback] - called with the arguments `(err, metadata)`
|
* @param {Function} [callback] - called with the arguments `(err, metadata)`
|
||||||
* @returns {Promise<Object>|Sharp}
|
* @returns {Promise<Object>|Sharp}
|
||||||
*/
|
*/
|
||||||
function metadata (callback) {
|
function metadata (callback) {
|
||||||
|
const stack = Error();
|
||||||
if (is.fn(callback)) {
|
if (is.fn(callback)) {
|
||||||
if (this._isStreamInput()) {
|
if (this._isStreamInput()) {
|
||||||
this.on('finish', () => {
|
this.on('finish', () => {
|
||||||
this._flattenBufferIn();
|
this._flattenBufferIn();
|
||||||
sharp.metadata(this.options, callback);
|
sharp.metadata(this.options, (err, metadata) => {
|
||||||
|
if (err) {
|
||||||
|
callback(is.nativeError(err, stack));
|
||||||
|
} else {
|
||||||
|
callback(null, metadata);
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
sharp.metadata(this.options, callback);
|
sharp.metadata(this.options, (err, metadata) => {
|
||||||
|
if (err) {
|
||||||
|
callback(is.nativeError(err, stack));
|
||||||
|
} else {
|
||||||
|
callback(null, metadata);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
} else {
|
} else {
|
||||||
if (this._isStreamInput()) {
|
if (this._isStreamInput()) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
this.on('finish', () => {
|
const finished = () => {
|
||||||
this._flattenBufferIn();
|
this._flattenBufferIn();
|
||||||
sharp.metadata(this.options, (err, metadata) => {
|
sharp.metadata(this.options, (err, metadata) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(is.nativeError(err, stack));
|
||||||
} else {
|
} else {
|
||||||
resolve(metadata);
|
resolve(metadata);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
};
|
||||||
|
if (this.writableFinished) {
|
||||||
|
finished();
|
||||||
|
} else {
|
||||||
|
this.once('finish', finished);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
sharp.metadata(this.options, (err, metadata) => {
|
sharp.metadata(this.options, (err, metadata) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(is.nativeError(err, stack));
|
||||||
} else {
|
} else {
|
||||||
resolve(metadata);
|
resolve(metadata);
|
||||||
}
|
}
|
||||||
@@ -540,14 +738,27 @@ function metadata (callback) {
|
|||||||
* @returns {Promise<Object>}
|
* @returns {Promise<Object>}
|
||||||
*/
|
*/
|
||||||
function stats (callback) {
|
function stats (callback) {
|
||||||
|
const stack = Error();
|
||||||
if (is.fn(callback)) {
|
if (is.fn(callback)) {
|
||||||
if (this._isStreamInput()) {
|
if (this._isStreamInput()) {
|
||||||
this.on('finish', () => {
|
this.on('finish', () => {
|
||||||
this._flattenBufferIn();
|
this._flattenBufferIn();
|
||||||
sharp.stats(this.options, callback);
|
sharp.stats(this.options, (err, stats) => {
|
||||||
|
if (err) {
|
||||||
|
callback(is.nativeError(err, stack));
|
||||||
|
} else {
|
||||||
|
callback(null, stats);
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
sharp.stats(this.options, callback);
|
sharp.stats(this.options, (err, stats) => {
|
||||||
|
if (err) {
|
||||||
|
callback(is.nativeError(err, stack));
|
||||||
|
} else {
|
||||||
|
callback(null, stats);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
} else {
|
} else {
|
||||||
@@ -557,7 +768,7 @@ function stats (callback) {
|
|||||||
this._flattenBufferIn();
|
this._flattenBufferIn();
|
||||||
sharp.stats(this.options, (err, stats) => {
|
sharp.stats(this.options, (err, stats) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(is.nativeError(err, stack));
|
||||||
} else {
|
} else {
|
||||||
resolve(stats);
|
resolve(stats);
|
||||||
}
|
}
|
||||||
@@ -568,7 +779,7 @@ function stats (callback) {
|
|||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
sharp.stats(this.options, (err, stats) => {
|
sharp.stats(this.options, (err, stats) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(is.nativeError(err, stack));
|
||||||
} else {
|
} else {
|
||||||
resolve(stats);
|
resolve(stats);
|
||||||
}
|
}
|
||||||
@@ -580,6 +791,7 @@ function stats (callback) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Decorate the Sharp prototype with input-related functions.
|
* Decorate the Sharp prototype with input-related functions.
|
||||||
|
* @module Sharp
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
module.exports = function (Sharp) {
|
module.exports = function (Sharp) {
|
||||||
|
|||||||
54
lib/is.js
@@ -1,3 +1,6 @@
|
|||||||
|
// Copyright 2013 Lovell Fuller and others.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -71,6 +74,14 @@ const typedArray = function (val) {
|
|||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Is this value an ArrayBuffer object?
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
const arrayBuffer = function (val) {
|
||||||
|
return val instanceof ArrayBuffer;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Is this value a non-empty string?
|
* Is this value a non-empty string?
|
||||||
* @private
|
* @private
|
||||||
@@ -126,18 +137,33 @@ const invalidParameterError = function (name, expected, actual) {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = {
|
/**
|
||||||
defined: defined,
|
* Ensures an Error from C++ contains a JS stack.
|
||||||
object: object,
|
*
|
||||||
plainObject: plainObject,
|
* @param {Error} native - Error with message from C++.
|
||||||
fn: fn,
|
* @param {Error} context - Error with stack from JS.
|
||||||
bool: bool,
|
* @returns {Error} Error with message and stack.
|
||||||
buffer: buffer,
|
* @private
|
||||||
typedArray: typedArray,
|
*/
|
||||||
string: string,
|
const nativeError = function (native, context) {
|
||||||
number: number,
|
context.message = native.message;
|
||||||
integer: integer,
|
return context;
|
||||||
inRange: inRange,
|
};
|
||||||
inArray: inArray,
|
|
||||||
invalidParameterError: invalidParameterError
|
module.exports = {
|
||||||
|
defined,
|
||||||
|
object,
|
||||||
|
plainObject,
|
||||||
|
fn,
|
||||||
|
bool,
|
||||||
|
buffer,
|
||||||
|
typedArray,
|
||||||
|
arrayBuffer,
|
||||||
|
string,
|
||||||
|
number,
|
||||||
|
integer,
|
||||||
|
inRange,
|
||||||
|
inArray,
|
||||||
|
invalidParameterError,
|
||||||
|
nativeError
|
||||||
};
|
};
|
||||||
|
|||||||
189
lib/libvips.js
@@ -1,52 +1,34 @@
|
|||||||
|
// Copyright 2013 Lovell Fuller and others.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const fs = require('fs');
|
const { spawnSync } = require('node:child_process');
|
||||||
const os = require('os');
|
const { createHash } = require('node:crypto');
|
||||||
const path = require('path');
|
|
||||||
const spawnSync = require('child_process').spawnSync;
|
|
||||||
const semverCoerce = require('semver/functions/coerce');
|
const semverCoerce = require('semver/functions/coerce');
|
||||||
const semverGreaterThanOrEqualTo = require('semver/functions/gte');
|
const semverGreaterThanOrEqualTo = require('semver/functions/gte');
|
||||||
|
const semverSatisfies = require('semver/functions/satisfies');
|
||||||
|
const detectLibc = require('detect-libc');
|
||||||
|
|
||||||
const platform = require('./platform');
|
const { config, engines, optionalDependencies } = require('../package.json');
|
||||||
const { config } = require('../package.json');
|
|
||||||
|
|
||||||
const env = process.env;
|
const minimumLibvipsVersionLabelled = process.env.npm_package_config_libvips || /* istanbul ignore next */
|
||||||
const minimumLibvipsVersionLabelled = env.npm_package_config_libvips || /* istanbul ignore next */
|
|
||||||
config.libvips;
|
config.libvips;
|
||||||
const minimumLibvipsVersion = semverCoerce(minimumLibvipsVersionLabelled).version;
|
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 = {
|
const spawnSyncOptions = {
|
||||||
encoding: 'utf8',
|
encoding: 'utf8',
|
||||||
shell: true
|
shell: true
|
||||||
};
|
};
|
||||||
|
|
||||||
const vendorPath = path.join(__dirname, '..', 'vendor', minimumLibvipsVersion, platform());
|
const log = (item) => {
|
||||||
|
|
||||||
const mkdirSync = function (dirPath) {
|
|
||||||
try {
|
|
||||||
fs.mkdirSync(dirPath, { recursive: true });
|
|
||||||
} catch (err) {
|
|
||||||
/* istanbul ignore next */
|
|
||||||
if (err.code !== 'EEXIST') {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const cachePath = function () {
|
|
||||||
const npmCachePath = env.npm_config_cache || /* istanbul ignore next */
|
|
||||||
(env.APPDATA ? path.join(env.APPDATA, 'npm-cache') : path.join(os.homedir(), '.npm'));
|
|
||||||
mkdirSync(npmCachePath);
|
|
||||||
const libvipsCachePath = path.join(npmCachePath, '_libvips');
|
|
||||||
mkdirSync(libvipsCachePath);
|
|
||||||
return libvipsCachePath;
|
|
||||||
};
|
|
||||||
|
|
||||||
const integrity = function (platformAndArch) {
|
|
||||||
return env[`npm_package_config_integrity_${platformAndArch.replace('-', '_')}`] || config.integrity[platformAndArch];
|
|
||||||
};
|
|
||||||
|
|
||||||
const log = function (item) {
|
|
||||||
if (item instanceof Error) {
|
if (item instanceof Error) {
|
||||||
console.error(`sharp: Installation error: ${item.message}`);
|
console.error(`sharp: Installation error: ${item.message}`);
|
||||||
} else {
|
} else {
|
||||||
@@ -54,7 +36,70 @@ const log = function (item) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const isRosetta = function () {
|
/* 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 */
|
/* istanbul ignore next */
|
||||||
if (process.platform === 'darwin' && process.arch === 'x64') {
|
if (process.platform === 'darwin' && process.arch === 'x64') {
|
||||||
const translated = spawnSync('sysctl sysctl.proc_translated', spawnSyncOptions).stdout;
|
const translated = spawnSync('sysctl sysctl.proc_translated', spawnSyncOptions).stdout;
|
||||||
@@ -63,12 +108,32 @@ const isRosetta = function () {
|
|||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
const globalLibvipsVersion = function () {
|
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') {
|
if (process.platform !== 'win32') {
|
||||||
const globalLibvipsVersion = spawnSync('pkg-config --modversion vips-cpp', {
|
const globalLibvipsVersion = spawnSync('pkg-config --modversion vips-cpp', {
|
||||||
...spawnSyncOptions,
|
...spawnSyncOptions,
|
||||||
env: {
|
env: {
|
||||||
...env,
|
...process.env,
|
||||||
PKG_CONFIG_PATH: pkgConfigPath()
|
PKG_CONFIG_PATH: pkgConfigPath()
|
||||||
}
|
}
|
||||||
}).stdout;
|
}).stdout;
|
||||||
@@ -79,17 +144,8 @@ const globalLibvipsVersion = function () {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const hasVendoredLibvips = function () {
|
|
||||||
return fs.existsSync(vendorPath);
|
|
||||||
};
|
|
||||||
|
|
||||||
/* istanbul ignore next */
|
/* istanbul ignore next */
|
||||||
const removeVendoredLibvips = function () {
|
const pkgConfigPath = () => {
|
||||||
const rm = fs.rmSync ? fs.rmSync : fs.rmdirSync;
|
|
||||||
rm(vendorPath, { recursive: true, maxRetries: 3, force: true });
|
|
||||||
};
|
|
||||||
|
|
||||||
const pkgConfigPath = function () {
|
|
||||||
if (process.platform !== 'win32') {
|
if (process.platform !== 'win32') {
|
||||||
const brewPkgConfigPath = spawnSync(
|
const brewPkgConfigPath = spawnSync(
|
||||||
'which brew >/dev/null 2>&1 && brew environment --plain | grep PKG_CONFIG_LIBDIR | cut -d" " -f2',
|
'which brew >/dev/null 2>&1 && brew environment --plain | grep PKG_CONFIG_LIBDIR | cut -d" " -f2',
|
||||||
@@ -97,7 +153,7 @@ const pkgConfigPath = function () {
|
|||||||
).stdout || '';
|
).stdout || '';
|
||||||
return [
|
return [
|
||||||
brewPkgConfigPath.trim(),
|
brewPkgConfigPath.trim(),
|
||||||
env.PKG_CONFIG_PATH,
|
process.env.PKG_CONFIG_PATH,
|
||||||
'/usr/local/lib/pkgconfig',
|
'/usr/local/lib/pkgconfig',
|
||||||
'/usr/lib/pkgconfig',
|
'/usr/lib/pkgconfig',
|
||||||
'/usr/local/libdata/pkgconfig',
|
'/usr/local/libdata/pkgconfig',
|
||||||
@@ -108,13 +164,23 @@ const pkgConfigPath = function () {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const useGlobalLibvips = function () {
|
const skipSearch = (status, reason, logger) => {
|
||||||
if (Boolean(env.SHARP_IGNORE_GLOBAL_LIBVIPS) === true) {
|
if (logger) {
|
||||||
return false;
|
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 */
|
/* istanbul ignore next */
|
||||||
if (isRosetta()) {
|
if (isRosetta()) {
|
||||||
return false;
|
return skipSearch(false, 'Rosetta', logger);
|
||||||
}
|
}
|
||||||
const globalVipsVersion = globalLibvipsVersion();
|
const globalVipsVersion = globalLibvipsVersion();
|
||||||
return !!globalVipsVersion && /* istanbul ignore next */
|
return !!globalVipsVersion && /* istanbul ignore next */
|
||||||
@@ -123,14 +189,17 @@ const useGlobalLibvips = function () {
|
|||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
minimumLibvipsVersion,
|
minimumLibvipsVersion,
|
||||||
minimumLibvipsVersionLabelled,
|
prebuiltPlatforms,
|
||||||
cachePath,
|
buildPlatformArch,
|
||||||
integrity,
|
buildSharpLibvipsIncludeDir,
|
||||||
|
buildSharpLibvipsCPlusPlusDir,
|
||||||
|
buildSharpLibvipsLibDir,
|
||||||
|
isUnsupportedNodeRuntime,
|
||||||
|
runtimePlatformArch,
|
||||||
log,
|
log,
|
||||||
|
yarnLocator,
|
||||||
|
spawnRebuild,
|
||||||
globalLibvipsVersion,
|
globalLibvipsVersion,
|
||||||
hasVendoredLibvips,
|
|
||||||
removeVendoredLibvips,
|
|
||||||
pkgConfigPath,
|
pkgConfigPath,
|
||||||
useGlobalLibvips,
|
useGlobalLibvips
|
||||||
mkdirSync
|
|
||||||
};
|
};
|
||||||
|
|||||||
396
lib/operation.js
@@ -1,41 +1,42 @@
|
|||||||
|
// Copyright 2013 Lovell Fuller and others.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const color = require('color');
|
|
||||||
const is = require('./is');
|
const is = require('./is');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Rotate the output image by either an explicit angle
|
* How accurate an operation should be.
|
||||||
* or auto-orient based on the EXIF `Orientation` tag.
|
* @member
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
const vipsPrecision = {
|
||||||
|
integer: 'integer',
|
||||||
|
float: 'float',
|
||||||
|
approximate: 'approximate'
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rotate the output image.
|
||||||
*
|
*
|
||||||
* If an angle is provided, it is converted to a valid positive degree rotation.
|
* The provided angle is converted to a valid positive degree rotation.
|
||||||
* For example, `-450` will produce a 270deg rotation.
|
* For example, `-450` will produce a 270 degree rotation.
|
||||||
*
|
*
|
||||||
* When rotating by an angle other than a multiple of 90,
|
* When rotating by an angle other than a multiple of 90,
|
||||||
* the background colour can be provided with the `background` option.
|
* the background colour can be provided with the `background` option.
|
||||||
*
|
*
|
||||||
* If no angle is provided, it is determined from the EXIF data.
|
* For backwards compatibility, if no angle is provided, `.autoOrient()` will be called.
|
||||||
* Mirroring is supported and may infer the use of a flip operation.
|
|
||||||
*
|
*
|
||||||
* The use of `rotate` implies the removal of the EXIF `Orientation` tag, if any.
|
* Only one rotation can occur per pipeline (aside from an initial call without
|
||||||
|
* arguments to orient via EXIF data). Previous calls to `rotate` in the same
|
||||||
|
* pipeline will be ignored.
|
||||||
*
|
*
|
||||||
* Only one rotation can occur per pipeline.
|
* Multi-page images can only be rotated by 180 degrees.
|
||||||
* Previous calls to `rotate` in the same pipeline will be ignored.
|
|
||||||
*
|
*
|
||||||
* Method order is important when rotating, resizing and/or extracting regions,
|
* 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)`.
|
* for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* const pipeline = sharp()
|
|
||||||
* .rotate()
|
|
||||||
* .resize(null, 200)
|
|
||||||
* .toBuffer(function (err, outputBuffer, info) {
|
|
||||||
* // outputBuffer contains 200px high JPEG image data,
|
|
||||||
* // auto-rotated using EXIF Orientation tag
|
|
||||||
* // info.width and info.height contain the dimensions of the resized image
|
|
||||||
* });
|
|
||||||
* readableStream.pipe(pipeline);
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* const rotateThenResize = await sharp(input)
|
* const rotateThenResize = await sharp(input)
|
||||||
* .rotate(90)
|
* .rotate(90)
|
||||||
* .resize({ width: 16, height: 8, fit: 'fill' })
|
* .resize({ width: 16, height: 8, fit: 'fill' })
|
||||||
@@ -52,23 +53,20 @@ const is = require('./is');
|
|||||||
* @throws {Error} Invalid parameters
|
* @throws {Error} Invalid parameters
|
||||||
*/
|
*/
|
||||||
function rotate (angle, options) {
|
function rotate (angle, options) {
|
||||||
if (this.options.useExifOrientation || this.options.angle || this.options.rotationAngle) {
|
|
||||||
this.options.debuglog('ignoring previous rotate options');
|
|
||||||
}
|
|
||||||
if (!is.defined(angle)) {
|
if (!is.defined(angle)) {
|
||||||
this.options.useExifOrientation = true;
|
return this.autoOrient();
|
||||||
} else if (is.integer(angle) && !(angle % 90)) {
|
}
|
||||||
|
if (this.options.angle || this.options.rotationAngle) {
|
||||||
|
this.options.debuglog('ignoring previous rotate options');
|
||||||
|
this.options.angle = 0;
|
||||||
|
this.options.rotationAngle = 0;
|
||||||
|
}
|
||||||
|
if (is.integer(angle) && !(angle % 90)) {
|
||||||
this.options.angle = angle;
|
this.options.angle = angle;
|
||||||
} else if (is.number(angle)) {
|
} else if (is.number(angle)) {
|
||||||
this.options.rotationAngle = angle;
|
this.options.rotationAngle = angle;
|
||||||
if (is.object(options) && options.background) {
|
if (is.object(options) && options.background) {
|
||||||
const backgroundColour = color(options.background);
|
this._setBackgroundColourOption('rotationBackground', options.background);
|
||||||
this.options.rotationBackground = [
|
|
||||||
backgroundColour.red(),
|
|
||||||
backgroundColour.green(),
|
|
||||||
backgroundColour.blue(),
|
|
||||||
Math.round(backgroundColour.alpha() * 255)
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('angle', 'numeric', angle);
|
throw is.invalidParameterError('angle', 'numeric', angle);
|
||||||
@@ -77,8 +75,38 @@ function rotate (angle, options) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Flip the image about the vertical Y axis. This always occurs before rotation, if any.
|
* Auto-orient based on the EXIF `Orientation` tag, then remove the tag.
|
||||||
* The use of `flip` implies the removal of the EXIF `Orientation` tag, if any.
|
* Mirroring is supported and may infer the use of a flip operation.
|
||||||
|
*
|
||||||
|
* Previous or subsequent use of `rotate(angle)` and either `flip()` or `flop()`
|
||||||
|
* will logically occur after auto-orientation, regardless of call order.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const output = await sharp(input).autoOrient().toBuffer();
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const pipeline = sharp()
|
||||||
|
* .autoOrient()
|
||||||
|
* .resize(null, 200)
|
||||||
|
* .toBuffer(function (err, outputBuffer, info) {
|
||||||
|
* // outputBuffer contains 200px high JPEG image data,
|
||||||
|
* // auto-oriented using EXIF Orientation tag
|
||||||
|
* // info.width and info.height contain the dimensions of the resized image
|
||||||
|
* });
|
||||||
|
* readableStream.pipe(pipeline);
|
||||||
|
*
|
||||||
|
* @returns {Sharp}
|
||||||
|
*/
|
||||||
|
function autoOrient () {
|
||||||
|
this.options.input.autoOrient = true;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mirror the image vertically (up-down) about the x-axis.
|
||||||
|
* This always occurs before rotation, if any.
|
||||||
|
*
|
||||||
|
* This operation does not work correctly with multi-page images.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* const output = await sharp(input).flip().toBuffer();
|
* const output = await sharp(input).flip().toBuffer();
|
||||||
@@ -92,8 +120,8 @@ function flip (flip) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Flop the image about the horizontal X axis. This always occurs before rotation, if any.
|
* Mirror the image horizontally (left-right) about the y-axis.
|
||||||
* The use of `flop` implies the removal of the EXIF `Orientation` tag, if any.
|
* This always occurs before rotation, if any.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* const output = await sharp(input).flop().toBuffer();
|
* const output = await sharp(input).flop().toBuffer();
|
||||||
@@ -110,8 +138,8 @@ function flop (flop) {
|
|||||||
* Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.
|
* Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.
|
||||||
*
|
*
|
||||||
* You must provide an array of length 4 or a 2x2 affine transformation matrix.
|
* You must provide an array of length 4 or a 2x2 affine transformation matrix.
|
||||||
* By default, new pixels are filled with a black background. You can provide a background color with the `background` option.
|
* By default, new pixels are filled with a black background. You can provide a background colour with the `background` option.
|
||||||
* A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolator` Object e.g. `sharp.interpolator.nohalo`.
|
* A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`.
|
||||||
*
|
*
|
||||||
* In the case of a 2x2 matrix, the transform is:
|
* In the case of a 2x2 matrix, the transform is:
|
||||||
* - X = `matrix[0, 0]` \* (x + `idx`) + `matrix[0, 1]` \* (y + `idy`) + `odx`
|
* - X = `matrix[0, 0]` \* (x + `idx`) + `matrix[0, 1]` \* (y + `idy`) + `odx`
|
||||||
@@ -128,7 +156,7 @@ function flop (flop) {
|
|||||||
* const pipeline = sharp()
|
* const pipeline = sharp()
|
||||||
* .affine([[1, 0.3], [0.1, 0.7]], {
|
* .affine([[1, 0.3], [0.1, 0.7]], {
|
||||||
* background: 'white',
|
* background: 'white',
|
||||||
* interpolate: sharp.interpolators.nohalo
|
* interpolator: sharp.interpolators.nohalo
|
||||||
* })
|
* })
|
||||||
* .toBuffer((err, outputBuffer, info) => {
|
* .toBuffer((err, outputBuffer, info) => {
|
||||||
* // outputBuffer contains the transformed image
|
* // outputBuffer contains the transformed image
|
||||||
@@ -205,9 +233,11 @@ function affine (matrix, options) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Sharpen the image.
|
* Sharpen the image.
|
||||||
|
*
|
||||||
* When used without parameters, performs a fast, mild sharpen of the output image.
|
* When used without parameters, performs a fast, mild sharpen of the output image.
|
||||||
|
*
|
||||||
* When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space.
|
* When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space.
|
||||||
* Separate control over the level of sharpening in "flat" and "jagged" areas is available.
|
* Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available.
|
||||||
*
|
*
|
||||||
* See {@link https://www.libvips.org/API/current/libvips-convolution.html#vips-sharpen|libvips sharpen} operation.
|
* See {@link https://www.libvips.org/API/current/libvips-convolution.html#vips-sharpen|libvips sharpen} operation.
|
||||||
*
|
*
|
||||||
@@ -229,13 +259,13 @@ function affine (matrix, options) {
|
|||||||
* })
|
* })
|
||||||
* .toBuffer();
|
* .toBuffer();
|
||||||
*
|
*
|
||||||
* @param {Object|number} [options] - if present, is an Object with attributes or (deprecated) a number for `options.sigma`.
|
* @param {Object|number} [options] - if present, is an Object with attributes
|
||||||
* @param {number} [options.sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
|
* @param {number} [options.sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`, between 0.000001 and 10
|
||||||
* @param {number} [options.m1=1.0] - the level of sharpening to apply to "flat" areas.
|
* @param {number} [options.m1=1.0] - the level of sharpening to apply to "flat" areas, between 0 and 1000000
|
||||||
* @param {number} [options.m2=2.0] - the level of sharpening to apply to "jagged" areas.
|
* @param {number} [options.m2=2.0] - the level of sharpening to apply to "jagged" areas, between 0 and 1000000
|
||||||
* @param {number} [options.x1=2.0] - threshold between "flat" and "jagged"
|
* @param {number} [options.x1=2.0] - threshold between "flat" and "jagged", between 0 and 1000000
|
||||||
* @param {number} [options.y2=10.0] - maximum amount of brightening.
|
* @param {number} [options.y2=10.0] - maximum amount of brightening, between 0 and 1000000
|
||||||
* @param {number} [options.y3=20.0] - maximum amount of darkening.
|
* @param {number} [options.y3=20.0] - maximum amount of darkening, between 0 and 1000000
|
||||||
* @param {number} [flat] - (deprecated) see `options.m1`.
|
* @param {number} [flat] - (deprecated) see `options.m1`.
|
||||||
* @param {number} [jagged] - (deprecated) see `options.m2`.
|
* @param {number} [jagged] - (deprecated) see `options.m2`.
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
@@ -268,44 +298,44 @@ function sharpen (options, flat, jagged) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (is.plainObject(options)) {
|
} else if (is.plainObject(options)) {
|
||||||
if (is.number(options.sigma) && is.inRange(options.sigma, 0.01, 10000)) {
|
if (is.number(options.sigma) && is.inRange(options.sigma, 0.000001, 10)) {
|
||||||
this.options.sharpenSigma = options.sigma;
|
this.options.sharpenSigma = options.sigma;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('options.sigma', 'number between 0.01 and 10000', options.sigma);
|
throw is.invalidParameterError('options.sigma', 'number between 0.000001 and 10', options.sigma);
|
||||||
}
|
}
|
||||||
if (is.defined(options.m1)) {
|
if (is.defined(options.m1)) {
|
||||||
if (is.number(options.m1) && is.inRange(options.m1, 0, 10000)) {
|
if (is.number(options.m1) && is.inRange(options.m1, 0, 1000000)) {
|
||||||
this.options.sharpenM1 = options.m1;
|
this.options.sharpenM1 = options.m1;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('options.m1', 'number between 0 and 10000', options.m1);
|
throw is.invalidParameterError('options.m1', 'number between 0 and 1000000', options.m1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(options.m2)) {
|
if (is.defined(options.m2)) {
|
||||||
if (is.number(options.m2) && is.inRange(options.m2, 0, 10000)) {
|
if (is.number(options.m2) && is.inRange(options.m2, 0, 1000000)) {
|
||||||
this.options.sharpenM2 = options.m2;
|
this.options.sharpenM2 = options.m2;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('options.m2', 'number between 0 and 10000', options.m2);
|
throw is.invalidParameterError('options.m2', 'number between 0 and 1000000', options.m2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(options.x1)) {
|
if (is.defined(options.x1)) {
|
||||||
if (is.number(options.x1) && is.inRange(options.x1, 0, 10000)) {
|
if (is.number(options.x1) && is.inRange(options.x1, 0, 1000000)) {
|
||||||
this.options.sharpenX1 = options.x1;
|
this.options.sharpenX1 = options.x1;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('options.x1', 'number between 0 and 10000', options.x1);
|
throw is.invalidParameterError('options.x1', 'number between 0 and 1000000', options.x1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(options.y2)) {
|
if (is.defined(options.y2)) {
|
||||||
if (is.number(options.y2) && is.inRange(options.y2, 0, 10000)) {
|
if (is.number(options.y2) && is.inRange(options.y2, 0, 1000000)) {
|
||||||
this.options.sharpenY2 = options.y2;
|
this.options.sharpenY2 = options.y2;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('options.y2', 'number between 0 and 10000', options.y2);
|
throw is.invalidParameterError('options.y2', 'number between 0 and 1000000', options.y2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(options.y3)) {
|
if (is.defined(options.y3)) {
|
||||||
if (is.number(options.y3) && is.inRange(options.y3, 0, 10000)) {
|
if (is.number(options.y3) && is.inRange(options.y3, 0, 1000000)) {
|
||||||
this.options.sharpenY3 = options.y3;
|
this.options.sharpenY3 = options.y3;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('options.y3', 'number between 0 and 10000', options.y3);
|
throw is.invalidParameterError('options.y3', 'number between 0 and 1000000', options.y3);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -358,23 +388,97 @@ function median (size) {
|
|||||||
* .blur(5)
|
* .blur(5)
|
||||||
* .toBuffer();
|
* .toBuffer();
|
||||||
*
|
*
|
||||||
* @param {number} [sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
|
* @param {Object|number|Boolean} [options]
|
||||||
|
* @param {number} [options.sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
|
||||||
|
* @param {string} [options.precision='integer'] How accurate the operation should be, one of: integer, float, approximate.
|
||||||
|
* @param {number} [options.minAmplitude=0.2] A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask.
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid parameters
|
* @throws {Error} Invalid parameters
|
||||||
*/
|
*/
|
||||||
function blur (sigma) {
|
function blur (options) {
|
||||||
if (!is.defined(sigma)) {
|
let sigma;
|
||||||
|
if (is.number(options)) {
|
||||||
|
sigma = options;
|
||||||
|
} else if (is.plainObject(options)) {
|
||||||
|
if (!is.number(options.sigma)) {
|
||||||
|
throw is.invalidParameterError('options.sigma', 'number between 0.3 and 1000', sigma);
|
||||||
|
}
|
||||||
|
sigma = options.sigma;
|
||||||
|
if ('precision' in options) {
|
||||||
|
if (is.string(vipsPrecision[options.precision])) {
|
||||||
|
this.options.precision = vipsPrecision[options.precision];
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('precision', 'one of: integer, float, approximate', options.precision);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ('minAmplitude' in options) {
|
||||||
|
if (is.number(options.minAmplitude) && is.inRange(options.minAmplitude, 0.001, 1)) {
|
||||||
|
this.options.minAmpl = options.minAmplitude;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('minAmplitude', 'number between 0.001 and 1', options.minAmplitude);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!is.defined(options)) {
|
||||||
// No arguments: default to mild blur
|
// No arguments: default to mild blur
|
||||||
this.options.blurSigma = -1;
|
this.options.blurSigma = -1;
|
||||||
} else if (is.bool(sigma)) {
|
} else if (is.bool(options)) {
|
||||||
// Boolean argument: apply mild blur?
|
// Boolean argument: apply mild blur?
|
||||||
this.options.blurSigma = sigma ? -1 : 0;
|
this.options.blurSigma = options ? -1 : 0;
|
||||||
} else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) {
|
} else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) {
|
||||||
// Numeric argument: specific sigma
|
// Numeric argument: specific sigma
|
||||||
this.options.blurSigma = sigma;
|
this.options.blurSigma = sigma;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('sigma', 'number between 0.3 and 1000', sigma);
|
throw is.invalidParameterError('sigma', 'number between 0.3 and 1000', sigma);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Expand foreground objects using the dilate morphological operator.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const output = await sharp(input)
|
||||||
|
* .dilate()
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
|
* @param {Number} [width=1] dilation width in pixels.
|
||||||
|
* @returns {Sharp}
|
||||||
|
* @throws {Error} Invalid parameters
|
||||||
|
*/
|
||||||
|
function dilate (width) {
|
||||||
|
if (!is.defined(width)) {
|
||||||
|
this.options.dilateWidth = 1;
|
||||||
|
} else if (is.integer(width) && width > 0) {
|
||||||
|
this.options.dilateWidth = width;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('dilate', 'positive integer', dilate);
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shrink foreground objects using the erode morphological operator.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const output = await sharp(input)
|
||||||
|
* .erode()
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
|
* @param {Number} [width=1] erosion width in pixels.
|
||||||
|
* @returns {Sharp}
|
||||||
|
* @throws {Error} Invalid parameters
|
||||||
|
*/
|
||||||
|
function erode (width) {
|
||||||
|
if (!is.defined(width)) {
|
||||||
|
this.options.erodeWidth = 1;
|
||||||
|
} else if (is.integer(width) && width > 0) {
|
||||||
|
this.options.erodeWidth = width;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('erode', 'positive integer', erode);
|
||||||
|
}
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -400,6 +504,32 @@ function flatten (options) {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
* await sharp(rgbInput)
|
||||||
|
* .unflatten()
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* await sharp(rgbInput)
|
||||||
|
* .threshold(128, { grayscale: false }) // converter bright pixels to white
|
||||||
|
* .unflatten()
|
||||||
|
* .toBuffer();
|
||||||
|
*/
|
||||||
|
function unflatten () {
|
||||||
|
this.options.unflatten = true;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of `1/gamma`
|
* 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`.
|
* then increasing the encoding (brighten) post-resize at a factor of `gamma`.
|
||||||
@@ -464,16 +594,50 @@ function negate (options) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Enhance output image contrast by stretching its luminance to cover the full dynamic range.
|
* Enhance output image contrast by stretching its luminance to cover 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.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* const output = await sharp(input).normalise().toBuffer();
|
* const output = await sharp(input)
|
||||||
|
* .normalise()
|
||||||
|
* .toBuffer();
|
||||||
*
|
*
|
||||||
* @param {Boolean} [normalise=true]
|
* @example
|
||||||
|
* const output = await sharp(input)
|
||||||
|
* .normalise({ lower: 0, upper: 100 })
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
|
* @param {Object} [options]
|
||||||
|
* @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed.
|
||||||
|
* @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed.
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
*/
|
*/
|
||||||
function normalise (normalise) {
|
function normalise (options) {
|
||||||
this.options.normalise = is.bool(normalise) ? normalise : true;
|
if (is.plainObject(options)) {
|
||||||
|
if (is.defined(options.lower)) {
|
||||||
|
if (is.number(options.lower) && is.inRange(options.lower, 0, 99)) {
|
||||||
|
this.options.normaliseLower = options.lower;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('lower', 'number between 0 and 99', options.lower);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (is.defined(options.upper)) {
|
||||||
|
if (is.number(options.upper) && is.inRange(options.upper, 1, 100)) {
|
||||||
|
this.options.normaliseUpper = options.upper;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('upper', 'number between 1 and 100', options.upper);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (this.options.normaliseLower >= this.options.normaliseUpper) {
|
||||||
|
throw is.invalidParameterError('range', 'lower to be less than upper',
|
||||||
|
`${this.options.normaliseLower} >= ${this.options.normaliseUpper}`);
|
||||||
|
}
|
||||||
|
this.options.normalise = true;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -481,13 +645,17 @@ function normalise (normalise) {
|
|||||||
* Alternative spelling of normalise.
|
* Alternative spelling of normalise.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* const output = await sharp(input).normalize().toBuffer();
|
* const output = await sharp(input)
|
||||||
|
* .normalize()
|
||||||
|
* .toBuffer();
|
||||||
*
|
*
|
||||||
* @param {Boolean} [normalize=true]
|
* @param {Object} [options]
|
||||||
|
* @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed.
|
||||||
|
* @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed.
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
*/
|
*/
|
||||||
function normalize (normalize) {
|
function normalize (options) {
|
||||||
return this.normalise(normalize);
|
return this.normalise(options);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -507,35 +675,34 @@ function normalize (normalize) {
|
|||||||
* .toBuffer();
|
* .toBuffer();
|
||||||
*
|
*
|
||||||
* @param {Object} options
|
* @param {Object} options
|
||||||
* @param {number} options.width - integer width of the region in pixels.
|
* @param {number} options.width - Integral width of the search window, in pixels.
|
||||||
* @param {number} options.height - integer height of the region in pixels.
|
* @param {number} options.height - Integral height of the search window, in pixels.
|
||||||
* @param {number} [options.maxSlope=3] - maximum value for the slope of the
|
* @param {number} [options.maxSlope=3] - Integral level of brightening, between 0 and 100, where 0 disables contrast limiting.
|
||||||
* cumulative histogram. A value of 0 disables contrast limiting. Valid values
|
|
||||||
* are integers in the range 0-100 (inclusive)
|
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid parameters
|
* @throws {Error} Invalid parameters
|
||||||
*/
|
*/
|
||||||
function clahe (options) {
|
function clahe (options) {
|
||||||
if (!is.plainObject(options)) {
|
if (is.plainObject(options)) {
|
||||||
|
if (is.integer(options.width) && options.width > 0) {
|
||||||
|
this.options.claheWidth = options.width;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('width', 'integer greater than zero', options.width);
|
||||||
|
}
|
||||||
|
if (is.integer(options.height) && options.height > 0) {
|
||||||
|
this.options.claheHeight = options.height;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('height', 'integer greater than zero', options.height);
|
||||||
|
}
|
||||||
|
if (is.defined(options.maxSlope)) {
|
||||||
|
if (is.integer(options.maxSlope) && is.inRange(options.maxSlope, 0, 100)) {
|
||||||
|
this.options.claheMaxSlope = options.maxSlope;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('maxSlope', 'integer between 0 and 100', options.maxSlope);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
throw is.invalidParameterError('options', 'plain object', options);
|
throw is.invalidParameterError('options', 'plain object', options);
|
||||||
}
|
}
|
||||||
if (!('width' in options) || !is.integer(options.width) || options.width <= 0) {
|
|
||||||
throw is.invalidParameterError('width', 'integer above zero', options.width);
|
|
||||||
} else {
|
|
||||||
this.options.claheWidth = options.width;
|
|
||||||
}
|
|
||||||
if (!('height' in options) || !is.integer(options.height) || options.height <= 0) {
|
|
||||||
throw is.invalidParameterError('height', 'integer above zero', options.height);
|
|
||||||
} else {
|
|
||||||
this.options.claheHeight = options.height;
|
|
||||||
}
|
|
||||||
if (!is.defined(options.maxSlope)) {
|
|
||||||
this.options.claheMaxSlope = 3;
|
|
||||||
} else if (!is.integer(options.maxSlope) || options.maxSlope < 0 || options.maxSlope > 100) {
|
|
||||||
throw is.invalidParameterError('maxSlope', 'integer 0-100', options.maxSlope);
|
|
||||||
} else {
|
|
||||||
this.options.claheMaxSlope = options.maxSlope;
|
|
||||||
}
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -698,7 +865,7 @@ function linear (a, b) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Recomb the image with the specified matrix.
|
* Recombine the image with the specified matrix.
|
||||||
*
|
*
|
||||||
* @since 0.21.1
|
* @since 0.21.1
|
||||||
*
|
*
|
||||||
@@ -711,28 +878,26 @@ function linear (a, b) {
|
|||||||
* ])
|
* ])
|
||||||
* .raw()
|
* .raw()
|
||||||
* .toBuffer(function(err, data, info) {
|
* .toBuffer(function(err, data, info) {
|
||||||
* // data contains the raw pixel data after applying the recomb
|
* // data contains the raw pixel data after applying the matrix
|
||||||
* // With this example input, a sepia filter has been applied
|
* // With this example input, a sepia filter has been applied
|
||||||
* });
|
* });
|
||||||
*
|
*
|
||||||
* @param {Array<Array<number>>} inputMatrix - 3x3 Recombination matrix
|
* @param {Array<Array<number>>} inputMatrix - 3x3 or 4x4 Recombination matrix
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid parameters
|
* @throws {Error} Invalid parameters
|
||||||
*/
|
*/
|
||||||
function recomb (inputMatrix) {
|
function recomb (inputMatrix) {
|
||||||
if (!Array.isArray(inputMatrix) || inputMatrix.length !== 3 ||
|
if (!Array.isArray(inputMatrix)) {
|
||||||
inputMatrix[0].length !== 3 ||
|
throw is.invalidParameterError('inputMatrix', 'array', inputMatrix);
|
||||||
inputMatrix[1].length !== 3 ||
|
|
||||||
inputMatrix[2].length !== 3
|
|
||||||
) {
|
|
||||||
// must pass in a kernel
|
|
||||||
throw new Error('Invalid recombination matrix');
|
|
||||||
}
|
}
|
||||||
this.options.recombMatrix = [
|
if (inputMatrix.length !== 3 && inputMatrix.length !== 4) {
|
||||||
inputMatrix[0][0], inputMatrix[0][1], inputMatrix[0][2],
|
throw is.invalidParameterError('inputMatrix', '3x3 or 4x4 array', inputMatrix.length);
|
||||||
inputMatrix[1][0], inputMatrix[1][1], inputMatrix[1][2],
|
}
|
||||||
inputMatrix[2][0], inputMatrix[2][1], inputMatrix[2][2]
|
const recombMatrix = inputMatrix.flat().map(Number);
|
||||||
].map(Number);
|
if (recombMatrix.length !== 9 && recombMatrix.length !== 16) {
|
||||||
|
throw is.invalidParameterError('inputMatrix', 'cardinality of 9 or 16', recombMatrix.length);
|
||||||
|
}
|
||||||
|
this.options.recombMatrix = recombMatrix;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -768,7 +933,7 @@ function recomb (inputMatrix) {
|
|||||||
* .toBuffer();
|
* .toBuffer();
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* // decreate brightness and saturation while also hue-rotating by 90 degrees
|
* // decrease brightness and saturation while also hue-rotating by 90 degrees
|
||||||
* const output = await sharp(input)
|
* const output = await sharp(input)
|
||||||
* .modulate({
|
* .modulate({
|
||||||
* brightness: 0.5,
|
* brightness: 0.5,
|
||||||
@@ -821,18 +986,23 @@ function modulate (options) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Decorate the Sharp prototype with operation-related functions.
|
* Decorate the Sharp prototype with operation-related functions.
|
||||||
|
* @module Sharp
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
module.exports = function (Sharp) {
|
module.exports = function (Sharp) {
|
||||||
Object.assign(Sharp.prototype, {
|
Object.assign(Sharp.prototype, {
|
||||||
|
autoOrient,
|
||||||
rotate,
|
rotate,
|
||||||
flip,
|
flip,
|
||||||
flop,
|
flop,
|
||||||
affine,
|
affine,
|
||||||
sharpen,
|
sharpen,
|
||||||
|
erode,
|
||||||
|
dilate,
|
||||||
median,
|
median,
|
||||||
blur,
|
blur,
|
||||||
flatten,
|
flatten,
|
||||||
|
unflatten,
|
||||||
gamma,
|
gamma,
|
||||||
negate,
|
negate,
|
||||||
normalise,
|
normalise,
|
||||||
|
|||||||
534
lib/output.js
@@ -1,6 +1,9 @@
|
|||||||
|
// Copyright 2013 Lovell Fuller and others.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const path = require('path');
|
const path = require('node:path');
|
||||||
const is = require('./is');
|
const is = require('./is');
|
||||||
const sharp = require('./sharp');
|
const sharp = require('./sharp');
|
||||||
|
|
||||||
@@ -22,10 +25,13 @@ const formats = new Map([
|
|||||||
['jp2', 'jp2'],
|
['jp2', 'jp2'],
|
||||||
['jpx', 'jp2'],
|
['jpx', 'jp2'],
|
||||||
['j2k', 'jp2'],
|
['j2k', 'jp2'],
|
||||||
['j2c', 'jp2']
|
['j2c', 'jp2'],
|
||||||
|
['jxl', 'jxl']
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const errJp2Save = new Error('JP2 output requires libvips with support for OpenJPEG');
|
const jp2Regex = /\.(jp[2x]|j2[kc])$/i;
|
||||||
|
|
||||||
|
const errJp2Save = () => new Error('JP2 output requires libvips with support for OpenJPEG');
|
||||||
|
|
||||||
const bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math.log2(colours)));
|
const bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math.log2(colours)));
|
||||||
|
|
||||||
@@ -37,7 +43,7 @@ const bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math
|
|||||||
* Note that raw pixel data is only supported for buffer output.
|
* Note that raw pixel data is only supported for buffer output.
|
||||||
*
|
*
|
||||||
* By default all metadata will be removed, which includes EXIF-based orientation.
|
* By default all metadata will be removed, which includes EXIF-based orientation.
|
||||||
* See {@link withMetadata} for control over this.
|
* See {@link #withmetadata|withMetadata} for control over this.
|
||||||
*
|
*
|
||||||
* The caller is responsible for ensuring directory structures and permissions exist.
|
* The caller is responsible for ensuring directory structures and permissions exist.
|
||||||
*
|
*
|
||||||
@@ -58,6 +64,8 @@ const bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math
|
|||||||
* `info` contains the output image `format`, `size` (bytes), `width`, `height`,
|
* `info` contains the output image `format`, `size` (bytes), `width`, `height`,
|
||||||
* `channels` and `premultiplied` (indicating if premultiplication was used).
|
* `channels` and `premultiplied` (indicating if premultiplication was used).
|
||||||
* When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
|
* When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
|
||||||
|
* When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region.
|
||||||
|
* Animated output will also contain `pageHeight` and `pages`.
|
||||||
* May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.
|
* May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.
|
||||||
* @returns {Promise<Object>} - when no callback is provided
|
* @returns {Promise<Object>} - when no callback is provided
|
||||||
* @throws {Error} Invalid parameters
|
* @throws {Error} Invalid parameters
|
||||||
@@ -68,6 +76,8 @@ function toFile (fileOut, callback) {
|
|||||||
err = new Error('Missing output file path');
|
err = new Error('Missing output file path');
|
||||||
} else if (is.string(this.options.input.file) && path.resolve(this.options.input.file) === path.resolve(fileOut)) {
|
} else if (is.string(this.options.input.file) && path.resolve(this.options.input.file) === path.resolve(fileOut)) {
|
||||||
err = new Error('Cannot use same file for input and output');
|
err = new Error('Cannot use same file for input and output');
|
||||||
|
} else if (jp2Regex.test(path.extname(fileOut)) && !this.constructor.format.jp2k.output.file) {
|
||||||
|
err = errJp2Save();
|
||||||
}
|
}
|
||||||
if (err) {
|
if (err) {
|
||||||
if (is.fn(callback)) {
|
if (is.fn(callback)) {
|
||||||
@@ -77,7 +87,8 @@ function toFile (fileOut, callback) {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
this.options.fileOut = fileOut;
|
this.options.fileOut = fileOut;
|
||||||
return this._pipeline(callback);
|
const stack = Error();
|
||||||
|
return this._pipeline(callback, stack);
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
@@ -86,12 +97,12 @@ function toFile (fileOut, callback) {
|
|||||||
* Write output to a Buffer.
|
* Write output to a Buffer.
|
||||||
* JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.
|
* JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.
|
||||||
*
|
*
|
||||||
* Use {@link toFormat} or one of the format-specific functions such as {@link jpeg}, {@link png} etc. to set the output format.
|
* Use {@link #toformat|toFormat} or one of the format-specific functions such as {@link jpeg}, {@link png} etc. to set the output format.
|
||||||
*
|
*
|
||||||
* If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output.
|
* If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output.
|
||||||
*
|
*
|
||||||
* By default all metadata will be removed, which includes EXIF-based orientation.
|
* By default all metadata will be removed, which includes EXIF-based orientation.
|
||||||
* See {@link withMetadata} for control over this.
|
* See {@link #withmetadata|withMetadata} for control over this.
|
||||||
*
|
*
|
||||||
* `callback`, if present, gets three arguments `(err, data, info)` where:
|
* `callback`, if present, gets three arguments `(err, data, info)` where:
|
||||||
* - `err` is an error, if any.
|
* - `err` is an error, if any.
|
||||||
@@ -99,6 +110,7 @@ function toFile (fileOut, callback) {
|
|||||||
* - `info` contains the output image `format`, `size` (bytes), `width`, `height`,
|
* - `info` contains the output image `format`, `size` (bytes), `width`, `height`,
|
||||||
* `channels` and `premultiplied` (indicating if premultiplication was used).
|
* `channels` and `premultiplied` (indicating if premultiplication was used).
|
||||||
* When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
|
* When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
|
||||||
|
* Animated output will also contain `pageHeight` and `pages`.
|
||||||
* May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.
|
* May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.
|
||||||
*
|
*
|
||||||
* A `Promise` is returned when `callback` is not provided.
|
* A `Promise` is returned when `callback` is not provided.
|
||||||
@@ -148,37 +160,243 @@ function toBuffer (options, callback) {
|
|||||||
this.options.resolveWithObject = false;
|
this.options.resolveWithObject = false;
|
||||||
}
|
}
|
||||||
this.options.fileOut = '';
|
this.options.fileOut = '';
|
||||||
return this._pipeline(is.fn(options) ? options : callback);
|
const stack = Error();
|
||||||
|
return this._pipeline(is.fn(options) ? options : callback, stack);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Include all metadata (EXIF, XMP, IPTC) from the input image in the output image.
|
* Keep all EXIF metadata from the input image in the output image.
|
||||||
* This will also convert to and add a web-friendly sRGB ICC profile unless a custom
|
|
||||||
* output profile is provided.
|
|
||||||
*
|
|
||||||
* The default behaviour, when `withMetadata` is not used, is to convert to the device-independent
|
|
||||||
* sRGB colour space and strip all metadata, including the removal of any ICC profile.
|
|
||||||
*
|
*
|
||||||
* EXIF metadata is unsupported for TIFF output.
|
* EXIF metadata is unsupported for TIFF output.
|
||||||
*
|
*
|
||||||
* @example
|
* @since 0.33.0
|
||||||
* sharp('input.jpg')
|
|
||||||
* .withMetadata()
|
|
||||||
* .toFile('output-with-metadata.jpg')
|
|
||||||
* .then(info => { ... });
|
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* // Set "IFD0-Copyright" in output EXIF metadata
|
* const outputWithExif = await sharp(inputWithExif)
|
||||||
* const data = await sharp(input)
|
* .keepExif()
|
||||||
* .withMetadata({
|
* .toBuffer();
|
||||||
* exif: {
|
*
|
||||||
* IFD0: {
|
* @returns {Sharp}
|
||||||
* Copyright: 'Wernham Hogg'
|
*/
|
||||||
* }
|
function keepExif () {
|
||||||
|
this.options.keepMetadata |= 0b00001;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set EXIF metadata in the output image, ignoring any EXIF in the input image.
|
||||||
|
*
|
||||||
|
* @since 0.33.0
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* 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();
|
* .toBuffer();
|
||||||
*
|
*
|
||||||
|
* @param {Object<string, Object<string, string>>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.
|
||||||
|
* @returns {Sharp}
|
||||||
|
* @throws {Error} Invalid parameters
|
||||||
|
*/
|
||||||
|
function withExif (exif) {
|
||||||
|
if (is.object(exif)) {
|
||||||
|
for (const [ifd, entries] of Object.entries(exif)) {
|
||||||
|
if (is.object(entries)) {
|
||||||
|
for (const [k, v] of Object.entries(entries)) {
|
||||||
|
if (is.string(v)) {
|
||||||
|
this.options.withExif[`exif-${ifd.toLowerCase()}-${k}`] = v;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError(`${ifd}.${k}`, 'string', v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError(ifd, 'object', entries);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('exif', 'object', exif);
|
||||||
|
}
|
||||||
|
this.options.withExifMerge = false;
|
||||||
|
return this.keepExif();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update EXIF metadata from the input image in the output image.
|
||||||
|
*
|
||||||
|
* @since 0.33.0
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const dataWithMergedExif = await sharp(inputWithExif)
|
||||||
|
* .withExifMerge({
|
||||||
|
* IFD0: {
|
||||||
|
* Copyright: 'The National Gallery'
|
||||||
|
* }
|
||||||
|
* })
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
|
* @param {Object<string, Object<string, string>>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.
|
||||||
|
* @returns {Sharp}
|
||||||
|
* @throws {Error} Invalid parameters
|
||||||
|
*/
|
||||||
|
function withExifMerge (exif) {
|
||||||
|
this.withExif(exif);
|
||||||
|
this.options.withExifMerge = true;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
* const outputWithIccProfile = await sharp(inputWithIccProfile)
|
||||||
|
* .keepIccProfile()
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
|
* @returns {Sharp}
|
||||||
|
*/
|
||||||
|
function keepIccProfile () {
|
||||||
|
this.options.keepMetadata |= 0b01000;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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`).
|
||||||
|
*
|
||||||
|
* @since 0.33.0
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const outputWithP3 = await sharp(input)
|
||||||
|
* .withIccProfile('p3')
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
|
* @param {string} icc - Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk).
|
||||||
|
* @param {Object} [options]
|
||||||
|
* @param {number} [options.attach=true] Should the ICC profile be included in the output image metadata?
|
||||||
|
* @returns {Sharp}
|
||||||
|
* @throws {Error} Invalid parameters
|
||||||
|
*/
|
||||||
|
function withIccProfile (icc, options) {
|
||||||
|
if (is.string(icc)) {
|
||||||
|
this.options.withIccProfile = icc;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('icc', 'string', icc);
|
||||||
|
}
|
||||||
|
this.keepIccProfile();
|
||||||
|
if (is.object(options)) {
|
||||||
|
if (is.defined(options.attach)) {
|
||||||
|
if (is.bool(options.attach)) {
|
||||||
|
if (!options.attach) {
|
||||||
|
this.options.keepMetadata &= ~0b01000;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('attach', 'boolean', options.attach);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep XMP metadata from the input image in the output image.
|
||||||
|
*
|
||||||
|
* @since 0.34.3
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const outputWithXmp = await sharp(inputWithXmp)
|
||||||
|
* .keepXmp()
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
|
* @returns {Sharp}
|
||||||
|
*/
|
||||||
|
function keepXmp () {
|
||||||
|
this.options.keepMetadata |= 0b00010;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set XMP metadata in the output image.
|
||||||
|
*
|
||||||
|
* Supported by PNG, JPEG, WebP, and TIFF output.
|
||||||
|
*
|
||||||
|
* @since 0.34.3
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const xmpString = `
|
||||||
|
* <?xml version="1.0"?>
|
||||||
|
* <x:xmpmeta xmlns:x="adobe:ns:meta/">
|
||||||
|
* <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||||
|
* <rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||||
|
* <dc:creator><rdf:Seq><rdf:li>John Doe</rdf:li></rdf:Seq></dc:creator>
|
||||||
|
* </rdf:Description>
|
||||||
|
* </rdf:RDF>
|
||||||
|
* </x:xmpmeta>`;
|
||||||
|
*
|
||||||
|
* const data = await sharp(input)
|
||||||
|
* .withXmp(xmpString)
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
|
* @param {string} xmp String containing XMP metadata to be embedded in the output image.
|
||||||
|
* @returns {Sharp}
|
||||||
|
* @throws {Error} Invalid parameters
|
||||||
|
*/
|
||||||
|
function withXmp (xmp) {
|
||||||
|
if (is.string(xmp) && xmp.length > 0) {
|
||||||
|
this.options.withXmp = xmp;
|
||||||
|
this.options.keepMetadata |= 0b00010;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('xmp', 'non-empty string', xmp);
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image.
|
||||||
|
*
|
||||||
|
* 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
|
||||||
|
* const outputWithMetadata = await sharp(inputWithMetadata)
|
||||||
|
* .keepMetadata()
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
|
* @returns {Sharp}
|
||||||
|
*/
|
||||||
|
function keepMetadata () {
|
||||||
|
this.options.keepMetadata = 0b11111;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const outputSrgbWithMetadata = await sharp(inputRgbWithMetadata)
|
||||||
|
* .withMetadata()
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
* @example
|
* @example
|
||||||
* // Set output metadata to 96 DPI
|
* // Set output metadata to 96 DPI
|
||||||
* const data = await sharp(input)
|
* const data = await sharp(input)
|
||||||
@@ -186,15 +404,14 @@ function toBuffer (options, callback) {
|
|||||||
* .toBuffer();
|
* .toBuffer();
|
||||||
*
|
*
|
||||||
* @param {Object} [options]
|
* @param {Object} [options]
|
||||||
* @param {number} [options.orientation] value between 1 and 8, used to update the EXIF `Orientation` tag.
|
* @param {number} [options.orientation] Used to update the EXIF `Orientation` tag, integer between 1 and 8.
|
||||||
* @param {string} [options.icc] filesystem path to output ICC profile, defaults to sRGB.
|
|
||||||
* @param {Object<Object>} [options.exif={}] Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.
|
|
||||||
* @param {number} [options.density] Number of pixels per inch (DPI).
|
* @param {number} [options.density] Number of pixels per inch (DPI).
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid parameters
|
* @throws {Error} Invalid parameters
|
||||||
*/
|
*/
|
||||||
function withMetadata (options) {
|
function withMetadata (options) {
|
||||||
this.options.withMetadata = is.bool(options) ? options : true;
|
this.keepMetadata();
|
||||||
|
this.withIccProfile('srgb');
|
||||||
if (is.object(options)) {
|
if (is.object(options)) {
|
||||||
if (is.defined(options.orientation)) {
|
if (is.defined(options.orientation)) {
|
||||||
if (is.integer(options.orientation) && is.inRange(options.orientation, 1, 8)) {
|
if (is.integer(options.orientation) && is.inRange(options.orientation, 1, 8)) {
|
||||||
@@ -211,30 +428,10 @@ function withMetadata (options) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(options.icc)) {
|
if (is.defined(options.icc)) {
|
||||||
if (is.string(options.icc)) {
|
this.withIccProfile(options.icc);
|
||||||
this.options.withMetadataIcc = options.icc;
|
|
||||||
} else {
|
|
||||||
throw is.invalidParameterError('icc', 'string filesystem path to ICC profile', options.icc);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (is.defined(options.exif)) {
|
if (is.defined(options.exif)) {
|
||||||
if (is.object(options.exif)) {
|
this.withExifMerge(options.exif);
|
||||||
for (const [ifd, entries] of Object.entries(options.exif)) {
|
|
||||||
if (is.object(entries)) {
|
|
||||||
for (const [k, v] of Object.entries(entries)) {
|
|
||||||
if (is.string(v)) {
|
|
||||||
this.options.withMetadataStrs[`exif-${ifd.toLowerCase()}-${k}`] = v;
|
|
||||||
} else {
|
|
||||||
throw is.invalidParameterError(`exif.${ifd}.${k}`, 'string', v);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
throw is.invalidParameterError(`exif.${ifd}`, 'object', entries);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
throw is.invalidParameterError('exif', 'object', options.exif);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
@@ -362,10 +559,14 @@ function jpeg (options) {
|
|||||||
/**
|
/**
|
||||||
* Use these PNG options for output image.
|
* Use these PNG options for output image.
|
||||||
*
|
*
|
||||||
* By default, PNG output is full colour at 8 or 16 bits per pixel.
|
* 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.
|
* 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.
|
* Set `palette` to `true` for slower, indexed PNG output.
|
||||||
*
|
*
|
||||||
|
* For 16 bits per pixel output, convert to `rgb16` via
|
||||||
|
* {@link /api-colour#tocolourspace|toColourspace}.
|
||||||
|
*
|
||||||
* @example
|
* @example
|
||||||
* // Convert any input to full colour PNG output
|
* // Convert any input to full colour PNG output
|
||||||
* const data = await sharp(input)
|
* const data = await sharp(input)
|
||||||
@@ -378,6 +579,13 @@ function jpeg (options) {
|
|||||||
* .png({ palette: true })
|
* .png({ palette: true })
|
||||||
* .toBuffer();
|
* .toBuffer();
|
||||||
*
|
*
|
||||||
|
* @example
|
||||||
|
* // Output 16 bits per pixel RGB(A)
|
||||||
|
* const data = await sharp(input)
|
||||||
|
* .toColourspace('rgb16')
|
||||||
|
* .png()
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
* @param {Object} [options]
|
* @param {Object} [options]
|
||||||
* @param {boolean} [options.progressive=false] - use progressive (interlace) scan
|
* @param {boolean} [options.progressive=false] - use progressive (interlace) scan
|
||||||
* @param {number} [options.compressionLevel=6] - zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest)
|
* @param {number} [options.compressionLevel=6] - zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest)
|
||||||
@@ -468,6 +676,8 @@ function png (options) {
|
|||||||
* @param {boolean} [options.lossless=false] - use lossless compression mode
|
* @param {boolean} [options.lossless=false] - use lossless compression mode
|
||||||
* @param {boolean} [options.nearLossless=false] - use near_lossless compression mode
|
* @param {boolean} [options.nearLossless=false] - use near_lossless compression mode
|
||||||
* @param {boolean} [options.smartSubsample=false] - use high quality chroma subsampling
|
* @param {boolean} [options.smartSubsample=false] - use high quality chroma subsampling
|
||||||
|
* @param {boolean} [options.smartDeblock=false] - auto-adjust the deblocking filter, can improve low contrast edges (slow)
|
||||||
|
* @param {string} [options.preset='default'] - named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text
|
||||||
* @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 6 (slowest)
|
* @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 6 (slowest)
|
||||||
* @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation
|
* @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation
|
||||||
* @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)
|
* @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)
|
||||||
@@ -502,6 +712,16 @@ function webp (options) {
|
|||||||
if (is.defined(options.smartSubsample)) {
|
if (is.defined(options.smartSubsample)) {
|
||||||
this._setBooleanOption('webpSmartSubsample', options.smartSubsample);
|
this._setBooleanOption('webpSmartSubsample', options.smartSubsample);
|
||||||
}
|
}
|
||||||
|
if (is.defined(options.smartDeblock)) {
|
||||||
|
this._setBooleanOption('webpSmartDeblock', options.smartDeblock);
|
||||||
|
}
|
||||||
|
if (is.defined(options.preset)) {
|
||||||
|
if (is.string(options.preset) && is.inArray(options.preset, ['default', 'photo', 'picture', 'drawing', 'icon', 'text'])) {
|
||||||
|
this.options.webpPreset = options.preset;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('preset', 'one of: default, photo, picture, drawing, icon, text', options.preset);
|
||||||
|
}
|
||||||
|
}
|
||||||
if (is.defined(options.effort)) {
|
if (is.defined(options.effort)) {
|
||||||
if (is.integer(options.effort) && is.inRange(options.effort, 0, 6)) {
|
if (is.integer(options.effort) && is.inRange(options.effort, 0, 6)) {
|
||||||
this.options.webpEffort = options.effort;
|
this.options.webpEffort = options.effort;
|
||||||
@@ -547,13 +767,22 @@ function webp (options) {
|
|||||||
* .gif({ dither: 0 })
|
* .gif({ dither: 0 })
|
||||||
* .toBuffer();
|
* .toBuffer();
|
||||||
*
|
*
|
||||||
|
* @example
|
||||||
|
* // Lossy file size reduction of animated GIF
|
||||||
|
* await sharp('in.gif', { animated: true })
|
||||||
|
* .gif({ interFrameMaxError: 8 })
|
||||||
|
* .toFile('optim.gif');
|
||||||
|
*
|
||||||
* @param {Object} [options] - output options
|
* @param {Object} [options] - output options
|
||||||
* @param {boolean} [options.reoptimise=false] - always generate new palettes (slow), re-use existing by default
|
* @param {boolean} [options.reuse=true] - re-use existing palette, otherwise generate new (slow)
|
||||||
* @param {boolean} [options.reoptimize=false] - alternative spelling of `options.reoptimise`
|
* @param {boolean} [options.progressive=false] - use progressive (interlace) scan
|
||||||
* @param {number} [options.colours=256] - maximum number of palette entries, including transparency, between 2 and 256
|
* @param {number} [options.colours=256] - maximum number of palette entries, including transparency, between 2 and 256
|
||||||
* @param {number} [options.colors=256] - alternative spelling of `options.colours`
|
* @param {number} [options.colors=256] - alternative spelling of `options.colours`
|
||||||
* @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest)
|
* @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest)
|
||||||
* @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most)
|
* @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most)
|
||||||
|
* @param {number} [options.interFrameMaxError=0] - maximum inter-frame error for transparency, between 0 (lossless) and 32
|
||||||
|
* @param {number} [options.interPaletteMaxError=3] - maximum inter-palette error for palette reuse, between 0 and 256
|
||||||
|
* @param {boolean} [options.keepDuplicateFrames=false] - keep duplicate frames in the output instead of combining them
|
||||||
* @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation
|
* @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation
|
||||||
* @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)
|
* @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)
|
||||||
* @param {boolean} [options.force=true] - force GIF output, otherwise attempt to use input format
|
* @param {boolean} [options.force=true] - force GIF output, otherwise attempt to use input format
|
||||||
@@ -562,10 +791,11 @@ function webp (options) {
|
|||||||
*/
|
*/
|
||||||
function gif (options) {
|
function gif (options) {
|
||||||
if (is.object(options)) {
|
if (is.object(options)) {
|
||||||
if (is.defined(options.reoptimise)) {
|
if (is.defined(options.reuse)) {
|
||||||
this._setBooleanOption('gifReoptimise', options.reoptimise);
|
this._setBooleanOption('gifReuse', options.reuse);
|
||||||
} else if (is.defined(options.reoptimize)) {
|
}
|
||||||
this._setBooleanOption('gifReoptimise', options.reoptimize);
|
if (is.defined(options.progressive)) {
|
||||||
|
this._setBooleanOption('gifProgressive', options.progressive);
|
||||||
}
|
}
|
||||||
const colours = options.colours || options.colors;
|
const colours = options.colours || options.colors;
|
||||||
if (is.defined(colours)) {
|
if (is.defined(colours)) {
|
||||||
@@ -589,11 +819,33 @@ function gif (options) {
|
|||||||
throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither);
|
throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (is.defined(options.interFrameMaxError)) {
|
||||||
|
if (is.number(options.interFrameMaxError) && is.inRange(options.interFrameMaxError, 0, 32)) {
|
||||||
|
this.options.gifInterFrameMaxError = options.interFrameMaxError;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('interFrameMaxError', 'number between 0.0 and 32.0', options.interFrameMaxError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (is.defined(options.interPaletteMaxError)) {
|
||||||
|
if (is.number(options.interPaletteMaxError) && is.inRange(options.interPaletteMaxError, 0, 256)) {
|
||||||
|
this.options.gifInterPaletteMaxError = options.interPaletteMaxError;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('interPaletteMaxError', 'number between 0.0 and 256.0', options.interPaletteMaxError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (is.defined(options.keepDuplicateFrames)) {
|
||||||
|
if (is.bool(options.keepDuplicateFrames)) {
|
||||||
|
this._setBooleanOption('gifKeepDuplicateFrames', options.keepDuplicateFrames);
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('keepDuplicateFrames', 'boolean', options.keepDuplicateFrames);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
trySetAnimationOptions(options, this.options);
|
trySetAnimationOptions(options, this.options);
|
||||||
return this._updateFormatOut('gif', options);
|
return this._updateFormatOut('gif', options);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* istanbul ignore next */
|
||||||
/**
|
/**
|
||||||
* Use these JP2 options for output image.
|
* Use these JP2 options for output image.
|
||||||
*
|
*
|
||||||
@@ -627,10 +879,9 @@ function gif (options) {
|
|||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid options
|
* @throws {Error} Invalid options
|
||||||
*/
|
*/
|
||||||
/* istanbul ignore next */
|
|
||||||
function jp2 (options) {
|
function jp2 (options) {
|
||||||
if (!this.constructor.format.jp2k.output.buffer) {
|
if (!this.constructor.format.jp2k.output.buffer) {
|
||||||
throw errJp2Save;
|
throw errJp2Save();
|
||||||
}
|
}
|
||||||
if (is.object(options)) {
|
if (is.object(options)) {
|
||||||
if (is.defined(options.quality)) {
|
if (is.defined(options.quality)) {
|
||||||
@@ -663,7 +914,7 @@ function jp2 (options) {
|
|||||||
}
|
}
|
||||||
if (is.defined(options.chromaSubsampling)) {
|
if (is.defined(options.chromaSubsampling)) {
|
||||||
if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) {
|
if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) {
|
||||||
this.options.heifChromaSubsampling = options.chromaSubsampling;
|
this.options.jp2ChromaSubsampling = options.chromaSubsampling;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);
|
throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);
|
||||||
}
|
}
|
||||||
@@ -708,7 +959,8 @@ function trySetAnimationOptions (source, target) {
|
|||||||
/**
|
/**
|
||||||
* Use these TIFF options for output image.
|
* Use these TIFF options for output image.
|
||||||
*
|
*
|
||||||
* The `density` can be set in pixels/inch via {@link withMetadata} instead of providing `xres` and `yres` in pixels/mm.
|
* The `density` can be set in pixels/inch via {@link #withmetadata|withMetadata}
|
||||||
|
* instead of providing `xres` and `yres` in pixels/mm.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* // Convert SVG input to LZW-compressed, 1 bit per pixel TIFF output
|
* // Convert SVG input to LZW-compressed, 1 bit per pixel TIFF output
|
||||||
@@ -733,6 +985,7 @@ function trySetAnimationOptions (source, target) {
|
|||||||
* @param {number} [options.yres=1.0] - vertical resolution in pixels/mm
|
* @param {number} [options.yres=1.0] - vertical resolution in pixels/mm
|
||||||
* @param {string} [options.resolutionUnit='inch'] - resolution unit options: inch, cm
|
* @param {string} [options.resolutionUnit='inch'] - resolution unit options: inch, cm
|
||||||
* @param {number} [options.bitdepth=8] - reduce bitdepth to 1, 2 or 4 bit
|
* @param {number} [options.bitdepth=8] - reduce bitdepth to 1, 2 or 4 bit
|
||||||
|
* @param {boolean} [options.miniswhite=false] - write 1-bit images as miniswhite
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid options
|
* @throws {Error} Invalid options
|
||||||
*/
|
*/
|
||||||
@@ -770,6 +1023,10 @@ function tiff (options) {
|
|||||||
throw is.invalidParameterError('tileHeight', 'integer greater than zero', options.tileHeight);
|
throw is.invalidParameterError('tileHeight', 'integer greater than zero', options.tileHeight);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// miniswhite
|
||||||
|
if (is.defined(options.miniswhite)) {
|
||||||
|
this._setBooleanOption('tiffMiniswhite', options.miniswhite);
|
||||||
|
}
|
||||||
// pyramid
|
// pyramid
|
||||||
if (is.defined(options.pyramid)) {
|
if (is.defined(options.pyramid)) {
|
||||||
this._setBooleanOption('tiffPyramid', options.pyramid);
|
this._setBooleanOption('tiffPyramid', options.pyramid);
|
||||||
@@ -820,10 +1077,11 @@ function tiff (options) {
|
|||||||
/**
|
/**
|
||||||
* Use these AVIF options for output image.
|
* Use these AVIF options for output image.
|
||||||
*
|
*
|
||||||
* Whilst it is possible to create AVIF images smaller than 16x16 pixels,
|
|
||||||
* most web browsers do not display these properly.
|
|
||||||
*
|
|
||||||
* AVIF image sequences are not supported.
|
* 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.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* const data = await sharp(input)
|
* const data = await sharp(input)
|
||||||
@@ -842,6 +1100,7 @@ function tiff (options) {
|
|||||||
* @param {boolean} [options.lossless=false] - use lossless compression
|
* @param {boolean} [options.lossless=false] - use lossless compression
|
||||||
* @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest)
|
* @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest)
|
||||||
* @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling
|
* @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling
|
||||||
|
* @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid options
|
* @throws {Error} Invalid options
|
||||||
*/
|
*/
|
||||||
@@ -862,17 +1121,23 @@ function avif (options) {
|
|||||||
*
|
*
|
||||||
* @since 0.23.0
|
* @since 0.23.0
|
||||||
*
|
*
|
||||||
* @param {Object} [options] - output options
|
* @param {Object} options - output options
|
||||||
|
* @param {string} options.compression - compression format: av1, hevc
|
||||||
* @param {number} [options.quality=50] - quality, integer 1-100
|
* @param {number} [options.quality=50] - quality, integer 1-100
|
||||||
* @param {string} [options.compression='av1'] - compression format: av1, hevc
|
|
||||||
* @param {boolean} [options.lossless=false] - use lossless compression
|
* @param {boolean} [options.lossless=false] - use lossless compression
|
||||||
* @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest)
|
* @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest)
|
||||||
* @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling
|
* @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling
|
||||||
|
* @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid options
|
* @throws {Error} Invalid options
|
||||||
*/
|
*/
|
||||||
function heif (options) {
|
function heif (options) {
|
||||||
if (is.object(options)) {
|
if (is.object(options)) {
|
||||||
|
if (is.string(options.compression) && is.inArray(options.compression, ['av1', 'hevc'])) {
|
||||||
|
this.options.heifCompression = options.compression;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('compression', 'one of: av1, hevc', options.compression);
|
||||||
|
}
|
||||||
if (is.defined(options.quality)) {
|
if (is.defined(options.quality)) {
|
||||||
if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {
|
if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {
|
||||||
this.options.heifQuality = options.quality;
|
this.options.heifQuality = options.quality;
|
||||||
@@ -887,13 +1152,6 @@ function heif (options) {
|
|||||||
throw is.invalidParameterError('lossless', 'boolean', options.lossless);
|
throw is.invalidParameterError('lossless', 'boolean', options.lossless);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(options.compression)) {
|
|
||||||
if (is.string(options.compression) && is.inArray(options.compression, ['av1', 'hevc'])) {
|
|
||||||
this.options.heifCompression = options.compression;
|
|
||||||
} else {
|
|
||||||
throw is.invalidParameterError('compression', 'one of: av1, hevc', options.compression);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (is.defined(options.effort)) {
|
if (is.defined(options.effort)) {
|
||||||
if (is.integer(options.effort) && is.inRange(options.effort, 0, 9)) {
|
if (is.integer(options.effort) && is.inRange(options.effort, 0, 9)) {
|
||||||
this.options.heifEffort = options.effort;
|
this.options.heifEffort = options.effort;
|
||||||
@@ -908,10 +1166,88 @@ function heif (options) {
|
|||||||
throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);
|
throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (is.defined(options.bitdepth)) {
|
||||||
|
if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [8, 10, 12])) {
|
||||||
|
if (options.bitdepth !== 8 && this.constructor.versions.heif) {
|
||||||
|
throw is.invalidParameterError('bitdepth when using prebuilt binaries', 8, options.bitdepth);
|
||||||
|
}
|
||||||
|
this.options.heifBitdepth = options.bitdepth;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('bitdepth', '8, 10 or 12', options.bitdepth);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('options', 'Object', options);
|
||||||
}
|
}
|
||||||
return this._updateFormatOut('heif', options);
|
return this._updateFormatOut('heif', options);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Use these JPEG-XL (JXL) options for output image.
|
||||||
|
*
|
||||||
|
* This feature is experimental, please do not use in production systems.
|
||||||
|
*
|
||||||
|
* Requires libvips compiled with support for libjxl.
|
||||||
|
* The prebuilt binaries do not include this - see
|
||||||
|
* {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}.
|
||||||
|
*
|
||||||
|
* @since 0.31.3
|
||||||
|
*
|
||||||
|
* @param {Object} [options] - output options
|
||||||
|
* @param {number} [options.distance=1.0] - maximum encoding error, between 0 (highest quality) and 15 (lowest quality)
|
||||||
|
* @param {number} [options.quality] - calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified
|
||||||
|
* @param {number} [options.decodingTier=0] - target decode speed tier, between 0 (highest quality) and 4 (lowest quality)
|
||||||
|
* @param {boolean} [options.lossless=false] - use lossless compression
|
||||||
|
* @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 9 (slowest)
|
||||||
|
* @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation
|
||||||
|
* @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)
|
||||||
|
* @returns {Sharp}
|
||||||
|
* @throws {Error} Invalid options
|
||||||
|
*/
|
||||||
|
function jxl (options) {
|
||||||
|
if (is.object(options)) {
|
||||||
|
if (is.defined(options.quality)) {
|
||||||
|
if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {
|
||||||
|
// https://github.com/libjxl/libjxl/blob/0aeea7f180bafd6893c1db8072dcb67d2aa5b03d/tools/cjxl_main.cc#L640-L644
|
||||||
|
this.options.jxlDistance = options.quality >= 30
|
||||||
|
? 0.1 + (100 - options.quality) * 0.09
|
||||||
|
: 53 / 3000 * options.quality * options.quality - 23 / 20 * options.quality + 25;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);
|
||||||
|
}
|
||||||
|
} else if (is.defined(options.distance)) {
|
||||||
|
if (is.number(options.distance) && is.inRange(options.distance, 0, 15)) {
|
||||||
|
this.options.jxlDistance = options.distance;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('distance', 'number between 0.0 and 15.0', options.distance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (is.defined(options.decodingTier)) {
|
||||||
|
if (is.integer(options.decodingTier) && is.inRange(options.decodingTier, 0, 4)) {
|
||||||
|
this.options.jxlDecodingTier = options.decodingTier;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('decodingTier', 'integer between 0 and 4', options.decodingTier);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (is.defined(options.lossless)) {
|
||||||
|
if (is.bool(options.lossless)) {
|
||||||
|
this.options.jxlLossless = options.lossless;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('lossless', 'boolean', options.lossless);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (is.defined(options.effort)) {
|
||||||
|
if (is.integer(options.effort) && is.inRange(options.effort, 1, 9)) {
|
||||||
|
this.options.jxlEffort = options.effort;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('effort', 'integer between 1 and 9', options.effort);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
trySetAnimationOptions(options, this.options);
|
||||||
|
return this._updateFormatOut('jxl', options);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Force output to be raw, uncompressed pixel data.
|
* Force output to be raw, uncompressed pixel data.
|
||||||
* Pixel ordering is left-to-right, top-to-bottom, without padding.
|
* Pixel ordering is left-to-right, top-to-bottom, without padding.
|
||||||
@@ -934,6 +1270,7 @@ function heif (options) {
|
|||||||
*
|
*
|
||||||
* @param {Object} [options] - output options
|
* @param {Object} [options] - output options
|
||||||
* @param {string} [options.depth='uchar'] - bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex
|
* @param {string} [options.depth='uchar'] - bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex
|
||||||
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid options
|
* @throws {Error} Invalid options
|
||||||
*/
|
*/
|
||||||
function raw (options) {
|
function raw (options) {
|
||||||
@@ -987,7 +1324,7 @@ function raw (options) {
|
|||||||
* @param {number} [options.angle=0] tile angle of rotation, must be a multiple of 90.
|
* @param {number} [options.angle=0] tile angle of rotation, must be a multiple of 90.
|
||||||
* @param {string|Object} [options.background={r: 255, g: 255, b: 255, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to white without transparency.
|
* @param {string|Object} [options.background={r: 255, g: 255, b: 255, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to white without transparency.
|
||||||
* @param {string} [options.depth] how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout.
|
* @param {string} [options.depth] how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout.
|
||||||
* @param {number} [options.skipBlanks=-1] threshold to skip tile generation, a value 0 - 255 for 8-bit images or 0 - 65535 for 16-bit images
|
* @param {number} [options.skipBlanks=-1] 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.
|
||||||
* @param {string} [options.container='fs'] tile container, with value `fs` (filesystem) or `zip` (compressed file).
|
* @param {string} [options.container='fs'] tile container, with value `fs` (filesystem) or `zip` (compressed file).
|
||||||
* @param {string} [options.layout='dz'] filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`.
|
* @param {string} [options.layout='dz'] filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`.
|
||||||
* @param {boolean} [options.centre=false] centre image in tile.
|
* @param {boolean} [options.centre=false] centre image in tile.
|
||||||
@@ -1168,7 +1505,8 @@ function _read () {
|
|||||||
/* istanbul ignore else */
|
/* istanbul ignore else */
|
||||||
if (!this.options.streamOut) {
|
if (!this.options.streamOut) {
|
||||||
this.options.streamOut = true;
|
this.options.streamOut = true;
|
||||||
this._pipeline();
|
const stack = Error();
|
||||||
|
this._pipeline(undefined, stack);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1177,18 +1515,30 @@ function _read () {
|
|||||||
* Supports callback, stream and promise variants
|
* Supports callback, stream and promise variants
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
function _pipeline (callback) {
|
function _pipeline (callback, stack) {
|
||||||
if (typeof callback === 'function') {
|
if (typeof callback === 'function') {
|
||||||
// output=file/buffer
|
// output=file/buffer
|
||||||
if (this._isStreamInput()) {
|
if (this._isStreamInput()) {
|
||||||
// output=file/buffer, input=stream
|
// output=file/buffer, input=stream
|
||||||
this.on('finish', () => {
|
this.on('finish', () => {
|
||||||
this._flattenBufferIn();
|
this._flattenBufferIn();
|
||||||
sharp.pipeline(this.options, callback);
|
sharp.pipeline(this.options, (err, data, info) => {
|
||||||
|
if (err) {
|
||||||
|
callback(is.nativeError(err, stack));
|
||||||
|
} else {
|
||||||
|
callback(null, data, info);
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// output=file/buffer, input=file/buffer
|
// output=file/buffer, input=file/buffer
|
||||||
sharp.pipeline(this.options, callback);
|
sharp.pipeline(this.options, (err, data, info) => {
|
||||||
|
if (err) {
|
||||||
|
callback(is.nativeError(err, stack));
|
||||||
|
} else {
|
||||||
|
callback(null, data, info);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
} else if (this.options.streamOut) {
|
} else if (this.options.streamOut) {
|
||||||
@@ -1199,13 +1549,13 @@ function _pipeline (callback) {
|
|||||||
this._flattenBufferIn();
|
this._flattenBufferIn();
|
||||||
sharp.pipeline(this.options, (err, data, info) => {
|
sharp.pipeline(this.options, (err, data, info) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
this.emit('error', err);
|
this.emit('error', is.nativeError(err, stack));
|
||||||
} else {
|
} else {
|
||||||
this.emit('info', info);
|
this.emit('info', info);
|
||||||
this.push(data);
|
this.push(data);
|
||||||
}
|
}
|
||||||
this.push(null);
|
this.push(null);
|
||||||
this.emit('close');
|
this.on('end', () => this.emit('close'));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
if (this.streamInFinished) {
|
if (this.streamInFinished) {
|
||||||
@@ -1215,13 +1565,13 @@ function _pipeline (callback) {
|
|||||||
// output=stream, input=file/buffer
|
// output=stream, input=file/buffer
|
||||||
sharp.pipeline(this.options, (err, data, info) => {
|
sharp.pipeline(this.options, (err, data, info) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
this.emit('error', err);
|
this.emit('error', is.nativeError(err, stack));
|
||||||
} else {
|
} else {
|
||||||
this.emit('info', info);
|
this.emit('info', info);
|
||||||
this.push(data);
|
this.push(data);
|
||||||
}
|
}
|
||||||
this.push(null);
|
this.push(null);
|
||||||
this.emit('close');
|
this.on('end', () => this.emit('close'));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
@@ -1234,7 +1584,7 @@ function _pipeline (callback) {
|
|||||||
this._flattenBufferIn();
|
this._flattenBufferIn();
|
||||||
sharp.pipeline(this.options, (err, data, info) => {
|
sharp.pipeline(this.options, (err, data, info) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(is.nativeError(err, stack));
|
||||||
} else {
|
} else {
|
||||||
if (this.options.resolveWithObject) {
|
if (this.options.resolveWithObject) {
|
||||||
resolve({ data, info });
|
resolve({ data, info });
|
||||||
@@ -1250,10 +1600,10 @@ function _pipeline (callback) {
|
|||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
sharp.pipeline(this.options, (err, data, info) => {
|
sharp.pipeline(this.options, (err, data, info) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(is.nativeError(err, stack));
|
||||||
} else {
|
} else {
|
||||||
if (this.options.resolveWithObject) {
|
if (this.options.resolveWithObject) {
|
||||||
resolve({ data: data, info: info });
|
resolve({ data, info });
|
||||||
} else {
|
} else {
|
||||||
resolve(data);
|
resolve(data);
|
||||||
}
|
}
|
||||||
@@ -1266,6 +1616,7 @@ function _pipeline (callback) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Decorate the Sharp prototype with output-related functions.
|
* Decorate the Sharp prototype with output-related functions.
|
||||||
|
* @module Sharp
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
module.exports = function (Sharp) {
|
module.exports = function (Sharp) {
|
||||||
@@ -1273,6 +1624,14 @@ module.exports = function (Sharp) {
|
|||||||
// Public
|
// Public
|
||||||
toFile,
|
toFile,
|
||||||
toBuffer,
|
toBuffer,
|
||||||
|
keepExif,
|
||||||
|
withExif,
|
||||||
|
withExifMerge,
|
||||||
|
keepIccProfile,
|
||||||
|
withIccProfile,
|
||||||
|
keepXmp,
|
||||||
|
withXmp,
|
||||||
|
keepMetadata,
|
||||||
withMetadata,
|
withMetadata,
|
||||||
toFormat,
|
toFormat,
|
||||||
jpeg,
|
jpeg,
|
||||||
@@ -1282,6 +1641,7 @@ module.exports = function (Sharp) {
|
|||||||
tiff,
|
tiff,
|
||||||
avif,
|
avif,
|
||||||
heif,
|
heif,
|
||||||
|
jxl,
|
||||||
gif,
|
gif,
|
||||||
raw,
|
raw,
|
||||||
tile,
|
tile,
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
const detectLibc = require('detect-libc');
|
|
||||||
|
|
||||||
const env = process.env;
|
|
||||||
|
|
||||||
module.exports = function () {
|
|
||||||
const arch = env.npm_config_arch || process.arch;
|
|
||||||
const platform = env.npm_config_platform || process.platform;
|
|
||||||
const libc = process.env.npm_config_libc ||
|
|
||||||
/* istanbul ignore next */
|
|
||||||
(detectLibc.isNonGlibcLinuxSync() ? detectLibc.familySync() : '');
|
|
||||||
const libcId = platform !== 'linux' || libc === detectLibc.GLIBC ? '' : libc;
|
|
||||||
|
|
||||||
const platformId = [`${platform}${libcId}`];
|
|
||||||
|
|
||||||
if (arch === 'arm') {
|
|
||||||
const fallback = process.versions.electron ? '7' : '6';
|
|
||||||
platformId.push(`armv${env.npm_config_arm_version || process.config.variables.arm_version || fallback}`);
|
|
||||||
} else if (arch === 'arm64') {
|
|
||||||
platformId.push(`arm64v${env.npm_config_arm_version || '8'}`);
|
|
||||||
} else {
|
|
||||||
platformId.push(arch);
|
|
||||||
}
|
|
||||||
|
|
||||||
return platformId.join('-');
|
|
||||||
};
|
|
||||||
190
lib/resize.js
@@ -1,3 +1,6 @@
|
|||||||
|
// Copyright 2013 Lovell Fuller and others.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const is = require('./is');
|
const is = require('./is');
|
||||||
@@ -36,6 +39,18 @@ const position = {
|
|||||||
'left top': 8
|
'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.
|
* Strategies for automagic cover behaviour.
|
||||||
* @member
|
* @member
|
||||||
@@ -53,10 +68,13 @@ const strategy = {
|
|||||||
*/
|
*/
|
||||||
const kernel = {
|
const kernel = {
|
||||||
nearest: 'nearest',
|
nearest: 'nearest',
|
||||||
|
linear: 'linear',
|
||||||
cubic: 'cubic',
|
cubic: 'cubic',
|
||||||
mitchell: 'mitchell',
|
mitchell: 'mitchell',
|
||||||
lanczos2: 'lanczos2',
|
lanczos2: 'lanczos2',
|
||||||
lanczos3: 'lanczos3'
|
lanczos3: 'lanczos3',
|
||||||
|
mks2013: 'mks2013',
|
||||||
|
mks2021: 'mks2021'
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -89,7 +107,7 @@ const mapFitToCanvas = {
|
|||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
function isRotationExpected (options) {
|
function isRotationExpected (options) {
|
||||||
return (options.angle % 360) !== 0 || options.useExifOrientation === true || options.rotationAngle !== 0;
|
return (options.angle % 360) !== 0 || options.input.autoOrient === true || options.rotationAngle !== 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -103,7 +121,7 @@ function isResizeExpected (options) {
|
|||||||
* Resize image to `width`, `height` or `width x height`.
|
* 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:
|
* When both a `width` and `height` are provided, the possible methods by which the image should **fit** these are:
|
||||||
* - `cover`: (default) Preserving aspect ratio, ensure the image covers both provided dimensions by cropping/clipping to fit.
|
* - `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.
|
* - `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.
|
* - `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.
|
* - `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.
|
||||||
@@ -111,24 +129,32 @@ function isResizeExpected (options) {
|
|||||||
*
|
*
|
||||||
* Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property.
|
* Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property.
|
||||||
*
|
*
|
||||||
* When using a `fit` of `cover` or `contain`, the default **position** is `centre`. Other options are:
|
* <img alt="Examples of various values for the fit property when resizing" width="100%" style="aspect-ratio: 998/243" src="/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.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`.
|
||||||
* - `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`.
|
* - `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`.
|
||||||
* - `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy.
|
* - `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy.
|
||||||
*
|
*
|
||||||
* Some of these values are based on the [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS property.
|
* Some of these values are based on the [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS property.
|
||||||
*
|
*
|
||||||
* The experimental strategy-based approach resizes so one dimension is at its target length
|
* 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.
|
* 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).
|
* - `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.
|
* - `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
|
||||||
*
|
*
|
||||||
* Possible interpolation kernels are:
|
* Possible downsizing kernels are:
|
||||||
* - `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation).
|
* - `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).
|
* - `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).
|
* - `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf).
|
||||||
* - `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`.
|
* - `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`.
|
||||||
* - `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
|
* - `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
|
||||||
|
* - `mks2013`: Use a [Magic Kernel Sharp](https://johncostella.com/magic/mks.pdf) 2013 kernel, as adopted by Facebook.
|
||||||
|
* - `mks2021`: Use a Magic Kernel Sharp 2021 kernel, with more accurate (reduced) sharpening than the 2013 version.
|
||||||
|
*
|
||||||
|
* When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators.
|
||||||
|
* Downsampling kernels without a matching upsampling interpolator map to `cubic`.
|
||||||
*
|
*
|
||||||
* Only one resize can occur per pipeline.
|
* Only one resize can occur per pipeline.
|
||||||
* Previous calls to `resize` in the same pipeline will be ignored.
|
* Previous calls to `resize` in the same pipeline will be ignored.
|
||||||
@@ -214,32 +240,35 @@ function isResizeExpected (options) {
|
|||||||
* .toBuffer()
|
* .toBuffer()
|
||||||
* );
|
* );
|
||||||
*
|
*
|
||||||
* @param {number} [width] - pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height.
|
* @param {number} [width] - 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] - pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width.
|
* @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 {Object} [options]
|
||||||
* @param {String} [options.width] - alternative means of specifying `width`. If both are present this take priority.
|
* @param {number} [options.width] - An alternative means of specifying `width`. If both are present this takes priority.
|
||||||
* @param {String} [options.height] - alternative means of specifying `height`. If both are present this take priority.
|
* @param {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 to fit both provided dimensions, one of `cover`, `contain`, `fill`, `inside` or `outside`.
|
* @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'] - position, gravity or strategy to use when `fit` is `cover` or `contain`.
|
* @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|Object} [options.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency.
|
||||||
* @param {String} [options.kernel='lanczos3'] - the kernel to use for image reduction.
|
* @param {String} [options.kernel='lanczos3'] - The kernel to use for image reduction 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 enlarge if the width *or* height are already less than the specified dimensions, equivalent to GraphicsMagick's `>` geometry option.
|
* @param {Boolean} [options.withoutEnlargement=false] - Do not 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 reduce if the width *or* height are already greater than the specified dimensions, equivalent to GraphicsMagick's `<` geometry option.
|
* @param {Boolean} [options.withoutReduction=false] - Do not 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 on some images.
|
* @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}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid parameters
|
* @throws {Error} Invalid parameters
|
||||||
*/
|
*/
|
||||||
function resize (width, height, options) {
|
function resize (widthOrOptions, height, options) {
|
||||||
if (isResizeExpected(this.options)) {
|
if (isResizeExpected(this.options)) {
|
||||||
this.options.debuglog('ignoring previous resize options');
|
this.options.debuglog('ignoring previous resize options');
|
||||||
}
|
}
|
||||||
if (is.defined(width)) {
|
if (this.options.widthPost !== -1) {
|
||||||
if (is.object(width) && !is.defined(options)) {
|
this.options.debuglog('operation order will be: extract, resize, extract');
|
||||||
options = width;
|
}
|
||||||
} else if (is.integer(width) && width > 0) {
|
if (is.defined(widthOrOptions)) {
|
||||||
this.options.width = width;
|
if (is.object(widthOrOptions) && !is.defined(options)) {
|
||||||
|
options = widthOrOptions;
|
||||||
|
} else if (is.integer(widthOrOptions) && widthOrOptions > 0) {
|
||||||
|
this.options.width = widthOrOptions;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('width', 'positive integer', width);
|
throw is.invalidParameterError('width', 'positive integer', widthOrOptions);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
this.options.width = -1;
|
this.options.width = -1;
|
||||||
@@ -320,7 +349,8 @@ function resize (width, height, options) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Extends/pads the edges of the image with the provided background colour.
|
* 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.
|
* This operation will always occur after resizing and extraction, if any.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
@@ -346,11 +376,21 @@ function resize (width, height, options) {
|
|||||||
* })
|
* })
|
||||||
* ...
|
* ...
|
||||||
*
|
*
|
||||||
|
* @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|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.top=0]
|
||||||
* @param {number} [extend.left=0]
|
* @param {number} [extend.left=0]
|
||||||
* @param {number} [extend.bottom=0]
|
* @param {number} [extend.bottom=0]
|
||||||
* @param {number} [extend.right=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.
|
* @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}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid parameters
|
* @throws {Error} Invalid parameters
|
||||||
@@ -391,6 +431,13 @@ function extend (extend) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
this._setBackgroundColourOption('extendBackground', extend.background);
|
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 {
|
} else {
|
||||||
throw is.invalidParameterError('extend', 'integer or object', extend);
|
throw is.invalidParameterError('extend', 'integer or object', extend);
|
||||||
}
|
}
|
||||||
@@ -402,7 +449,7 @@ function extend (extend) {
|
|||||||
*
|
*
|
||||||
* - Use `extract` before `resize` for pre-resize extraction.
|
* - Use `extract` before `resize` for pre-resize extraction.
|
||||||
* - Use `extract` after `resize` for post-resize extraction.
|
* - Use `extract` after `resize` for post-resize extraction.
|
||||||
* - Use `extract` before and after for both.
|
* - Use `extract` twice and `resize` once for extract-then-resize-then-extract in a fixed operation order.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* sharp(input)
|
* sharp(input)
|
||||||
@@ -428,7 +475,7 @@ function extend (extend) {
|
|||||||
* @throws {Error} Invalid parameters
|
* @throws {Error} Invalid parameters
|
||||||
*/
|
*/
|
||||||
function extract (options) {
|
function extract (options) {
|
||||||
const suffix = isResizeExpected(this.options) || isRotationExpected(this.options) ? 'Post' : 'Pre';
|
const suffix = isResizeExpected(this.options) || this.options.widthPre !== -1 ? 'Post' : 'Pre';
|
||||||
if (this.options[`width${suffix}`] !== -1) {
|
if (this.options[`width${suffix}`] !== -1) {
|
||||||
this.options.debuglog('ignoring previous extract options');
|
this.options.debuglog('ignoring previous extract options');
|
||||||
}
|
}
|
||||||
@@ -456,73 +503,67 @@ function extract (options) {
|
|||||||
*
|
*
|
||||||
* If the result of this operation would trim an image to nothing then no change is made.
|
* If the result of this operation would trim an image to nothing then no change is made.
|
||||||
*
|
*
|
||||||
* The `info` response Object, obtained from callback of `.toFile()` or `.toBuffer()`,
|
* The `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` properties.
|
||||||
* will contain `trimOffsetLeft` and `trimOffsetTop` properties.
|
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* // Trim pixels with a colour similar to that of the top-left pixel.
|
* // Trim pixels with a colour similar to that of the top-left pixel.
|
||||||
* sharp(input)
|
* await sharp(input)
|
||||||
* .trim()
|
* .trim()
|
||||||
* .toFile(output, function(err, info) {
|
* .toFile(output);
|
||||||
* ...
|
*
|
||||||
* });
|
|
||||||
* @example
|
* @example
|
||||||
* // Trim pixels with the exact same colour as that of the top-left pixel.
|
* // Trim pixels with the exact same colour as that of the top-left pixel.
|
||||||
* sharp(input)
|
* await sharp(input)
|
||||||
* .trim(0)
|
* .trim({
|
||||||
* .toFile(output, function(err, info) {
|
* threshold: 0
|
||||||
* ...
|
* })
|
||||||
* });
|
* .toFile(output);
|
||||||
|
*
|
||||||
* @example
|
* @example
|
||||||
* // Trim only pixels with a similar colour to red.
|
* // Assume input is line art and trim only pixels with a similar colour to red.
|
||||||
* sharp(input)
|
* const output = await sharp(input)
|
||||||
* .trim("#FF0000")
|
* .trim({
|
||||||
* .toFile(output, function(err, info) {
|
* background: "#FF0000",
|
||||||
* ...
|
* lineArt: true
|
||||||
* });
|
* })
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
* @example
|
* @example
|
||||||
* // Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
|
* // Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
|
||||||
* sharp(input)
|
* const output = await sharp(input)
|
||||||
* .trim({
|
* .trim({
|
||||||
* background: "yellow",
|
* background: "yellow",
|
||||||
* threshold: 42,
|
* threshold: 42,
|
||||||
* })
|
* })
|
||||||
* .toFile(output, function(err, info) {
|
* .toBuffer();
|
||||||
* ...
|
|
||||||
* });
|
|
||||||
*
|
*
|
||||||
* @param {string|number|Object} trim - the specific background colour to trim, the threshold for doing so or an Object with both.
|
* @param {Object} [options]
|
||||||
* @param {string|Object} [trim.background='top-left pixel'] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel.
|
* @param {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} [trim.threshold=10] - the allowed difference from the above colour, a positive number.
|
* @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}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid parameters
|
* @throws {Error} Invalid parameters
|
||||||
*/
|
*/
|
||||||
function trim (trim) {
|
function trim (options) {
|
||||||
if (!is.defined(trim)) {
|
this.options.trimThreshold = 10;
|
||||||
this.options.trimThreshold = 10;
|
if (is.defined(options)) {
|
||||||
} else if (is.string(trim)) {
|
if (is.object(options)) {
|
||||||
this._setBackgroundColourOption('trimBackground', trim);
|
if (is.defined(options.background)) {
|
||||||
this.options.trimThreshold = 10;
|
this._setBackgroundColourOption('trimBackground', options.background);
|
||||||
} else if (is.number(trim)) {
|
|
||||||
if (trim >= 0) {
|
|
||||||
this.options.trimThreshold = trim;
|
|
||||||
} else {
|
|
||||||
throw is.invalidParameterError('threshold', 'positive number', trim);
|
|
||||||
}
|
|
||||||
} else if (is.object(trim)) {
|
|
||||||
this._setBackgroundColourOption('trimBackground', trim.background);
|
|
||||||
|
|
||||||
if (!is.defined(trim.threshold)) {
|
|
||||||
this.options.trimThreshold = 10;
|
|
||||||
} else if (is.number(trim.threshold)) {
|
|
||||||
if (trim.threshold >= 0) {
|
|
||||||
this.options.trimThreshold = trim.threshold;
|
|
||||||
} else {
|
|
||||||
throw is.invalidParameterError('threshold', 'positive number', trim);
|
|
||||||
}
|
}
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
throw is.invalidParameterError('trim', 'string, number or object', trim);
|
|
||||||
}
|
}
|
||||||
if (isRotationExpected(this.options)) {
|
if (isRotationExpected(this.options)) {
|
||||||
this.options.rotateBeforePreExtract = true;
|
this.options.rotateBeforePreExtract = true;
|
||||||
@@ -532,6 +573,7 @@ function trim (trim) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Decorate the Sharp prototype with resize-related functions.
|
* Decorate the Sharp prototype with resize-related functions.
|
||||||
|
* @module Sharp
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
module.exports = function (Sharp) {
|
module.exports = function (Sharp) {
|
||||||
|
|||||||
133
lib/sharp.js
@@ -1,35 +1,122 @@
|
|||||||
|
// Copyright 2013 Lovell Fuller and others.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const platformAndArch = require('./platform')();
|
// 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 */
|
/* istanbul ignore next */
|
||||||
try {
|
if (sharp && path.startsWith('@img/sharp-linux-x64') && !sharp._isUsingX64V2()) {
|
||||||
module.exports = require(`../build/Release/sharp-${platformAndArch}.node`);
|
const err = new Error('Prebuilt binaries for linux-x64 require v2 microarchitecture');
|
||||||
} catch (err) {
|
err.code = 'Unsupported CPU';
|
||||||
// Bail early if bindings aren't available
|
errors.push(err);
|
||||||
const help = ['', 'Something went wrong installing the "sharp" module', '', err.message, '', 'Possible solutions:'];
|
sharp = null;
|
||||||
if (/dylib/.test(err.message) && /Incompatible library version/.test(err.message)) {
|
}
|
||||||
help.push('- Update Homebrew: "brew update && brew upgrade vips"');
|
|
||||||
} else {
|
/* istanbul ignore next */
|
||||||
const [platform, arch] = platformAndArch.split('-');
|
if (sharp) {
|
||||||
if (platform === 'linux' && /Module did not self-register/.test(err.message)) {
|
module.exports = sharp;
|
||||||
help.push('- Using worker threads? See https://sharp.pixelplumbing.com/install#worker-threads');
|
} 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(
|
help.push(
|
||||||
'- Install with verbose logging and look for errors: "npm install --ignore-scripts=false --foreground-scripts --verbose sharp"',
|
'- Please upgrade Node.js:',
|
||||||
`- Install for the current ${platformAndArch} runtime: "npm install --platform=${platform} --arch=${arch} sharp"`
|
` 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(
|
help.push(
|
||||||
'- Consult the installation documentation: https://sharp.pixelplumbing.com/install'
|
'- Consult the installation documentation:',
|
||||||
|
' See https://sharp.pixelplumbing.com/install'
|
||||||
);
|
);
|
||||||
// Check loaded
|
|
||||||
if (process.platform === 'win32' || /symbol/.test(err.message)) {
|
|
||||||
const loadedModule = Object.keys(require.cache).find((i) => /[\\/]build[\\/]Release[\\/]sharp(.*)\.node$/.test(i));
|
|
||||||
if (loadedModule) {
|
|
||||||
const [, loadedPackage] = loadedModule.match(/node_modules[\\/]([^\\/]+)[\\/]/);
|
|
||||||
help.push(`- Ensure the version of sharp aligns with the ${loadedPackage} package: "npm ls sharp"`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw new Error(help.join('\n'));
|
throw new Error(help.join('\n'));
|
||||||
}
|
}
|
||||||
|
|||||||
150
lib/utility.js
@@ -1,14 +1,18 @@
|
|||||||
|
// Copyright 2013 Lovell Fuller and others.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const fs = require('fs');
|
const events = require('node:events');
|
||||||
const path = require('path');
|
|
||||||
const events = require('events');
|
|
||||||
const detectLibc = require('detect-libc');
|
const detectLibc = require('detect-libc');
|
||||||
|
|
||||||
const is = require('./is');
|
const is = require('./is');
|
||||||
const platformAndArch = require('./platform')();
|
const { runtimePlatformArch } = require('./libvips');
|
||||||
const sharp = require('./sharp');
|
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.
|
* An Object containing nested boolean values representing the available input and output formats/methods.
|
||||||
* @member
|
* @member
|
||||||
@@ -43,32 +47,40 @@ const interpolators = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An Object containing the version numbers of libvips and its dependencies.
|
* An Object containing the version numbers of sharp, libvips
|
||||||
|
* and (when using prebuilt binaries) its dependencies.
|
||||||
|
*
|
||||||
* @member
|
* @member
|
||||||
* @example
|
* @example
|
||||||
* console.log(sharp.versions);
|
* console.log(sharp.versions);
|
||||||
*/
|
*/
|
||||||
let versions = {
|
let versions = {
|
||||||
vips: sharp.libvipsVersion()
|
vips: libvipsVersion.semver
|
||||||
};
|
};
|
||||||
try {
|
/* istanbul ignore next */
|
||||||
versions = require(`../vendor/${versions.vips}/${platformAndArch}/versions.json`);
|
if (!libvipsVersion.isGlobal) {
|
||||||
} catch (_err) { /* ignore */ }
|
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 */
|
||||||
* An Object containing the platform and architecture
|
if (versions.heif && format.heif) {
|
||||||
* of the current and installed vendored binaries.
|
// Prebuilt binaries provide AV1
|
||||||
* @member
|
format.heif.input.fileSuffix = ['.avif'];
|
||||||
* @example
|
format.heif.output.alias = ['avif'];
|
||||||
* console.log(sharp.vendor);
|
}
|
||||||
*/
|
|
||||||
const vendor = {
|
|
||||||
current: platformAndArch,
|
|
||||||
installed: []
|
|
||||||
};
|
|
||||||
try {
|
|
||||||
vendor.installed = fs.readdirSync(path.join(__dirname, `../vendor/${versions.vips}`));
|
|
||||||
} catch (_err) { /* ignore */ }
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets or, when options are provided, sets the limits of _libvips'_ operation cache.
|
* Gets or, when options are provided, sets the limits of _libvips'_ operation cache.
|
||||||
@@ -123,15 +135,9 @@ cache(true);
|
|||||||
* e.g. libaom manages its own 4 threads when encoding AVIF images,
|
* e.g. libaom manages its own 4 threads when encoding AVIF images,
|
||||||
* and these are independent of the value set here.
|
* and these are independent of the value set here.
|
||||||
*
|
*
|
||||||
* The maximum number of images that sharp can process in parallel
|
* :::note
|
||||||
* is controlled by libuv's `UV_THREADPOOL_SIZE` environment variable,
|
* Further {@link /performance|control over performance} is available.
|
||||||
* which defaults to 4.
|
* :::
|
||||||
*
|
|
||||||
* https://nodejs.org/api/cli.html#uv_threadpool_sizesize
|
|
||||||
*
|
|
||||||
* For example, by default, a machine with 8 CPU cores will process
|
|
||||||
* 4 images in parallel and use up to 8 threads per image,
|
|
||||||
* so there will be up to 32 concurrent threads.
|
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* const threads = sharp.concurrency(); // 4
|
* const threads = sharp.concurrency(); // 4
|
||||||
@@ -148,6 +154,9 @@ function concurrency (concurrency) {
|
|||||||
if (detectLibc.familySync() === detectLibc.GLIBC && !sharp._isUsingJemalloc()) {
|
if (detectLibc.familySync() === detectLibc.GLIBC && !sharp._isUsingJemalloc()) {
|
||||||
// Reduce default concurrency to 1 when using glibc memory allocator
|
// Reduce default concurrency to 1 when using glibc memory allocator
|
||||||
sharp.concurrency(1);
|
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());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -178,17 +187,17 @@ function counters () {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Get and set use of SIMD vector unit instructions.
|
* Get and set use of SIMD vector unit instructions.
|
||||||
* Requires libvips to have been compiled with liborc support.
|
* Requires libvips to have been compiled with highway support.
|
||||||
*
|
*
|
||||||
* Improves the performance of `resize`, `blur` and `sharpen` operations
|
* 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.
|
* by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* const simd = sharp.simd();
|
* const simd = sharp.simd();
|
||||||
* // simd is `true` if the runtime use of liborc is currently enabled
|
* // simd is `true` if the runtime use of highway is currently enabled
|
||||||
* @example
|
* @example
|
||||||
* const simd = sharp.simd(false);
|
* const simd = sharp.simd(false);
|
||||||
* // prevent libvips from using liborc at runtime
|
* // prevent libvips from using highway at runtime
|
||||||
*
|
*
|
||||||
* @param {boolean} [simd=true]
|
* @param {boolean} [simd=true]
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
@@ -196,10 +205,76 @@ function counters () {
|
|||||||
function simd (simd) {
|
function simd (simd) {
|
||||||
return sharp.simd(is.bool(simd) ? simd : null);
|
return sharp.simd(is.bool(simd) ? simd : null);
|
||||||
}
|
}
|
||||||
simd(true);
|
|
||||||
|
/**
|
||||||
|
* 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.
|
* Decorate the Sharp class with utility-related functions.
|
||||||
|
* @module Sharp
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
module.exports = function (Sharp) {
|
module.exports = function (Sharp) {
|
||||||
@@ -210,6 +285,7 @@ module.exports = function (Sharp) {
|
|||||||
Sharp.format = format;
|
Sharp.format = format;
|
||||||
Sharp.interpolators = interpolators;
|
Sharp.interpolators = interpolators;
|
||||||
Sharp.versions = versions;
|
Sharp.versions = versions;
|
||||||
Sharp.vendor = vendor;
|
|
||||||
Sharp.queue = queue;
|
Sharp.queue = queue;
|
||||||
|
Sharp.block = block;
|
||||||
|
Sharp.unblock = unblock;
|
||||||
};
|
};
|
||||||
|
|||||||
40
npm/darwin-arm64/package.json
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
{
|
||||||
|
"name": "@img/sharp-darwin-arm64",
|
||||||
|
"version": "0.34.3",
|
||||||
|
"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"
|
||||||
|
]
|
||||||
|
}
|
||||||
40
npm/darwin-x64/package.json
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
{
|
||||||
|
"name": "@img/sharp-darwin-x64",
|
||||||
|
"version": "0.34.3",
|
||||||
|
"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
@@ -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);
|
||||||
|
}
|
||||||
46
npm/linux-arm/package.json
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
{
|
||||||
|
"name": "@img/sharp-linux-arm",
|
||||||
|
"version": "0.34.3",
|
||||||
|
"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"
|
||||||
|
]
|
||||||
|
}
|
||||||
46
npm/linux-arm64/package.json
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
{
|
||||||
|
"name": "@img/sharp-linux-arm64",
|
||||||
|
"version": "0.34.3",
|
||||||
|
"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"
|
||||||
|
]
|
||||||
|
}
|
||||||
46
npm/linux-ppc64/package.json
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
{
|
||||||
|
"name": "@img/sharp-linux-ppc64",
|
||||||
|
"version": "0.34.3",
|
||||||
|
"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"
|
||||||
|
]
|
||||||
|
}
|
||||||
46
npm/linux-s390x/package.json
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
{
|
||||||
|
"name": "@img/sharp-linux-s390x",
|
||||||
|
"version": "0.34.3",
|
||||||
|
"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"
|
||||||
|
]
|
||||||
|
}
|
||||||
46
npm/linux-x64/package.json
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
{
|
||||||
|
"name": "@img/sharp-linux-x64",
|
||||||
|
"version": "0.34.3",
|
||||||
|
"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"
|
||||||
|
]
|
||||||
|
}
|
||||||
46
npm/linuxmusl-arm64/package.json
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
{
|
||||||
|
"name": "@img/sharp-linuxmusl-arm64",
|
||||||
|
"version": "0.34.3",
|
||||||
|
"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"
|
||||||
|
]
|
||||||
|
}
|
||||||
46
npm/linuxmusl-x64/package.json
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
{
|
||||||
|
"name": "@img/sharp-linuxmusl-x64",
|
||||||
|
"version": "0.34.3",
|
||||||
|
"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
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"name": "@img/sharp",
|
||||||
|
"version": "0.34.3",
|
||||||
|
"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
@@ -0,0 +1,39 @@
|
|||||||
|
{
|
||||||
|
"name": "@img/sharp-wasm32",
|
||||||
|
"version": "0.34.3",
|
||||||
|
"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"
|
||||||
|
]
|
||||||
|
}
|
||||||
39
npm/win32-arm64/package.json
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
{
|
||||||
|
"name": "@img/sharp-win32-arm64",
|
||||||
|
"version": "0.34.3",
|
||||||
|
"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"
|
||||||
|
]
|
||||||
|
}
|
||||||
39
npm/win32-ia32/package.json
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
{
|
||||||
|
"name": "@img/sharp-win32-ia32",
|
||||||
|
"version": "0.34.3",
|
||||||
|
"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"
|
||||||
|
]
|
||||||
|
}
|
||||||
39
npm/win32-x64/package.json
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
{
|
||||||
|
"name": "@img/sharp-win32-x64",
|
||||||
|
"version": "0.34.3",
|
||||||
|
"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"
|
||||||
|
]
|
||||||
|
}
|
||||||
139
package.json
@@ -1,9 +1,9 @@
|
|||||||
{
|
{
|
||||||
"name": "sharp",
|
"name": "sharp",
|
||||||
"description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images",
|
"description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images",
|
||||||
"version": "0.31.0",
|
"version": "0.34.3",
|
||||||
"author": "Lovell Fuller <npm@lovell.info>",
|
"author": "Lovell Fuller <npm@lovell.info>",
|
||||||
"homepage": "https://github.com/lovell/sharp",
|
"homepage": "https://sharp.pixelplumbing.com",
|
||||||
"contributors": [
|
"contributors": [
|
||||||
"Pierre Inglebert <pierre.inglebert@gmail.com>",
|
"Pierre Inglebert <pierre.inglebert@gmail.com>",
|
||||||
"Jonathan Ong <jonathanrichardong@gmail.com>",
|
"Jonathan Ong <jonathanrichardong@gmail.com>",
|
||||||
@@ -82,34 +82,40 @@
|
|||||||
"Joris Dugué <zaruike10@gmail.com>",
|
"Joris Dugué <zaruike10@gmail.com>",
|
||||||
"Chris Banks <christopher.bradley.banks@gmail.com>",
|
"Chris Banks <christopher.bradley.banks@gmail.com>",
|
||||||
"Ompal Singh <ompal.hitm09@gmail.com>",
|
"Ompal Singh <ompal.hitm09@gmail.com>",
|
||||||
"Brodan <christopher.hranj@gmail.com",
|
"Brodan <christopher.hranj@gmail.com>",
|
||||||
"Ankur Parihar <ankur.github@gmail.com>",
|
"Ankur Parihar <ankur.github@gmail.com>",
|
||||||
"Brahim Ait elhaj <brahima@gmail.com>",
|
"Brahim Ait elhaj <brahima@gmail.com>",
|
||||||
"Mart Jansink <m.jansink@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": {
|
"scripts": {
|
||||||
"install": "(node install/libvips && node install/dll-copy && prebuild-install) || (node install/can-compile && node-gyp rebuild && node install/dll-copy)",
|
"install": "node install/check.js",
|
||||||
"clean": "rm -rf node_modules/ build/ vendor/ .nyc_output/ coverage/ test/fixtures/output.*",
|
"clean": "rm -rf src/build/ .nyc_output/ coverage/ test/fixtures/output.*",
|
||||||
"test": "npm run test-lint && npm run test-unit && npm run test-licensing",
|
"test": "npm run test-lint && npm run test-unit && npm run test-licensing && npm run test-types",
|
||||||
"test-lint": "semistandard && cpplint",
|
"test-lint": "semistandard && cpplint",
|
||||||
"test-unit": "nyc --reporter=lcov --branches=99 mocha --slow=1000 --timeout=60000 ./test/unit/*.js",
|
"test-unit": "nyc --reporter=lcov --reporter=text --check-coverage --branches=100 mocha",
|
||||||
"test-licensing": "license-checker --production --summary --onlyAllow=\"Apache-2.0;BSD;ISC;MIT\"",
|
"test-licensing": "license-checker --production --summary --onlyAllow=\"Apache-2.0;BSD;ISC;LGPL-3.0-or-later;MIT\"",
|
||||||
"test-coverage": "./test/coverage/report.sh",
|
|
||||||
"test-leak": "./test/leak/leak.sh",
|
"test-leak": "./test/leak/leak.sh",
|
||||||
"docs-build": "documentation lint lib && node docs/build && node docs/search-index/build",
|
"test-types": "tsd",
|
||||||
"docs-serve": "cd docs && npx serve",
|
"package-from-local-build": "node npm/from-local-build.js",
|
||||||
"docs-publish": "cd docs && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp"
|
"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",
|
"main": "lib/index.js",
|
||||||
|
"types": "lib/index.d.ts",
|
||||||
"files": [
|
"files": [
|
||||||
"binding.gyp",
|
"install",
|
||||||
"install/**",
|
"lib",
|
||||||
"lib/**",
|
"src/*.{cc,h,gyp}"
|
||||||
"src/**"
|
|
||||||
],
|
],
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git://github.com/lovell/sharp"
|
"url": "git://github.com/lovell/sharp.git"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"jpeg",
|
"jpeg",
|
||||||
@@ -131,59 +137,66 @@
|
|||||||
],
|
],
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"color": "^4.2.3",
|
"color": "^4.2.3",
|
||||||
"detect-libc": "^2.0.1",
|
"detect-libc": "^2.0.4",
|
||||||
"node-addon-api": "^5.0.0",
|
"semver": "^7.7.2"
|
||||||
"prebuild-install": "^7.1.1",
|
},
|
||||||
"semver": "^7.3.7",
|
"optionalDependencies": {
|
||||||
"simple-get": "^4.0.1",
|
"@img/sharp-darwin-arm64": "0.34.3",
|
||||||
"tar-fs": "^2.1.1",
|
"@img/sharp-darwin-x64": "0.34.3",
|
||||||
"tunnel-agent": "^0.6.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",
|
||||||
|
"@img/sharp-linux-arm64": "0.34.3",
|
||||||
|
"@img/sharp-linux-ppc64": "0.34.3",
|
||||||
|
"@img/sharp-linux-s390x": "0.34.3",
|
||||||
|
"@img/sharp-linux-x64": "0.34.3",
|
||||||
|
"@img/sharp-linuxmusl-arm64": "0.34.3",
|
||||||
|
"@img/sharp-linuxmusl-x64": "0.34.3",
|
||||||
|
"@img/sharp-wasm32": "0.34.3",
|
||||||
|
"@img/sharp-win32-arm64": "0.34.3",
|
||||||
|
"@img/sharp-win32-ia32": "0.34.3",
|
||||||
|
"@img/sharp-win32-x64": "0.34.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"async": "^3.2.4",
|
"@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",
|
"cc": "^3.0.1",
|
||||||
"documentation": "^14.0.0",
|
"emnapi": "^1.4.4",
|
||||||
"exif-reader": "^1.0.3",
|
"exif-reader": "^2.0.2",
|
||||||
"extract-zip": "^2.0.1",
|
"extract-zip": "^2.0.1",
|
||||||
"icc": "^2.0.0",
|
"icc": "^3.0.0",
|
||||||
|
"jsdoc-to-markdown": "^9.1.1",
|
||||||
"license-checker": "^25.0.1",
|
"license-checker": "^25.0.1",
|
||||||
"mocha": "^10.0.0",
|
"mocha": "^11.7.1",
|
||||||
"mock-fs": "^5.1.4",
|
"node-addon-api": "^8.4.0",
|
||||||
"nyc": "^15.1.0",
|
"node-gyp": "^11.2.0",
|
||||||
"prebuild": "^11.0.4",
|
"nyc": "^17.1.0",
|
||||||
"rimraf": "^3.0.2",
|
"semistandard": "^17.0.0",
|
||||||
"semistandard": "^16.0.1"
|
"tar-fs": "^3.1.0",
|
||||||
|
"tsd": "^0.32.0"
|
||||||
},
|
},
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"config": {
|
|
||||||
"libvips": "8.13.1",
|
|
||||||
"integrity": {
|
|
||||||
"darwin-arm64v8": "sha512-JdpGTx67RDbvRkg3ljFvTzqoq+oBXmMdDFEp0expDYXmP5HLH+GCkikmsROlGltgfKE2KqL/qwpxTEhIwMK/3A==",
|
|
||||||
"darwin-x64": "sha512-0Oh4/hEDnzV+X8MiiyUQ4G/Zh/MHw9rKstfuX0P1czgaxS2hX8Pxdbzdk1oqwTOEYVEGO/hMm9ItCVZ3RVPPaA==",
|
|
||||||
"linux-arm64v8": "sha512-9pSlPzEojt6ue5vXfASNMhQO1YS1p4i4Wydu+bzOfMtIPSBRXbu/+y8WELbbo03Ts7pftm9KtrMHitCVdy5EXw==",
|
|
||||||
"linux-armv6": "sha512-sv2FqS/ggpQly7h5/+nh8txQDulolE5ptaE90PO7iwfTont8N42pudeqootWKsuf0fRmkW4M92184VfVVYCvGw==",
|
|
||||||
"linux-armv7": "sha512-LmQIB8FDfasK6BsFhnE7ZI3LMlxh/rF5tZRNQ/uoTbF2xrtWQqqgiZgCifJByiEM+1tR7RxwNdnjxZhWvM9WmQ==",
|
|
||||||
"linux-x64": "sha512-JBRf8WBnlVw/K1jpSvmeZpnGZGjeqhG2NDEiQV/hUze3zgDGwDza4oiworaQExQmKcDrc2LJKF14Nsz1qQSNJw==",
|
|
||||||
"linuxmusl-arm64v8": "sha512-yzUQO5isDwsRpEUxbMXBeWp0sKhWghebrSK46SUF5mvB/kq6hZ7JbRuJ2aZjE84K/HUTyuCc0kE+M3m8naOs+g==",
|
|
||||||
"linuxmusl-x64": "sha512-H3Vz1QaaZ6X5iEbfPST7TPFwDO01tI8dk1osLm6l4a17BWCaOMaBQlqxgTgYrtd09JJ9CvGoq5fo5j5TPxUc4Q==",
|
|
||||||
"win32-arm64v8": "sha512-b5Ver+uwOJhdOGqvZVM+qF2KLKcowcac/wKK5Fg0czqlSMqP/KxDF2kxw2eKXUJNgfqe4eDH1QG/yTg2pQSetQ==",
|
|
||||||
"win32-ia32": "sha512-h/SJ/Yfn0ce9H70vt1wS8rZ4PfHnguCCTsOGik7e6O/e2AlBQOM0mKsPIB9jSOquoCP8rP0qF6AOPOjXKnCk+w==",
|
|
||||||
"win32-x64": "sha512-p9qpdWdhZooPteib92Kk+qF1vvzcScxvOwdIP8muhgo/A8uDI4/mqXCpEbMBw6vjETKlS3qo2JUbVF6+0/lyWQ=="
|
|
||||||
},
|
|
||||||
"runtime": "napi",
|
|
||||||
"target": 7
|
|
||||||
},
|
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=14.15.0"
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
|
},
|
||||||
|
"config": {
|
||||||
|
"libvips": ">=8.17.1"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
},
|
},
|
||||||
"binary": {
|
|
||||||
"napi_versions": [
|
|
||||||
7
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"semistandard": {
|
"semistandard": {
|
||||||
"env": [
|
"env": [
|
||||||
"mocha"
|
"mocha"
|
||||||
@@ -194,5 +207,13 @@
|
|||||||
"filter": [
|
"filter": [
|
||||||
"build/include"
|
"build/include"
|
||||||
]
|
]
|
||||||
|
},
|
||||||
|
"nyc": {
|
||||||
|
"include": [
|
||||||
|
"lib"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"tsd": {
|
||||||
|
"directory": "test/types/"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
299
src/binding.gyp
Normal 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'
|
||||||
|
]
|
||||||
|
}]
|
||||||
|
}]
|
||||||
|
]
|
||||||
|
}]
|
||||||
|
}
|
||||||
336
src/common.cc
@@ -1,16 +1,5 @@
|
|||||||
// Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Lovell Fuller and contributors.
|
// Copyright 2013 Lovell Fuller and others.
|
||||||
//
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
// 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
|
|
||||||
//
|
|
||||||
// http://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.
|
|
||||||
|
|
||||||
#include <cstdlib>
|
#include <cstdlib>
|
||||||
#include <string>
|
#include <string>
|
||||||
@@ -86,13 +75,17 @@ namespace sharp {
|
|||||||
Napi::Buffer<char> buffer = input.Get("buffer").As<Napi::Buffer<char>>();
|
Napi::Buffer<char> buffer = input.Get("buffer").As<Napi::Buffer<char>>();
|
||||||
descriptor->bufferLength = buffer.Length();
|
descriptor->bufferLength = buffer.Length();
|
||||||
descriptor->buffer = buffer.Data();
|
descriptor->buffer = buffer.Data();
|
||||||
descriptor->isBuffer = TRUE;
|
descriptor->isBuffer = true;
|
||||||
}
|
}
|
||||||
descriptor->failOn = AttrAsEnum<VipsFailOn>(input, "failOn", VIPS_TYPE_FAIL_ON);
|
descriptor->failOn = AttrAsEnum<VipsFailOn>(input, "failOn", VIPS_TYPE_FAIL_ON);
|
||||||
// Density for vector-based input
|
// Density for vector-based input
|
||||||
if (HasAttr(input, "density")) {
|
if (HasAttr(input, "density")) {
|
||||||
descriptor->density = AttrAsDouble(input, "density");
|
descriptor->density = AttrAsDouble(input, "density");
|
||||||
}
|
}
|
||||||
|
// Should we ignore any embedded ICC profile
|
||||||
|
if (HasAttr(input, "ignoreIcc")) {
|
||||||
|
descriptor->ignoreIcc = AttrAsBool(input, "ignoreIcc");
|
||||||
|
}
|
||||||
// Raw pixel input
|
// Raw pixel input
|
||||||
if (HasAttr(input, "rawChannels")) {
|
if (HasAttr(input, "rawChannels")) {
|
||||||
descriptor->rawDepth = AttrAsEnum<VipsBandFormat>(input, "rawDepth", VIPS_TYPE_BAND_FORMAT);
|
descriptor->rawDepth = AttrAsEnum<VipsBandFormat>(input, "rawDepth", VIPS_TYPE_BAND_FORMAT);
|
||||||
@@ -100,6 +93,7 @@ namespace sharp {
|
|||||||
descriptor->rawWidth = AttrAsUint32(input, "rawWidth");
|
descriptor->rawWidth = AttrAsUint32(input, "rawWidth");
|
||||||
descriptor->rawHeight = AttrAsUint32(input, "rawHeight");
|
descriptor->rawHeight = AttrAsUint32(input, "rawHeight");
|
||||||
descriptor->rawPremultiplied = AttrAsBool(input, "rawPremultiplied");
|
descriptor->rawPremultiplied = AttrAsBool(input, "rawPremultiplied");
|
||||||
|
descriptor->rawPageHeight = AttrAsUint32(input, "rawPageHeight");
|
||||||
}
|
}
|
||||||
// Multi-page input (GIF, TIFF, PDF)
|
// Multi-page input (GIF, TIFF, PDF)
|
||||||
if (HasAttr(input, "pages")) {
|
if (HasAttr(input, "pages")) {
|
||||||
@@ -108,19 +102,35 @@ namespace sharp {
|
|||||||
if (HasAttr(input, "page")) {
|
if (HasAttr(input, "page")) {
|
||||||
descriptor->page = AttrAsUint32(input, "page");
|
descriptor->page = AttrAsUint32(input, "page");
|
||||||
}
|
}
|
||||||
|
// SVG
|
||||||
|
if (HasAttr(input, "svgStylesheet")) {
|
||||||
|
descriptor->svgStylesheet = AttrAsStr(input, "svgStylesheet");
|
||||||
|
}
|
||||||
|
if (HasAttr(input, "svgHighBitdepth")) {
|
||||||
|
descriptor->svgHighBitdepth = AttrAsBool(input, "svgHighBitdepth");
|
||||||
|
}
|
||||||
// Multi-level input (OpenSlide)
|
// Multi-level input (OpenSlide)
|
||||||
if (HasAttr(input, "level")) {
|
if (HasAttr(input, "openSlideLevel")) {
|
||||||
descriptor->level = AttrAsUint32(input, "level");
|
descriptor->openSlideLevel = AttrAsUint32(input, "openSlideLevel");
|
||||||
}
|
}
|
||||||
// subIFD (OME-TIFF)
|
// subIFD (OME-TIFF)
|
||||||
if (HasAttr(input, "subifd")) {
|
if (HasAttr(input, "subifd")) {
|
||||||
descriptor->subifd = AttrAsInt32(input, "subifd");
|
descriptor->tiffSubifd = AttrAsInt32(input, "tiffSubifd");
|
||||||
|
}
|
||||||
|
// // PDF background color
|
||||||
|
if (HasAttr(input, "pdfBackground")) {
|
||||||
|
descriptor->pdfBackground = AttrAsVectorOfDouble(input, "pdfBackground");
|
||||||
|
}
|
||||||
|
// Use JPEG 2000 oneshot mode?
|
||||||
|
if (HasAttr(input, "jp2Oneshot")) {
|
||||||
|
descriptor->jp2Oneshot = AttrAsBool(input, "jp2Oneshot");
|
||||||
}
|
}
|
||||||
// Create new image
|
// Create new image
|
||||||
if (HasAttr(input, "createChannels")) {
|
if (HasAttr(input, "createChannels")) {
|
||||||
descriptor->createChannels = AttrAsUint32(input, "createChannels");
|
descriptor->createChannels = AttrAsUint32(input, "createChannels");
|
||||||
descriptor->createWidth = AttrAsUint32(input, "createWidth");
|
descriptor->createWidth = AttrAsUint32(input, "createWidth");
|
||||||
descriptor->createHeight = AttrAsUint32(input, "createHeight");
|
descriptor->createHeight = AttrAsUint32(input, "createHeight");
|
||||||
|
descriptor->createPageHeight = AttrAsUint32(input, "createPageHeight");
|
||||||
if (HasAttr(input, "createNoiseType")) {
|
if (HasAttr(input, "createNoiseType")) {
|
||||||
descriptor->createNoiseType = AttrAsStr(input, "createNoiseType");
|
descriptor->createNoiseType = AttrAsStr(input, "createNoiseType");
|
||||||
descriptor->createNoiseMean = AttrAsDouble(input, "createNoiseMean");
|
descriptor->createNoiseMean = AttrAsDouble(input, "createNoiseMean");
|
||||||
@@ -159,21 +169,46 @@ namespace sharp {
|
|||||||
if (HasAttr(input, "textSpacing")) {
|
if (HasAttr(input, "textSpacing")) {
|
||||||
descriptor->textSpacing = AttrAsUint32(input, "textSpacing");
|
descriptor->textSpacing = AttrAsUint32(input, "textSpacing");
|
||||||
}
|
}
|
||||||
|
if (HasAttr(input, "textWrap")) {
|
||||||
|
descriptor->textWrap = AttrAsEnum<VipsTextWrap>(input, "textWrap", VIPS_TYPE_TEXT_WRAP);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Join images together
|
||||||
|
if (HasAttr(input, "joinAnimated")) {
|
||||||
|
descriptor->joinAnimated = AttrAsBool(input, "joinAnimated");
|
||||||
|
}
|
||||||
|
if (HasAttr(input, "joinAcross")) {
|
||||||
|
descriptor->joinAcross = AttrAsUint32(input, "joinAcross");
|
||||||
|
}
|
||||||
|
if (HasAttr(input, "joinShim")) {
|
||||||
|
descriptor->joinShim = AttrAsUint32(input, "joinShim");
|
||||||
|
}
|
||||||
|
if (HasAttr(input, "joinBackground")) {
|
||||||
|
descriptor->joinBackground = AttrAsVectorOfDouble(input, "joinBackground");
|
||||||
|
}
|
||||||
|
if (HasAttr(input, "joinHalign")) {
|
||||||
|
descriptor->joinHalign = AttrAsEnum<VipsAlign>(input, "joinHalign", VIPS_TYPE_ALIGN);
|
||||||
|
}
|
||||||
|
if (HasAttr(input, "joinValign")) {
|
||||||
|
descriptor->joinValign = AttrAsEnum<VipsAlign>(input, "joinValign", VIPS_TYPE_ALIGN);
|
||||||
}
|
}
|
||||||
// Limit input images to a given number of pixels, where pixels = width * height
|
// Limit input images to a given number of pixels, where pixels = width * height
|
||||||
descriptor->limitInputPixels = static_cast<uint64_t>(AttrAsInt64(input, "limitInputPixels"));
|
descriptor->limitInputPixels = static_cast<uint64_t>(AttrAsInt64(input, "limitInputPixels"));
|
||||||
// Allow switch from random to sequential access
|
if (HasAttr(input, "access")) {
|
||||||
descriptor->access = AttrAsBool(input, "sequentialRead") ? VIPS_ACCESS_SEQUENTIAL : VIPS_ACCESS_RANDOM;
|
descriptor->access = AttrAsBool(input, "sequentialRead") ? VIPS_ACCESS_SEQUENTIAL : VIPS_ACCESS_RANDOM;
|
||||||
|
}
|
||||||
// Remove safety features and allow unlimited input
|
// Remove safety features and allow unlimited input
|
||||||
descriptor->unlimited = AttrAsBool(input, "unlimited");
|
descriptor->unlimited = AttrAsBool(input, "unlimited");
|
||||||
|
// Use the EXIF orientation to auto orient the image
|
||||||
|
descriptor->autoOrient = AttrAsBool(input, "autoOrient");
|
||||||
return descriptor;
|
return descriptor;
|
||||||
}
|
}
|
||||||
|
|
||||||
// How many tasks are in the queue?
|
// How many tasks are in the queue?
|
||||||
volatile int counterQueue = 0;
|
std::atomic<int> counterQueue{0};
|
||||||
|
|
||||||
// How many tasks are being processed?
|
// How many tasks are being processed?
|
||||||
volatile int counterProcess = 0;
|
std::atomic<int> counterProcess{0};
|
||||||
|
|
||||||
// Filename extension checkers
|
// Filename extension checkers
|
||||||
static bool EndsWith(std::string const &str, std::string const &end) {
|
static bool EndsWith(std::string const &str, std::string const &end) {
|
||||||
@@ -207,6 +242,9 @@ namespace sharp {
|
|||||||
bool IsAvif(std::string const &str) {
|
bool IsAvif(std::string const &str) {
|
||||||
return EndsWith(str, ".avif") || EndsWith(str, ".AVIF");
|
return EndsWith(str, ".avif") || EndsWith(str, ".AVIF");
|
||||||
}
|
}
|
||||||
|
bool IsJxl(std::string const &str) {
|
||||||
|
return EndsWith(str, ".jxl") || EndsWith(str, ".JXL");
|
||||||
|
}
|
||||||
bool IsDz(std::string const &str) {
|
bool IsDz(std::string const &str) {
|
||||||
return EndsWith(str, ".dzi") || EndsWith(str, ".DZI");
|
return EndsWith(str, ".dzi") || EndsWith(str, ".DZI");
|
||||||
}
|
}
|
||||||
@@ -217,6 +255,13 @@ namespace sharp {
|
|||||||
return EndsWith(str, ".v") || EndsWith(str, ".V") || EndsWith(str, ".vips") || EndsWith(str, ".VIPS");
|
return EndsWith(str, ".v") || EndsWith(str, ".V") || EndsWith(str, ".vips") || EndsWith(str, ".VIPS");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
Trim space from end of string.
|
||||||
|
*/
|
||||||
|
std::string TrimEnd(std::string const &str) {
|
||||||
|
return str.substr(0, str.find_last_not_of(" \n\r\f") + 1);
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Provide a string identifier for the given image type.
|
Provide a string identifier for the given image type.
|
||||||
*/
|
*/
|
||||||
@@ -237,6 +282,9 @@ namespace sharp {
|
|||||||
case ImageType::PPM: id = "ppm"; break;
|
case ImageType::PPM: id = "ppm"; break;
|
||||||
case ImageType::FITS: id = "fits"; break;
|
case ImageType::FITS: id = "fits"; break;
|
||||||
case ImageType::EXR: id = "exr"; break;
|
case ImageType::EXR: id = "exr"; break;
|
||||||
|
case ImageType::JXL: id = "jxl"; break;
|
||||||
|
case ImageType::RAD: id = "rad"; break;
|
||||||
|
case ImageType::DCRAW: id = "dcraw"; break;
|
||||||
case ImageType::VIPS: id = "vips"; break;
|
case ImageType::VIPS: id = "vips"; break;
|
||||||
case ImageType::RAW: id = "raw"; break;
|
case ImageType::RAW: id = "raw"; break;
|
||||||
case ImageType::UNKNOWN: id = "unknown"; break;
|
case ImageType::UNKNOWN: id = "unknown"; break;
|
||||||
@@ -281,6 +329,12 @@ namespace sharp {
|
|||||||
{ "VipsForeignLoadPpmFile", ImageType::PPM },
|
{ "VipsForeignLoadPpmFile", ImageType::PPM },
|
||||||
{ "VipsForeignLoadFitsFile", ImageType::FITS },
|
{ "VipsForeignLoadFitsFile", ImageType::FITS },
|
||||||
{ "VipsForeignLoadOpenexr", ImageType::EXR },
|
{ "VipsForeignLoadOpenexr", ImageType::EXR },
|
||||||
|
{ "VipsForeignLoadJxlFile", ImageType::JXL },
|
||||||
|
{ "VipsForeignLoadJxlBuffer", ImageType::JXL },
|
||||||
|
{ "VipsForeignLoadRadFile", ImageType::RAD },
|
||||||
|
{ "VipsForeignLoadRadBuffer", ImageType::RAD },
|
||||||
|
{ "VipsForeignLoadDcRawFile", ImageType::DCRAW },
|
||||||
|
{ "VipsForeignLoadDcRawBuffer", ImageType::DCRAW },
|
||||||
{ "VipsForeignLoadVips", ImageType::VIPS },
|
{ "VipsForeignLoadVips", ImageType::VIPS },
|
||||||
{ "VipsForeignLoadVipsFile", ImageType::VIPS },
|
{ "VipsForeignLoadVipsFile", ImageType::VIPS },
|
||||||
{ "VipsForeignLoadRaw", ImageType::RAW }
|
{ "VipsForeignLoadRaw", ImageType::RAW }
|
||||||
@@ -345,6 +399,48 @@ namespace sharp {
|
|||||||
imageType == ImageType::HEIF;
|
imageType == ImageType::HEIF;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
Format-specific options builder
|
||||||
|
*/
|
||||||
|
vips::VOption* GetOptionsForImageType(ImageType imageType, InputDescriptor *descriptor) {
|
||||||
|
vips::VOption *option = VImage::option()
|
||||||
|
->set("access", descriptor->access)
|
||||||
|
->set("fail_on", descriptor->failOn);
|
||||||
|
if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {
|
||||||
|
option->set("unlimited", true);
|
||||||
|
}
|
||||||
|
if (ImageTypeSupportsPage(imageType)) {
|
||||||
|
option->set("n", descriptor->pages);
|
||||||
|
option->set("page", descriptor->page);
|
||||||
|
}
|
||||||
|
switch (imageType) {
|
||||||
|
case ImageType::SVG:
|
||||||
|
option->set("dpi", descriptor->density)
|
||||||
|
->set("stylesheet", descriptor->svgStylesheet.data())
|
||||||
|
->set("high_bitdepth", descriptor->svgHighBitdepth);
|
||||||
|
break;
|
||||||
|
case ImageType::TIFF:
|
||||||
|
option->set("tiffSubifd", descriptor->tiffSubifd);
|
||||||
|
break;
|
||||||
|
case ImageType::PDF:
|
||||||
|
option->set("dpi", descriptor->density)
|
||||||
|
->set("background", descriptor->pdfBackground);
|
||||||
|
break;
|
||||||
|
case ImageType::OPENSLIDE:
|
||||||
|
option->set("openSlideLevel", descriptor->openSlideLevel);
|
||||||
|
break;
|
||||||
|
case ImageType::JP2:
|
||||||
|
option->set("oneshot", descriptor->jp2Oneshot);
|
||||||
|
break;
|
||||||
|
case ImageType::MAGICK:
|
||||||
|
option->set("density", std::to_string(descriptor->density).data());
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return option;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data)
|
Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data)
|
||||||
*/
|
*/
|
||||||
@@ -354,12 +450,17 @@ namespace sharp {
|
|||||||
if (descriptor->isBuffer) {
|
if (descriptor->isBuffer) {
|
||||||
if (descriptor->rawChannels > 0) {
|
if (descriptor->rawChannels > 0) {
|
||||||
// Raw, uncompressed pixel data
|
// Raw, uncompressed pixel data
|
||||||
|
bool const is8bit = vips_band_format_is8bit(descriptor->rawDepth);
|
||||||
image = VImage::new_from_memory(descriptor->buffer, descriptor->bufferLength,
|
image = VImage::new_from_memory(descriptor->buffer, descriptor->bufferLength,
|
||||||
descriptor->rawWidth, descriptor->rawHeight, descriptor->rawChannels, descriptor->rawDepth);
|
descriptor->rawWidth, descriptor->rawHeight, descriptor->rawChannels, descriptor->rawDepth);
|
||||||
if (descriptor->rawChannels < 3) {
|
if (descriptor->rawChannels < 3) {
|
||||||
image.get_image()->Type = VIPS_INTERPRETATION_B_W;
|
image.get_image()->Type = is8bit ? VIPS_INTERPRETATION_B_W : VIPS_INTERPRETATION_GREY16;
|
||||||
} else {
|
} else {
|
||||||
image.get_image()->Type = VIPS_INTERPRETATION_sRGB;
|
image.get_image()->Type = is8bit ? VIPS_INTERPRETATION_sRGB : VIPS_INTERPRETATION_RGB16;
|
||||||
|
}
|
||||||
|
if (descriptor->rawPageHeight > 0) {
|
||||||
|
image.set(VIPS_META_PAGE_HEIGHT, descriptor->rawPageHeight);
|
||||||
|
image.set(VIPS_META_N_PAGES, static_cast<int>(descriptor->rawHeight / descriptor->rawPageHeight));
|
||||||
}
|
}
|
||||||
if (descriptor->rawPremultiplied) {
|
if (descriptor->rawPremultiplied) {
|
||||||
image = image.unpremultiply();
|
image = image.unpremultiply();
|
||||||
@@ -370,28 +471,7 @@ namespace sharp {
|
|||||||
imageType = DetermineImageType(descriptor->buffer, descriptor->bufferLength);
|
imageType = DetermineImageType(descriptor->buffer, descriptor->bufferLength);
|
||||||
if (imageType != ImageType::UNKNOWN) {
|
if (imageType != ImageType::UNKNOWN) {
|
||||||
try {
|
try {
|
||||||
vips::VOption *option = VImage::option()
|
vips::VOption *option = GetOptionsForImageType(imageType, descriptor);
|
||||||
->set("access", descriptor->access)
|
|
||||||
->set("fail_on", descriptor->failOn);
|
|
||||||
if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {
|
|
||||||
option->set("unlimited", TRUE);
|
|
||||||
}
|
|
||||||
if (imageType == ImageType::SVG || imageType == ImageType::PDF) {
|
|
||||||
option->set("dpi", descriptor->density);
|
|
||||||
}
|
|
||||||
if (imageType == ImageType::MAGICK) {
|
|
||||||
option->set("density", std::to_string(descriptor->density).data());
|
|
||||||
}
|
|
||||||
if (ImageTypeSupportsPage(imageType)) {
|
|
||||||
option->set("n", descriptor->pages);
|
|
||||||
option->set("page", descriptor->page);
|
|
||||||
}
|
|
||||||
if (imageType == ImageType::OPENSLIDE) {
|
|
||||||
option->set("level", descriptor->level);
|
|
||||||
}
|
|
||||||
if (imageType == ImageType::TIFF) {
|
|
||||||
option->set("subifd", descriptor->subifd);
|
|
||||||
}
|
|
||||||
image = VImage::new_from_buffer(descriptor->buffer, descriptor->bufferLength, nullptr, option);
|
image = VImage::new_from_buffer(descriptor->buffer, descriptor->bufferLength, nullptr, option);
|
||||||
if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) {
|
if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) {
|
||||||
image = SetDensity(image, descriptor->density);
|
image = SetDensity(image, descriptor->density);
|
||||||
@@ -431,6 +511,10 @@ namespace sharp {
|
|||||||
channels < 3 ? VIPS_INTERPRETATION_B_W : VIPS_INTERPRETATION_sRGB))
|
channels < 3 ? VIPS_INTERPRETATION_B_W : VIPS_INTERPRETATION_sRGB))
|
||||||
.new_from_image(background);
|
.new_from_image(background);
|
||||||
}
|
}
|
||||||
|
if (descriptor->createPageHeight > 0) {
|
||||||
|
image.set(VIPS_META_PAGE_HEIGHT, descriptor->createPageHeight);
|
||||||
|
image.set(VIPS_META_N_PAGES, static_cast<int>(descriptor->createHeight / descriptor->createPageHeight));
|
||||||
|
}
|
||||||
image = image.cast(VIPS_FORMAT_UCHAR);
|
image = image.cast(VIPS_FORMAT_UCHAR);
|
||||||
imageType = ImageType::RAW;
|
imageType = ImageType::RAW;
|
||||||
} else if (descriptor->textValue.length() > 0) {
|
} else if (descriptor->textValue.length() > 0) {
|
||||||
@@ -440,6 +524,7 @@ namespace sharp {
|
|||||||
->set("justify", descriptor->textJustify)
|
->set("justify", descriptor->textJustify)
|
||||||
->set("rgba", descriptor->textRgba)
|
->set("rgba", descriptor->textRgba)
|
||||||
->set("spacing", descriptor->textSpacing)
|
->set("spacing", descriptor->textSpacing)
|
||||||
|
->set("wrap", descriptor->textWrap)
|
||||||
->set("autofit_dpi", &descriptor->textAutofitDpi);
|
->set("autofit_dpi", &descriptor->textAutofitDpi);
|
||||||
if (descriptor->textWidth > 0) {
|
if (descriptor->textWidth > 0) {
|
||||||
textOptions->set("width", descriptor->textWidth);
|
textOptions->set("width", descriptor->textWidth);
|
||||||
@@ -473,28 +558,7 @@ namespace sharp {
|
|||||||
}
|
}
|
||||||
if (imageType != ImageType::UNKNOWN) {
|
if (imageType != ImageType::UNKNOWN) {
|
||||||
try {
|
try {
|
||||||
vips::VOption *option = VImage::option()
|
vips::VOption *option = GetOptionsForImageType(imageType, descriptor);
|
||||||
->set("access", descriptor->access)
|
|
||||||
->set("fail_on", descriptor->failOn);
|
|
||||||
if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {
|
|
||||||
option->set("unlimited", TRUE);
|
|
||||||
}
|
|
||||||
if (imageType == ImageType::SVG || imageType == ImageType::PDF) {
|
|
||||||
option->set("dpi", descriptor->density);
|
|
||||||
}
|
|
||||||
if (imageType == ImageType::MAGICK) {
|
|
||||||
option->set("density", std::to_string(descriptor->density).data());
|
|
||||||
}
|
|
||||||
if (ImageTypeSupportsPage(imageType)) {
|
|
||||||
option->set("n", descriptor->pages);
|
|
||||||
option->set("page", descriptor->page);
|
|
||||||
}
|
|
||||||
if (imageType == ImageType::OPENSLIDE) {
|
|
||||||
option->set("level", descriptor->level);
|
|
||||||
}
|
|
||||||
if (imageType == ImageType::TIFF) {
|
|
||||||
option->set("subifd", descriptor->subifd);
|
|
||||||
}
|
|
||||||
image = VImage::new_from_file(descriptor->file.data(), option);
|
image = VImage::new_from_file(descriptor->file.data(), option);
|
||||||
if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) {
|
if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) {
|
||||||
image = SetDensity(image, descriptor->density);
|
image = SetDensity(image, descriptor->density);
|
||||||
@@ -507,9 +571,10 @@ namespace sharp {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Limit input images to a given number of pixels, where pixels = width * height
|
// Limit input images to a given number of pixels, where pixels = width * height
|
||||||
if (descriptor->limitInputPixels > 0 &&
|
if (descriptor->limitInputPixels > 0 &&
|
||||||
static_cast<uint64_t>(image.width() * image.height()) > descriptor->limitInputPixels) {
|
static_cast<uint64_t>(image.width()) * image.height() > descriptor->limitInputPixels) {
|
||||||
throw vips::VError("Input image exceeds pixel limit");
|
throw vips::VError("Input image exceeds pixel limit");
|
||||||
}
|
}
|
||||||
return std::make_tuple(image, imageType);
|
return std::make_tuple(image, imageType);
|
||||||
@@ -519,15 +584,54 @@ namespace sharp {
|
|||||||
Does this image have an embedded profile?
|
Does this image have an embedded profile?
|
||||||
*/
|
*/
|
||||||
bool HasProfile(VImage image) {
|
bool HasProfile(VImage image) {
|
||||||
return (image.get_typeof(VIPS_META_ICC_NAME) != 0) ? TRUE : FALSE;
|
return image.get_typeof(VIPS_META_ICC_NAME) == VIPS_TYPE_BLOB;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Does this image have an alpha channel?
|
Get copy of embedded profile.
|
||||||
Uses colour space interpretation with number of channels to guess this.
|
|
||||||
*/
|
*/
|
||||||
bool HasAlpha(VImage image) {
|
std::pair<char*, size_t> GetProfile(VImage image) {
|
||||||
return image.has_alpha();
|
std::pair<char*, size_t> icc(nullptr, 0);
|
||||||
|
if (HasProfile(image)) {
|
||||||
|
size_t length;
|
||||||
|
const void *data = image.get_blob(VIPS_META_ICC_NAME, &length);
|
||||||
|
icc.first = static_cast<char*>(g_malloc(length));
|
||||||
|
icc.second = length;
|
||||||
|
memcpy(icc.first, data, length);
|
||||||
|
}
|
||||||
|
return icc;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
Set embedded profile.
|
||||||
|
*/
|
||||||
|
VImage SetProfile(VImage image, std::pair<char*, size_t> icc) {
|
||||||
|
if (icc.first != nullptr) {
|
||||||
|
image = image.copy();
|
||||||
|
image.set(VIPS_META_ICC_NAME, reinterpret_cast<VipsCallbackFn>(vips_area_free_cb), icc.first, icc.second);
|
||||||
|
}
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void* RemoveExifCallback(VipsImage *image, char const *field, GValue *value, void *data) {
|
||||||
|
std::vector<std::string> *fieldNames = static_cast<std::vector<std::string> *>(data);
|
||||||
|
std::string fieldName(field);
|
||||||
|
if (fieldName.substr(0, 8) == ("exif-ifd")) {
|
||||||
|
fieldNames->push_back(fieldName);
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
Remove all EXIF-related image fields.
|
||||||
|
*/
|
||||||
|
VImage RemoveExif(VImage image) {
|
||||||
|
std::vector<std::string> fieldNames;
|
||||||
|
vips_image_map(image.get_image(), static_cast<VipsImageMapFn>(RemoveExifCallback), &fieldNames);
|
||||||
|
for (const auto& f : fieldNames) {
|
||||||
|
image.remove(f.data());
|
||||||
|
}
|
||||||
|
return image;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -556,6 +660,7 @@ namespace sharp {
|
|||||||
VImage RemoveExifOrientation(VImage image) {
|
VImage RemoveExifOrientation(VImage image) {
|
||||||
VImage copy = image.copy();
|
VImage copy = image.copy();
|
||||||
copy.remove(VIPS_META_ORIENTATION);
|
copy.remove(VIPS_META_ORIENTATION);
|
||||||
|
copy.remove("exif-ifd0-Orientation");
|
||||||
return copy;
|
return copy;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -564,22 +669,21 @@ namespace sharp {
|
|||||||
*/
|
*/
|
||||||
VImage SetAnimationProperties(VImage image, int nPages, int pageHeight, std::vector<int> delay, int loop) {
|
VImage SetAnimationProperties(VImage image, int nPages, int pageHeight, std::vector<int> delay, int loop) {
|
||||||
bool hasDelay = !delay.empty();
|
bool hasDelay = !delay.empty();
|
||||||
|
|
||||||
// Avoid a copy if none of the animation properties are needed.
|
|
||||||
if (nPages == 1 && !hasDelay && loop == -1) return image;
|
|
||||||
|
|
||||||
if (delay.size() == 1) {
|
|
||||||
// We have just one delay, repeat that value for all frames.
|
|
||||||
delay.insert(delay.end(), nPages - 1, delay[0]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Attaching metadata, need to copy the image.
|
|
||||||
VImage copy = image.copy();
|
VImage copy = image.copy();
|
||||||
|
|
||||||
// Only set page-height if we have more than one page, or this could
|
// Only set page-height if we have more than one page, or this could
|
||||||
// accidentally turn into an animated image later.
|
// accidentally turn into an animated image later.
|
||||||
if (nPages > 1) copy.set(VIPS_META_PAGE_HEIGHT, pageHeight);
|
if (nPages > 1) copy.set(VIPS_META_PAGE_HEIGHT, pageHeight);
|
||||||
if (hasDelay) copy.set("delay", delay);
|
if (hasDelay) {
|
||||||
|
if (delay.size() == 1) {
|
||||||
|
// We have just one delay, repeat that value for all frames.
|
||||||
|
delay.insert(delay.end(), nPages - 1, delay[0]);
|
||||||
|
}
|
||||||
|
copy.set("delay", delay);
|
||||||
|
}
|
||||||
|
if (nPages == 1 && !hasDelay && loop == -1) {
|
||||||
|
loop = 1;
|
||||||
|
}
|
||||||
if (loop != -1) copy.set("loop", loop);
|
if (loop != -1) copy.set("loop", loop);
|
||||||
|
|
||||||
return copy;
|
return copy;
|
||||||
@@ -596,6 +700,15 @@ namespace sharp {
|
|||||||
return copy;
|
return copy;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
Remove GIF palette from image.
|
||||||
|
*/
|
||||||
|
VImage RemoveGifPalette(VImage image) {
|
||||||
|
VImage copy = image.copy();
|
||||||
|
copy.remove("gif-palette");
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Does this image have a non-default density?
|
Does this image have a non-default density?
|
||||||
*/
|
*/
|
||||||
@@ -648,6 +761,10 @@ namespace sharp {
|
|||||||
if (image.width() > 65535 || height > 65535) {
|
if (image.width() > 65535 || height > 65535) {
|
||||||
throw vips::VError("Processed image is too large for the GIF format");
|
throw vips::VError("Processed image is too large for the GIF format");
|
||||||
}
|
}
|
||||||
|
} else if (imageType == ImageType::HEIF) {
|
||||||
|
if (image.width() > 16384 || height > 16384) {
|
||||||
|
throw vips::VError("Processed image is too large for the HEIF format");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -695,7 +812,7 @@ namespace sharp {
|
|||||||
int *timeout = VIPS_NEW(im, int);
|
int *timeout = VIPS_NEW(im, int);
|
||||||
*timeout = seconds;
|
*timeout = seconds;
|
||||||
g_signal_connect(im, "eval", G_CALLBACK(VipsProgressCallBack), timeout);
|
g_signal_connect(im, "eval", G_CALLBACK(VipsProgressCallBack), timeout);
|
||||||
vips_image_set_progress(im, TRUE);
|
vips_image_set_progress(im, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -705,7 +822,7 @@ namespace sharp {
|
|||||||
*/
|
*/
|
||||||
void VipsProgressCallBack(VipsImage *im, VipsProgress *progress, int *timeout) {
|
void VipsProgressCallBack(VipsImage *im, VipsProgress *progress, int *timeout) {
|
||||||
if (*timeout > 0 && progress->run >= *timeout) {
|
if (*timeout > 0 && progress->run >= *timeout) {
|
||||||
vips_image_set_kill(im, TRUE);
|
vips_image_set_kill(im, true);
|
||||||
vips_error("timeout", "%d%% complete", progress->percent);
|
vips_error("timeout", "%d%% complete", progress->percent);
|
||||||
*timeout = 0;
|
*timeout = 0;
|
||||||
}
|
}
|
||||||
@@ -852,14 +969,6 @@ namespace sharp {
|
|||||||
return interpretation == VIPS_INTERPRETATION_RGB16 || interpretation == VIPS_INTERPRETATION_GREY16;
|
return interpretation == VIPS_INTERPRETATION_RGB16 || interpretation == VIPS_INTERPRETATION_GREY16;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
Return the image alpha maximum. Useful for combining alpha bands. scRGB
|
|
||||||
images are 0 - 1 for image data, but the alpha is 0 - 255.
|
|
||||||
*/
|
|
||||||
double MaximumImageAlpha(VipsInterpretation const interpretation) {
|
|
||||||
return Is16Bit(interpretation) ? 65535.0 : 255.0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Convert RGBA value to another colourspace
|
Convert RGBA value to another colourspace
|
||||||
*/
|
*/
|
||||||
@@ -902,25 +1011,25 @@ namespace sharp {
|
|||||||
0.0722 * colour[2])
|
0.0722 * colour[2])
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
// Add alpha channel to alphaColour colour
|
// Add alpha channel(s) to alphaColour colour
|
||||||
if (colour[3] < 255.0 || HasAlpha(image)) {
|
if (colour[3] < 255.0 || image.has_alpha()) {
|
||||||
alphaColour.push_back(colour[3] * multiplier);
|
int extraBands = image.bands() > 4 ? image.bands() - 3 : 1;
|
||||||
|
alphaColour.insert(alphaColour.end(), extraBands, colour[3] * multiplier);
|
||||||
}
|
}
|
||||||
// Ensure alphaColour colour uses correct colourspace
|
// Ensure alphaColour colour uses correct colourspace
|
||||||
alphaColour = sharp::GetRgbaAsColourspace(alphaColour, image.interpretation(), premultiply);
|
alphaColour = sharp::GetRgbaAsColourspace(alphaColour, image.interpretation(), premultiply);
|
||||||
// Add non-transparent alpha channel, if required
|
// Add non-transparent alpha channel, if required
|
||||||
if (colour[3] < 255.0 && !HasAlpha(image)) {
|
if (colour[3] < 255.0 && !image.has_alpha()) {
|
||||||
image = image.bandjoin(
|
image = image.bandjoin_const({ 255 * multiplier });
|
||||||
VImage::new_matrix(image.width(), image.height()).new_from_image(255 * multiplier));
|
|
||||||
}
|
}
|
||||||
return std::make_tuple(image, alphaColour);
|
return std::make_tuple(image, alphaColour);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Removes alpha channel, if any.
|
Removes alpha channels, if any.
|
||||||
*/
|
*/
|
||||||
VImage RemoveAlpha(VImage image) {
|
VImage RemoveAlpha(VImage image) {
|
||||||
if (HasAlpha(image)) {
|
while (image.bands() > 1 && image.has_alpha()) {
|
||||||
image = image.extract_band(0, VImage::option()->set("n", image.bands() - 1));
|
image = image.extract_band(0, VImage::option()->set("n", image.bands() - 1));
|
||||||
}
|
}
|
||||||
return image;
|
return image;
|
||||||
@@ -930,21 +1039,14 @@ namespace sharp {
|
|||||||
Ensures alpha channel, if missing.
|
Ensures alpha channel, if missing.
|
||||||
*/
|
*/
|
||||||
VImage EnsureAlpha(VImage image, double const value) {
|
VImage EnsureAlpha(VImage image, double const value) {
|
||||||
if (!HasAlpha(image)) {
|
if (!image.has_alpha()) {
|
||||||
std::vector<double> alpha;
|
image = image.bandjoin_const({ value * vips_interpretation_max_alpha(image.interpretation()) });
|
||||||
alpha.push_back(value * sharp::MaximumImageAlpha(image.interpretation()));
|
|
||||||
image = image.bandjoin_const(alpha);
|
|
||||||
}
|
}
|
||||||
return image;
|
return image;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::pair<double, double> ResolveShrink(int width, int height, int targetWidth, int targetHeight,
|
std::pair<double, double> ResolveShrink(int width, int height, int targetWidth, int targetHeight,
|
||||||
Canvas canvas, bool swap, bool withoutEnlargement, bool withoutReduction) {
|
Canvas canvas, bool withoutEnlargement, bool withoutReduction) {
|
||||||
if (swap && canvas != Canvas::IGNORE_ASPECT) {
|
|
||||||
// Swap input width and height when requested.
|
|
||||||
std::swap(width, height);
|
|
||||||
}
|
|
||||||
|
|
||||||
double hshrink = 1.0;
|
double hshrink = 1.0;
|
||||||
double vshrink = 1.0;
|
double vshrink = 1.0;
|
||||||
|
|
||||||
@@ -1010,4 +1112,14 @@ namespace sharp {
|
|||||||
return std::make_pair(hshrink, vshrink);
|
return std::make_pair(hshrink, vshrink);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
Ensure decoding remains sequential.
|
||||||
|
*/
|
||||||
|
VImage StaySequential(VImage image, bool condition) {
|
||||||
|
if (vips_image_is_sequential(image.get_image()) && condition) {
|
||||||
|
image = image.copy_memory().copy();
|
||||||
|
image.remove(VIPS_META_SEQUENTIAL);
|
||||||
|
}
|
||||||
|
return image;
|
||||||
|
}
|
||||||
} // namespace sharp
|
} // namespace sharp
|
||||||
|
|||||||
143
src/common.h
@@ -1,16 +1,5 @@
|
|||||||
// Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Lovell Fuller and contributors.
|
// Copyright 2013 Lovell Fuller and others.
|
||||||
//
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
// 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
|
|
||||||
//
|
|
||||||
// http://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.
|
|
||||||
|
|
||||||
#ifndef SRC_COMMON_H_
|
#ifndef SRC_COMMON_H_
|
||||||
#define SRC_COMMON_H_
|
#define SRC_COMMON_H_
|
||||||
@@ -18,6 +7,7 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
#include <tuple>
|
#include <tuple>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
#include <atomic>
|
||||||
|
|
||||||
#include <napi.h>
|
#include <napi.h>
|
||||||
#include <vips/vips8>
|
#include <vips/vips8>
|
||||||
@@ -25,18 +15,14 @@
|
|||||||
// Verify platform and compiler compatibility
|
// Verify platform and compiler compatibility
|
||||||
|
|
||||||
#if (VIPS_MAJOR_VERSION < 8) || \
|
#if (VIPS_MAJOR_VERSION < 8) || \
|
||||||
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION < 13) || \
|
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION < 17) || \
|
||||||
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION == 13 && VIPS_MICRO_VERSION < 1)
|
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION == 17 && VIPS_MICRO_VERSION < 1)
|
||||||
#error "libvips version 8.13.1+ is required - please see https://sharp.pixelplumbing.com/install"
|
#error "libvips version 8.17.1+ is required - please see https://sharp.pixelplumbing.com/install"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if ((!defined(__clang__)) && defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 6)))
|
#if defined(__has_include)
|
||||||
#error "GCC version 4.6+ is required for C++11 features - please see https://sharp.pixelplumbing.com/install"
|
#if !__has_include(<filesystem>)
|
||||||
#endif
|
#error "C++17 compiler required - please see https://sharp.pixelplumbing.com/install"
|
||||||
|
|
||||||
#if (defined(__clang__) && defined(__has_feature))
|
|
||||||
#if (!__has_feature(cxx_range_for))
|
|
||||||
#error "clang version 3.0+ is required for C++11 features - please see https://sharp.pixelplumbing.com/install"
|
|
||||||
#endif
|
#endif
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
@@ -47,6 +33,7 @@ namespace sharp {
|
|||||||
struct InputDescriptor { // NOLINT(runtime/indentation_namespace)
|
struct InputDescriptor { // NOLINT(runtime/indentation_namespace)
|
||||||
std::string name;
|
std::string name;
|
||||||
std::string file;
|
std::string file;
|
||||||
|
bool autoOrient;
|
||||||
char *buffer;
|
char *buffer;
|
||||||
VipsFailOn failOn;
|
VipsFailOn failOn;
|
||||||
uint64_t limitInputPixels;
|
uint64_t limitInputPixels;
|
||||||
@@ -55,18 +42,19 @@ namespace sharp {
|
|||||||
size_t bufferLength;
|
size_t bufferLength;
|
||||||
bool isBuffer;
|
bool isBuffer;
|
||||||
double density;
|
double density;
|
||||||
|
bool ignoreIcc;
|
||||||
VipsBandFormat rawDepth;
|
VipsBandFormat rawDepth;
|
||||||
int rawChannels;
|
int rawChannels;
|
||||||
int rawWidth;
|
int rawWidth;
|
||||||
int rawHeight;
|
int rawHeight;
|
||||||
bool rawPremultiplied;
|
bool rawPremultiplied;
|
||||||
|
int rawPageHeight;
|
||||||
int pages;
|
int pages;
|
||||||
int page;
|
int page;
|
||||||
int level;
|
|
||||||
int subifd;
|
|
||||||
int createChannels;
|
int createChannels;
|
||||||
int createWidth;
|
int createWidth;
|
||||||
int createHeight;
|
int createHeight;
|
||||||
|
int createPageHeight;
|
||||||
std::vector<double> createBackground;
|
std::vector<double> createBackground;
|
||||||
std::string createNoiseType;
|
std::string createNoiseType;
|
||||||
double createNoiseMean;
|
double createNoiseMean;
|
||||||
@@ -81,40 +69,67 @@ namespace sharp {
|
|||||||
int textDpi;
|
int textDpi;
|
||||||
bool textRgba;
|
bool textRgba;
|
||||||
int textSpacing;
|
int textSpacing;
|
||||||
|
VipsTextWrap textWrap;
|
||||||
int textAutofitDpi;
|
int textAutofitDpi;
|
||||||
|
bool joinAnimated;
|
||||||
|
int joinAcross;
|
||||||
|
int joinShim;
|
||||||
|
std::vector<double> joinBackground;
|
||||||
|
VipsAlign joinHalign;
|
||||||
|
VipsAlign joinValign;
|
||||||
|
std::string svgStylesheet;
|
||||||
|
bool svgHighBitdepth;
|
||||||
|
int tiffSubifd;
|
||||||
|
int openSlideLevel;
|
||||||
|
std::vector<double> pdfBackground;
|
||||||
|
bool jp2Oneshot;
|
||||||
|
|
||||||
InputDescriptor():
|
InputDescriptor():
|
||||||
|
autoOrient(false),
|
||||||
buffer(nullptr),
|
buffer(nullptr),
|
||||||
failOn(VIPS_FAIL_ON_WARNING),
|
failOn(VIPS_FAIL_ON_WARNING),
|
||||||
limitInputPixels(0x3FFF * 0x3FFF),
|
limitInputPixels(0x3FFF * 0x3FFF),
|
||||||
unlimited(FALSE),
|
unlimited(false),
|
||||||
access(VIPS_ACCESS_RANDOM),
|
access(VIPS_ACCESS_SEQUENTIAL),
|
||||||
bufferLength(0),
|
bufferLength(0),
|
||||||
isBuffer(FALSE),
|
isBuffer(false),
|
||||||
density(72.0),
|
density(72.0),
|
||||||
|
ignoreIcc(false),
|
||||||
rawDepth(VIPS_FORMAT_UCHAR),
|
rawDepth(VIPS_FORMAT_UCHAR),
|
||||||
rawChannels(0),
|
rawChannels(0),
|
||||||
rawWidth(0),
|
rawWidth(0),
|
||||||
rawHeight(0),
|
rawHeight(0),
|
||||||
rawPremultiplied(false),
|
rawPremultiplied(false),
|
||||||
|
rawPageHeight(0),
|
||||||
pages(1),
|
pages(1),
|
||||||
page(0),
|
page(0),
|
||||||
level(0),
|
|
||||||
subifd(-1),
|
|
||||||
createChannels(0),
|
createChannels(0),
|
||||||
createWidth(0),
|
createWidth(0),
|
||||||
createHeight(0),
|
createHeight(0),
|
||||||
|
createPageHeight(0),
|
||||||
createBackground{ 0.0, 0.0, 0.0, 255.0 },
|
createBackground{ 0.0, 0.0, 0.0, 255.0 },
|
||||||
createNoiseMean(0.0),
|
createNoiseMean(0.0),
|
||||||
createNoiseSigma(0.0),
|
createNoiseSigma(0.0),
|
||||||
textWidth(0),
|
textWidth(0),
|
||||||
textHeight(0),
|
textHeight(0),
|
||||||
textAlign(VIPS_ALIGN_LOW),
|
textAlign(VIPS_ALIGN_LOW),
|
||||||
textJustify(FALSE),
|
textJustify(false),
|
||||||
textDpi(72),
|
textDpi(72),
|
||||||
textRgba(FALSE),
|
textRgba(false),
|
||||||
textSpacing(0),
|
textSpacing(0),
|
||||||
textAutofitDpi(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
|
// Convenience methods to access the attributes of a Napi::Object
|
||||||
@@ -152,6 +167,9 @@ namespace sharp {
|
|||||||
PPM,
|
PPM,
|
||||||
FITS,
|
FITS,
|
||||||
EXR,
|
EXR,
|
||||||
|
JXL,
|
||||||
|
RAD,
|
||||||
|
DCRAW,
|
||||||
VIPS,
|
VIPS,
|
||||||
RAW,
|
RAW,
|
||||||
UNKNOWN,
|
UNKNOWN,
|
||||||
@@ -167,10 +185,10 @@ namespace sharp {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// How many tasks are in the queue?
|
// How many tasks are in the queue?
|
||||||
extern volatile int counterQueue;
|
extern std::atomic<int> counterQueue;
|
||||||
|
|
||||||
// How many tasks are being processed?
|
// How many tasks are being processed?
|
||||||
extern volatile int counterProcess;
|
extern std::atomic<int> counterProcess;
|
||||||
|
|
||||||
// Filename extension checkers
|
// Filename extension checkers
|
||||||
bool IsJpeg(std::string const &str);
|
bool IsJpeg(std::string const &str);
|
||||||
@@ -182,10 +200,16 @@ namespace sharp {
|
|||||||
bool IsHeic(std::string const &str);
|
bool IsHeic(std::string const &str);
|
||||||
bool IsHeif(std::string const &str);
|
bool IsHeif(std::string const &str);
|
||||||
bool IsAvif(std::string const &str);
|
bool IsAvif(std::string const &str);
|
||||||
|
bool IsJxl(std::string const &str);
|
||||||
bool IsDz(std::string const &str);
|
bool IsDz(std::string const &str);
|
||||||
bool IsDzZip(std::string const &str);
|
bool IsDzZip(std::string const &str);
|
||||||
bool IsV(std::string const &str);
|
bool IsV(std::string const &str);
|
||||||
|
|
||||||
|
/*
|
||||||
|
Trim space from end of string.
|
||||||
|
*/
|
||||||
|
std::string TrimEnd(std::string const &str);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Provide a string identifier for the given image type.
|
Provide a string identifier for the given image type.
|
||||||
*/
|
*/
|
||||||
@@ -202,14 +226,9 @@ namespace sharp {
|
|||||||
ImageType DetermineImageType(char const *file);
|
ImageType DetermineImageType(char const *file);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Does this image type support multiple pages?
|
Format-specific options builder
|
||||||
*/
|
*/
|
||||||
bool ImageTypeSupportsPage(ImageType imageType);
|
vips::VOption* GetOptionsForImageType(ImageType imageType, InputDescriptor *descriptor);
|
||||||
|
|
||||||
/*
|
|
||||||
Does this image type support removal of safety limits?
|
|
||||||
*/
|
|
||||||
bool ImageTypeSupportsUnlimited(ImageType imageType);
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data)
|
Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data)
|
||||||
@@ -222,10 +241,19 @@ namespace sharp {
|
|||||||
bool HasProfile(VImage image);
|
bool HasProfile(VImage image);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Does this image have an alpha channel?
|
Get copy of embedded profile.
|
||||||
Uses colour space interpretation with number of channels to guess this.
|
|
||||||
*/
|
*/
|
||||||
bool HasAlpha(VImage image);
|
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.
|
Get EXIF Orientation of image, if any.
|
||||||
@@ -252,6 +280,11 @@ namespace sharp {
|
|||||||
*/
|
*/
|
||||||
VImage RemoveAnimationProperties(VImage image);
|
VImage RemoveAnimationProperties(VImage image);
|
||||||
|
|
||||||
|
/*
|
||||||
|
Remove GIF palette from image.
|
||||||
|
*/
|
||||||
|
VImage RemoveGifPalette(VImage image);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Does this image have a non-default density?
|
Does this image have a non-default density?
|
||||||
*/
|
*/
|
||||||
@@ -329,12 +362,6 @@ namespace sharp {
|
|||||||
*/
|
*/
|
||||||
bool Is16Bit(VipsInterpretation const interpretation);
|
bool Is16Bit(VipsInterpretation const interpretation);
|
||||||
|
|
||||||
/*
|
|
||||||
Return the image alpha maximum. Useful for combining alpha bands. scRGB
|
|
||||||
images are 0 - 1 for image data, but the alpha is 0 - 255.
|
|
||||||
*/
|
|
||||||
double MaximumImageAlpha(VipsInterpretation const interpretation);
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Convert RGBA value to another colourspace
|
Convert RGBA value to another colourspace
|
||||||
*/
|
*/
|
||||||
@@ -347,7 +374,7 @@ namespace sharp {
|
|||||||
std::tuple<VImage, std::vector<double>> ApplyAlpha(VImage image, std::vector<double> colour, bool premultiply);
|
std::tuple<VImage, std::vector<double>> ApplyAlpha(VImage image, std::vector<double> colour, bool premultiply);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Removes alpha channel, if any.
|
Removes alpha channels, if any.
|
||||||
*/
|
*/
|
||||||
VImage RemoveAlpha(VImage image);
|
VImage RemoveAlpha(VImage image);
|
||||||
|
|
||||||
@@ -357,13 +384,15 @@ namespace sharp {
|
|||||||
VImage EnsureAlpha(VImage image, double const value);
|
VImage EnsureAlpha(VImage image, double const value);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Calculate the shrink factor, taking into account auto-rotate, the canvas
|
Calculate the horizontal and vertical shrink factors, taking the canvas mode into account.
|
||||||
mode, and so on. The hshrink/vshrink are the amount to shrink the input
|
|
||||||
image axes by in order for the output axes (ie. after rotation) to match
|
|
||||||
the required thumbnail width/height and canvas mode.
|
|
||||||
*/
|
*/
|
||||||
std::pair<double, double> ResolveShrink(int width, int height, int targetWidth, int targetHeight,
|
std::pair<double, double> ResolveShrink(int width, int height, int targetWidth, int targetHeight,
|
||||||
Canvas canvas, bool swap, bool withoutEnlargement, bool withoutReduction);
|
Canvas canvas, bool withoutEnlargement, bool withoutReduction);
|
||||||
|
|
||||||
|
/*
|
||||||
|
Ensure decoding remains sequential.
|
||||||
|
*/
|
||||||
|
VImage StaySequential(VImage image, bool condition = true);
|
||||||
|
|
||||||
} // namespace sharp
|
} // namespace sharp
|
||||||
|
|
||||||
|
|||||||