mirror of
https://github.com/lovell/sharp.git
synced 2026-02-04 05:36:18 +01:00
Compare commits
832 Commits
v0.26.0-be
...
v0.33.3-rc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
f7b29d7b59 | ||
|
|
0b806187fc | ||
|
|
c1393daa70 | ||
|
|
31c1cfb049 | ||
|
|
afc35c2208 | ||
|
|
6eb2add3bf | ||
|
|
5cdb2b83d5 | ||
|
|
1eb66c0944 | ||
|
|
55c4d8807c | ||
|
|
9a54a034e1 | ||
|
|
f5109560d6 | ||
|
|
953a94885b | ||
|
|
0e3bd46ca3 | ||
|
|
4b38f56d02 | ||
|
|
0fe857c5ac | ||
|
|
1bf06bd5b4 | ||
|
|
6e3f4c3c92 | ||
|
|
8583eb1235 | ||
|
|
c3a852eecf | ||
|
|
3a44748f49 | ||
|
|
e1bc8674fd | ||
|
|
a618ce7a15 | ||
|
|
a44168c8c7 | ||
|
|
74e3f73934 | ||
|
|
b9261c243c | ||
|
|
cc9f91f37c | ||
|
|
212a6e7519 | ||
|
|
e547eaa180 | ||
|
|
9a0d9eed74 | ||
|
|
dd56a9699e | ||
|
|
ea7cf2a2ef | ||
|
|
76c4c51e2a | ||
|
|
b46ab510da | ||
|
|
3e327a586c | ||
|
|
974fab946e | ||
|
|
f998a8f249 | ||
|
|
be331e958e | ||
|
|
254944f8ab | ||
|
|
f1e640d231 | ||
|
|
c295f06a6f | ||
|
|
6288c7bced | ||
|
|
d247c02762 | ||
|
|
1b84ccbbe9 | ||
|
|
e4160c684d | ||
|
|
905518fab0 | ||
|
|
8ff33763ce | ||
|
|
cbf741cac7 | ||
|
|
6c2e2be41d | ||
|
|
e0d3c6e05d | ||
|
|
e3cab7f10f | ||
|
|
204463ffbb | ||
|
|
1bcd3700c5 | ||
|
|
c99a11cff5 | ||
|
|
81c74f57e0 | ||
|
|
7a8ab452c5 | ||
|
|
bb91912883 | ||
|
|
afc4c5bf79 | ||
|
|
e40a881ab4 | ||
|
|
c1b13adac3 | ||
|
|
29e09898f7 | ||
|
|
853a20358e | ||
|
|
8bb30d7801 | ||
|
|
a333b87f5d | ||
|
|
4662527a17 | ||
|
|
b10d8f89ca | ||
|
|
f903e1465e | ||
|
|
a75718565c | ||
|
|
4d82331bf6 | ||
|
|
b91875d3d9 | ||
|
|
a0568ec0c3 | ||
|
|
48e3ea5e29 | ||
|
|
93b29057e4 | ||
|
|
db654de385 | ||
|
|
a6aeef612b | ||
|
|
7bf6cbd669 | ||
|
|
04c31b35a7 | ||
|
|
ee9cdb6598 | ||
|
|
8960eb8309 | ||
|
|
54d9dc46f5 | ||
|
|
51b4a7c564 | ||
|
|
5b03579e5c | ||
|
|
58c2af3251 | ||
|
|
ee948ac6fa | ||
|
|
66a3ce5e55 | ||
|
|
75e5afcd42 | ||
|
|
d396a4e65d | ||
|
|
ae1dbcdf4e | ||
|
|
4c29368b51 | ||
|
|
36e55969d2 | ||
|
|
985e881e7a | ||
|
|
0b116715aa | ||
|
|
9deac83322 | ||
|
|
5d36f5f699 | ||
|
|
926572b41e | ||
|
|
d0c8e95641 | ||
|
|
b0ca23c3e7 | ||
|
|
c3a0d5f5d0 | ||
|
|
1d36936954 | ||
|
|
b609df4b48 | ||
|
|
c567d3b9ab | ||
|
|
27d9fe2a4e | ||
|
|
ac883c5215 | ||
|
|
e8720c9374 | ||
|
|
42e45d842a | ||
|
|
72fd8abe2c | ||
|
|
ac18bbbc7c | ||
|
|
fcbe4e1e01 | ||
|
|
9280742385 | ||
|
|
7a1a1cf9e8 | ||
|
|
ea599ade10 | ||
|
|
1de49f3ed8 | ||
|
|
4ac65054bc | ||
|
|
23033e2050 | ||
|
|
dd3b78272a | ||
|
|
80d169b7c2 | ||
|
|
003279a0b0 | ||
|
|
af80d7e389 | ||
|
|
21a960796c | ||
|
|
fc3b4a683d | ||
|
|
808133e7dc | ||
|
|
801b6fea6c | ||
|
|
c2ecde6a16 | ||
|
|
55efe5602b | ||
|
|
c62002554b | ||
|
|
7f83ecd255 | ||
|
|
dc5f4dcd28 | ||
|
|
735793ba99 | ||
|
|
47792df689 | ||
|
|
5c6cdfaece | ||
|
|
115a6b10f6 | ||
|
|
4feee506cf | ||
|
|
83db5f8a2a | ||
|
|
7eb5efa3a3 | ||
|
|
5a9f89fe06 | ||
|
|
02e0c2dfc9 | ||
|
|
968d9d7008 | ||
|
|
7faacd91b0 | ||
|
|
154eaff4ec | ||
|
|
424660278d | ||
|
|
2b01951306 | ||
|
|
83bb6a4554 | ||
|
|
c72d42816d | ||
|
|
35a81a7af2 | ||
|
|
9dc8db4370 | ||
|
|
47ae1f52db | ||
|
|
ec17d7f580 | ||
|
|
da5453a7c0 | ||
|
|
f7bed69ffb | ||
|
|
7aa340232e | ||
|
|
68823a5edb | ||
|
|
1c3ba303ea | ||
|
|
76f8112952 | ||
|
|
24150eac89 | ||
|
|
51121a1440 | ||
|
|
3b370b6c01 | ||
|
|
884947a069 | ||
|
|
f8340e1a82 | ||
|
|
5101f4e79c | ||
|
|
161d127bf3 | ||
|
|
638d540371 | ||
|
|
d8f1298511 | ||
|
|
d67e09ba7c | ||
|
|
4c3a8a7007 | ||
|
|
92399ee5e2 | ||
|
|
96992845ed | ||
|
|
2b8e4d20de | ||
|
|
dd6583044b | ||
|
|
446e4e3c3a | ||
|
|
3b492ea423 | ||
|
|
3da258f6fb | ||
|
|
9755629cfd | ||
|
|
5bb6702717 | ||
|
|
8c0660d71e | ||
|
|
513fb40f40 | ||
|
|
659cdabd8e | ||
|
|
add4c7928f | ||
|
|
336856dfc2 | ||
|
|
e1ba2a7fd8 | ||
|
|
2b1f5cbe07 | ||
|
|
72025051c5 | ||
|
|
140eeebb3d | ||
|
|
407bfcb42a | ||
|
|
549219f32a | ||
|
|
afab0d34dd | ||
|
|
2deced0fb9 | ||
|
|
2a0077c481 | ||
|
|
f7f3e43490 | ||
|
|
b876abaf88 | ||
|
|
dcd9a3c558 | ||
|
|
a06b8c296a | ||
|
|
602f988aba | ||
|
|
079bd7b9f5 | ||
|
|
1ff84b20b7 | ||
|
|
97655d2dfd | ||
|
|
d10d7b02d4 | ||
|
|
2ffdae2914 | ||
|
|
342de36973 | ||
|
|
b33231d4bd | ||
|
|
319db21f29 | ||
|
|
d359331426 | ||
|
|
7ae151362b | ||
|
|
648a1e05da | ||
|
|
b9f211fe34 | ||
|
|
e475d9e47f | ||
|
|
f37ca8249a | ||
|
|
1dd4be670d | ||
|
|
197d4cf835 | ||
|
|
83eed86b53 | ||
|
|
bbf612cb9e | ||
|
|
2679bb567b | ||
|
|
481e350f39 | ||
|
|
50c7a08754 | ||
|
|
9a0bb60737 | ||
|
|
deb5d81221 | ||
|
|
916b04dbac | ||
|
|
52307fad5d | ||
|
|
afb21135c2 | ||
|
|
b7fbffb3f7 | ||
|
|
5d98bcd8d8 | ||
|
|
e044788f63 | ||
|
|
4a9267ce12 | ||
|
|
104464c2e0 | ||
|
|
60adc110f5 | ||
|
|
2031d7d112 | ||
|
|
3402656ec5 | ||
|
|
4e84f743e4 | ||
|
|
17e50de5f0 | ||
|
|
978a788f40 | ||
|
|
6e91d55971 | ||
|
|
d4ce0a1e36 | ||
|
|
148608b377 | ||
|
|
f725f4acb7 | ||
|
|
d07a549438 | ||
|
|
551441cedd | ||
|
|
46c14e939b | ||
|
|
6084647795 | ||
|
|
e0a598ae62 | ||
|
|
28833eb04a | ||
|
|
b24c9c86d1 | ||
|
|
b7add480c7 | ||
|
|
eabb671b10 | ||
|
|
513ed02b76 | ||
|
|
b7ddbe71f7 | ||
|
|
21d1a7ca62 | ||
|
|
4c2d28a7ad | ||
|
|
2afec9e3ed | ||
|
|
69790421b7 | ||
|
|
3f08f6a359 | ||
|
|
719c2db8da | ||
|
|
a9aa55c32d | ||
|
|
3f6d9d6ee9 | ||
|
|
b32568159f | ||
|
|
bb48d0d857 | ||
|
|
536412515f | ||
|
|
fcc6eaadd3 | ||
|
|
7dc78e8796 | ||
|
|
c65de3fe6d | ||
|
|
d000f57773 | ||
|
|
75cddbdb6d | ||
|
|
e418d91511 | ||
|
|
6c2e6c5432 | ||
|
|
8c6d9fdc62 | ||
|
|
468e95427e | ||
|
|
6d7a5ace6b | ||
|
|
cbaec198a5 | ||
|
|
7467fa8b50 | ||
|
|
61640fb5c7 | ||
|
|
19cb4b62b0 | ||
|
|
81ee8bc30f | ||
|
|
9f384e1c6c | ||
|
|
35e8c8b25e | ||
|
|
dc53f1baff | ||
|
|
70139600b5 | ||
|
|
1b4d1521e0 | ||
|
|
ed3377cb2d | ||
|
|
d72852b3aa | ||
|
|
4b6b6189bf | ||
|
|
b69a54fc75 | ||
|
|
81e388a4cc | ||
|
|
5bd5e5052a | ||
|
|
a2d3fa729f | ||
|
|
cb6811bc47 | ||
|
|
53c6e80869 | ||
|
|
e71dca586c | ||
|
|
b3cd48db5f | ||
|
|
476448b9d4 | ||
|
|
070534df5b | ||
|
|
9a1e8ed574 | ||
|
|
309918a878 | ||
|
|
cac83b94c1 | ||
|
|
9c06df08a1 | ||
|
|
52e4543d31 | ||
|
|
a688468378 | ||
|
|
e1760d64fb | ||
|
|
84d4e3cf8f | ||
|
|
f8a76372ad | ||
|
|
4237f5520f | ||
|
|
8c0c01c702 | ||
|
|
9c100830e0 | ||
|
|
ed5d753b89 | ||
|
|
d1ca756bd8 | ||
|
|
16cf9f0ef2 | ||
|
|
133f69d66c | ||
|
|
bc60daff9e | ||
|
|
43a085d1ae | ||
|
|
8c33d0aa56 | ||
|
|
fe0767df13 | ||
|
|
08a25a0c8f | ||
|
|
cd410080bd | ||
|
|
7555378e3b | ||
|
|
80c95ee66a | ||
|
|
31563b210d | ||
|
|
861cd93324 | ||
|
|
abb344bb1a | ||
|
|
6147491d9e | ||
|
|
f1f18fbb4a | ||
|
|
9fc611f257 | ||
|
|
34a2e14a14 | ||
|
|
83fe65b9e9 | ||
|
|
ec26c8aa49 | ||
|
|
da43a3055f | ||
|
|
a38126c82f | ||
|
|
cb592ce588 | ||
|
|
d69c58a6da | ||
|
|
bdb1986e08 | ||
|
|
55356c78a8 | ||
|
|
a0f55252b1 | ||
|
|
013f5cffa9 | ||
|
|
d5d008f568 | ||
|
|
3b02134cdc | ||
|
|
a57d7b51b1 | ||
|
|
1a3c38d35f | ||
|
|
00aece0538 | ||
|
|
5a9cc835b3 | ||
|
|
58526cc849 | ||
|
|
955b5f43a5 | ||
|
|
447aec3fde | ||
|
|
473260a836 | ||
|
|
4d2784c10c | ||
|
|
d9af897595 | ||
|
|
23a48be315 | ||
|
|
ce8f48e5d1 | ||
|
|
6aaf839662 | ||
|
|
984a9e653e | ||
|
|
8dffa28b4d | ||
|
|
b05a4bdadd | ||
|
|
36087fe518 | ||
|
|
5eed87ec4d | ||
|
|
af66a73225 | ||
|
|
dcf913c17e | ||
|
|
68ccba8f74 | ||
|
|
956f7e29db | ||
|
|
4264c0577e | ||
|
|
cc37b59309 | ||
|
|
9f2f92095d | ||
|
|
0c1075c089 | ||
|
|
9c64710c8b | ||
|
|
f6f16b91db | ||
|
|
1986b5cfe6 | ||
|
|
6445b72d41 | ||
|
|
df7b8ba738 | ||
|
|
202083999e | ||
|
|
315f519e1d | ||
|
|
d7d580ae6f | ||
|
|
7017af303d | ||
|
|
0dc325daa4 | ||
|
|
6dffb47973 | ||
|
|
b19dad69d6 | ||
|
|
94c5ac64e9 | ||
|
|
c4bcd088fb | ||
|
|
aeecbe9396 | ||
|
|
171aade9cd | ||
|
|
67213ae86c | ||
|
|
24d9e53c3f | ||
|
|
573ed5f4b5 | ||
|
|
ceff628add | ||
|
|
0bb8cb9203 | ||
|
|
98349bde28 | ||
|
|
f09be932eb | ||
|
|
4c57ac2bbe | ||
|
|
1dd93c1b6b | ||
|
|
c9f85fe27f | ||
|
|
419cbe50f6 | ||
|
|
5031c8323f | ||
|
|
762d5913ce | ||
|
|
290df1b1c7 | ||
|
|
79170afc51 | ||
|
|
bba00c2bfe | ||
|
|
f7e2b3688f | ||
|
|
8d49b7dde1 | ||
|
|
138e60adb3 | ||
|
|
d6376c31e0 | ||
|
|
a7003e93c8 | ||
|
|
4821a11223 | ||
|
|
bf1b326988 | ||
|
|
39ddb6a175 | ||
|
|
b2a0b8c0f0 | ||
|
|
4debc46d0e | ||
|
|
f4e259d10f | ||
|
|
774d78228e | ||
|
|
0e62bde5c3 | ||
|
|
2bbd9b23e6 | ||
|
|
02676140e8 | ||
|
|
182beaa4a1 | ||
|
|
7c08a09529 | ||
|
|
ef964b5472 | ||
|
|
ee54ce9913 | ||
|
|
e59e146887 | ||
|
|
103ec0d58f | ||
|
|
a0d89ed514 | ||
|
|
c10888e6fe | ||
|
|
93455f8eb5 | ||
|
|
65acd96c8d | ||
|
|
fabe720b9b | ||
|
|
53dd313e97 | ||
|
|
2678d7a660 | ||
|
|
46718102c6 | ||
|
|
0f473fe3b1 | ||
|
|
2872602c9e | ||
|
|
ab653cae33 | ||
|
|
e6a035e575 | ||
|
|
fbe48d75dd | ||
|
|
20ba0f49dd | ||
|
|
c213e9878d | ||
|
|
9704ca4c18 | ||
|
|
49dce6219e | ||
|
|
260ff6c94f | ||
|
|
3ec281d104 | ||
|
|
c4c43d525b | ||
|
|
6c5cde363a | ||
|
|
d46b4d950f | ||
|
|
b369c4bb8a | ||
|
|
c3898487c4 | ||
|
|
ca3c5b400f | ||
|
|
97772b176c | ||
|
|
08a2965f1c | ||
|
|
76dcddfa3d | ||
|
|
79f476ae4d | ||
|
|
d406cb619c | ||
|
|
4f3890f1e4 | ||
|
|
7a9d58cc51 | ||
|
|
eef87da0e1 | ||
|
|
00e65f6f14 | ||
|
|
866e9824d1 | ||
|
|
482e6078e2 | ||
|
|
bc7ab296ef | ||
|
|
a5f4f53b56 | ||
|
|
b1227f526d | ||
|
|
78b42c8306 |
105
.circleci/config.yml
Normal file
105
.circleci/config.yml
Normal file
@@ -0,0 +1,105 @@
|
||||
version: 2.1
|
||||
|
||||
workflows:
|
||||
build:
|
||||
jobs:
|
||||
- linux-arm64-glibc-node-18:
|
||||
filters:
|
||||
tags:
|
||||
only: /^v.*/
|
||||
- linux-arm64-musl-node-18:
|
||||
filters:
|
||||
tags:
|
||||
only: /^v.*/
|
||||
- linux-arm64-glibc-node-20:
|
||||
filters:
|
||||
tags:
|
||||
only: /^v.*/
|
||||
- linux-arm64-musl-node-20:
|
||||
filters:
|
||||
tags:
|
||||
only: /^v.*/
|
||||
|
||||
jobs:
|
||||
linux-arm64-glibc-node-18:
|
||||
resource_class: arm.medium
|
||||
machine:
|
||||
image: ubuntu-2204:current
|
||||
steps:
|
||||
- checkout
|
||||
- run: |
|
||||
sudo docker run -dit --name sharp --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp arm64v8/debian:bullseye
|
||||
sudo docker exec sharp sh -c "apt-get update && apt-get install -y build-essential git python3 curl fonts-noto-core"
|
||||
sudo docker exec sharp sh -c "mkdir -p /etc/apt/keyrings"
|
||||
sudo docker exec sharp sh -c "curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg"
|
||||
sudo docker exec sharp sh -c "echo 'deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_18.x nodistro main' | tee /etc/apt/sources.list.d/nodesource.list"
|
||||
sudo docker exec sharp sh -c "apt-get update && apt-get install -y nodejs"
|
||||
- run: sudo docker exec sharp sh -c "npm install --build-from-source"
|
||||
- run: sudo docker exec sharp sh -c "npm test"
|
||||
- run: |
|
||||
sudo docker exec sharp sh -c "npm run package-from-local-build"
|
||||
sudo docker exec sharp sh -c "npm pkg set \"optionalDependencies.@img/sharp-linux-arm64=file:./npm/linux-arm64\""
|
||||
sudo docker exec sharp sh -c "npm run clean"
|
||||
sudo docker exec sharp sh -c "npm install --ignore-scripts"
|
||||
sudo docker exec sharp sh -c "npm test"
|
||||
- run: "[[ -n $CIRCLE_TAG ]] && sudo docker exec --env prebuild_upload sharp sh -c \"cd src && ln -s ../package.json && npx prebuild --upload=$prebuild_upload\" || true"
|
||||
linux-arm64-glibc-node-20:
|
||||
resource_class: arm.medium
|
||||
machine:
|
||||
image: ubuntu-2204:current
|
||||
steps:
|
||||
- checkout
|
||||
- run: |
|
||||
sudo docker run -dit --name sharp --workdir /mnt/sharp arm64v8/debian:bullseye
|
||||
sudo docker exec sharp sh -c "apt-get update && apt-get install -y build-essential git python3 curl fonts-noto-core"
|
||||
sudo docker exec sharp sh -c "mkdir -p /etc/apt/keyrings"
|
||||
sudo docker exec sharp sh -c "curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg"
|
||||
sudo docker exec sharp sh -c "echo 'deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_20.x nodistro main' | tee /etc/apt/sources.list.d/nodesource.list"
|
||||
sudo docker exec sharp sh -c "apt-get update && apt-get install -y nodejs"
|
||||
sudo docker exec sharp sh -c "mkdir -p /mnt/sharp"
|
||||
sudo docker cp . sharp:/mnt/sharp/.
|
||||
- run: sudo docker exec sharp sh -c "npm install --build-from-source"
|
||||
- run: sudo docker exec sharp sh -c "npm test"
|
||||
- run: |
|
||||
sudo docker exec sharp sh -c "npm run package-from-local-build"
|
||||
sudo docker exec sharp sh -c "npm pkg set \"optionalDependencies.@img/sharp-linux-arm64=file:./npm/linux-arm64\""
|
||||
sudo docker exec sharp sh -c "npm run clean"
|
||||
sudo docker exec sharp sh -c "npm install --ignore-scripts"
|
||||
sudo docker exec sharp sh -c "npm test"
|
||||
linux-arm64-musl-node-18:
|
||||
resource_class: arm.medium
|
||||
machine:
|
||||
image: ubuntu-2204:current
|
||||
steps:
|
||||
- checkout
|
||||
- run: |
|
||||
sudo docker run -dit --name sharp --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp node:18-alpine3.17
|
||||
sudo docker exec sharp sh -c "apk add build-base git python3 font-noto --update-cache"
|
||||
- run: sudo docker exec sharp sh -c "npm install --build-from-source"
|
||||
- run: sudo docker exec sharp sh -c "npm test"
|
||||
- run: |
|
||||
sudo docker exec sharp sh -c "npm run package-from-local-build"
|
||||
sudo docker exec sharp sh -c "npm pkg set \"optionalDependencies.@img/sharp-linuxmusl-arm64=file:./npm/linuxmusl-arm64\""
|
||||
sudo docker exec sharp sh -c "npm run clean"
|
||||
sudo docker exec sharp sh -c "npm install --ignore-scripts"
|
||||
sudo docker exec sharp sh -c "npm test"
|
||||
- run: "[[ -n $CIRCLE_TAG ]] && sudo docker exec --env prebuild_upload sharp sh -c \"cd src && ln -s ../package.json && npx prebuild --upload=$prebuild_upload\" || true"
|
||||
linux-arm64-musl-node-20:
|
||||
resource_class: arm.medium
|
||||
machine:
|
||||
image: ubuntu-2204:current
|
||||
steps:
|
||||
- checkout
|
||||
- run: |
|
||||
sudo docker run -dit --name sharp --workdir /mnt/sharp node:20-alpine3.18
|
||||
sudo docker exec sharp sh -c "apk add build-base git python3 font-noto --update-cache"
|
||||
sudo docker exec sharp sh -c "mkdir -p /mnt/sharp"
|
||||
sudo docker cp . sharp:/mnt/sharp/.
|
||||
- run: sudo docker exec sharp sh -c "npm install --build-from-source"
|
||||
- run: sudo docker exec sharp sh -c "npm test"
|
||||
- run: |
|
||||
sudo docker exec sharp sh -c "npm run package-from-local-build"
|
||||
sudo docker exec sharp sh -c "npm pkg set \"optionalDependencies.@img/sharp-linuxmusl-arm64=file:./npm/linuxmusl-arm64\""
|
||||
sudo docker exec sharp sh -c "npm run clean"
|
||||
sudo docker exec sharp sh -c "npm install --ignore-scripts"
|
||||
sudo docker exec sharp sh -c "npm test"
|
||||
11
.cirrus.yml
11
.cirrus.yml
@@ -1,14 +1,17 @@
|
||||
freebsd_instance:
|
||||
image_family: freebsd-13-0-snap
|
||||
image_family: freebsd-14-0-snap
|
||||
|
||||
task:
|
||||
name: FreeBSD
|
||||
env:
|
||||
IGNORE_OSVERSION: yes
|
||||
skip_notifications: true
|
||||
prerequisites_script:
|
||||
- pkg update -f
|
||||
- pkg upgrade -y
|
||||
- pkg install -y pkgconf vips node npm
|
||||
- pkg install -y devel/git devel/pkgconf graphics/vips www/node20 www/npm
|
||||
- pkg-config --modversion vips-cpp
|
||||
install_script:
|
||||
- npm install --unsafe-perm
|
||||
- npm install --build-from-source
|
||||
test_script:
|
||||
- npm test
|
||||
- npx mocha --no-config --spec=test/unit/io.js --timeout=30000
|
||||
|
||||
1
.gitattributes
vendored
1
.gitattributes
vendored
@@ -1 +0,0 @@
|
||||
src/libvips/* linguist-vendored
|
||||
21
.github/CONTRIBUTING.md
vendored
21
.github/CONTRIBUTING.md
vendored
@@ -16,36 +16,33 @@ If a [similar request](https://github.com/lovell/sharp/labels/enhancement) exist
|
||||
it's probably fastest to add a comment to it about your requirement.
|
||||
|
||||
Implementation is usually straightforward if libvips
|
||||
[already supports](https://libvips.github.io/libvips/API/current/func-list.html)
|
||||
[already supports](https://www.libvips.org/API/current/func-list.html)
|
||||
the feature you need.
|
||||
|
||||
## Submit a Pull Request to fix a bug
|
||||
|
||||
Thank you! To prevent the problem occurring again, please add unit tests that would have failed.
|
||||
|
||||
Please select the `master` branch as the destination for your Pull Request so your fix can be included in the next minor release.
|
||||
Please select the `main` branch as the destination for your Pull Request so your fix can be included in the next minor release.
|
||||
|
||||
Please squash your changes into a single commit using a command like `git rebase -i upstream/master`.
|
||||
Please squash your changes into a single commit using a command like `git rebase -i upstream/main`.
|
||||
|
||||
To test C++ changes, you can compile the module using `npm install` and then run the tests using `npm test`.
|
||||
To test C++ changes, you can compile the module using `npm install --build-from-source` and then run the tests using `npm test`.
|
||||
|
||||
## Submit a Pull Request with a new feature
|
||||
|
||||
Please add JavaScript [unit tests](https://github.com/lovell/sharp/tree/master/test/unit) to cover your new feature.
|
||||
Please add JavaScript [unit tests](https://github.com/lovell/sharp/tree/main/test/unit) to cover your new feature.
|
||||
A test coverage report for the JavaScript code is generated in the `coverage/lcov-report` directory.
|
||||
Please also update the [TypeScript definitions](https://github.com/lovell/sharp/tree/main/lib/index.d.ts), along with the [type definition tests](https://github.com/lovell/sharp/tree/main/test/types/sharp.test-d.ts).
|
||||
|
||||
Where possible, the functional tests use gradient-based perceptual hashes
|
||||
based on [dHash](http://www.hackerfactor.com/blog/index.php?/archives/529-Kind-of-Like-That.html)
|
||||
to compare expected vs actual images.
|
||||
|
||||
You deserve to add your details to the [list of contributors](https://github.com/lovell/sharp/blob/master/package.json#L5).
|
||||
You deserve to add your details to the [list of contributors](https://github.com/lovell/sharp/blob/main/package.json#L5).
|
||||
|
||||
Any change that modifies the existing public API should be added to the relevant work-in-progress branch for inclusion in the next major release.
|
||||
|
||||
| Release | WIP branch |
|
||||
| ------: | :--------- |
|
||||
| v0.26.0 | zoom |
|
||||
|
||||
Please squash your changes into a single commit using a command like `git rebase -i upstream/<wip-branch>`.
|
||||
|
||||
### Add a new public method
|
||||
@@ -66,7 +63,7 @@ By way of example, the `background()` method present in v0.20.0 was deprecated i
|
||||
|
||||
## 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:
|
||||
```sh
|
||||
@@ -97,5 +94,5 @@ Please feel free to ask any questions via a
|
||||
[new issue](https://github.com/lovell/sharp/issues/new).
|
||||
|
||||
If you're unable to post details publicly, please
|
||||
[e-mail](https://github.com/lovell/sharp/blob/master/package.json#L5)
|
||||
[e-mail](https://github.com/lovell/sharp/blob/main/package.json#L5)
|
||||
for private, paid consulting.
|
||||
|
||||
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Documentation
|
||||
url: https://sharp.pixelplumbing.com/
|
||||
about: Installation instructions, complete API documentation with examples, changelog
|
||||
22
.github/ISSUE_TEMPLATE/feature_request.md
vendored
22
.github/ISSUE_TEMPLATE/feature_request.md
vendored
@@ -5,12 +5,24 @@ labels: enhancement
|
||||
|
||||
---
|
||||
|
||||
What are you trying to achieve?
|
||||
## Feature request
|
||||
|
||||
Have you searched for similar feature requests?
|
||||
### What are you trying to achieve?
|
||||
|
||||
What would you expect the API to look like?
|
||||
<!-- Please provide context here. -->
|
||||
|
||||
What alternatives have you considered?
|
||||
### When you searched for similar feature requests, what did you find that might be related?
|
||||
|
||||
Is there a sample image that helps explain?
|
||||
<!-- Please demonstrate your research here. -->
|
||||
|
||||
### What would you expect the API to look like?
|
||||
|
||||
<!-- Please provide your suggestions here. -->
|
||||
|
||||
### What alternatives have you considered?
|
||||
|
||||
<!-- Please provide your ideas here. -->
|
||||
|
||||
### Please provide sample image(s) that help explain this feature
|
||||
|
||||
<!-- Please provide links to one or more images here. -->
|
||||
|
||||
63
.github/ISSUE_TEMPLATE/installation.md
vendored
63
.github/ISSUE_TEMPLATE/installation.md
vendored
@@ -5,16 +5,65 @@ labels: installation
|
||||
|
||||
---
|
||||
|
||||
Did you see the [documentation relating to installation](https://sharp.pixelplumbing.com/install)?
|
||||
<!-- Please try to answer as many of these questions as possible. -->
|
||||
|
||||
Have you ensured the platform and version of Node.js used for `npm install` is the same as the platform and version of Node.js used at runtime?
|
||||
## Possible install-time or require-time problem
|
||||
|
||||
Are you using the latest version? Is the version currently in use as reported by `npm ls sharp` the same as the latest version as reported by `npm view sharp dist-tags.latest`?
|
||||
<!-- Please place an [x] in the box to confirm. -->
|
||||
|
||||
If you are installing as a `root` or `sudo` user, have you tried with the `npm install --unsafe-perm` flag?
|
||||
- [ ] I have read and understood all of the [documentation relating to installation](https://sharp.pixelplumbing.com/install).
|
||||
- [ ] I have searched for known bugs relating to this problem in my choice of package manager.
|
||||
|
||||
If you are using the `ignore-scripts` feature of `npm`, have you tried with the `npm install --ignore-scripts=false` flag?
|
||||
You must confirm both of these before continuing.
|
||||
|
||||
What is the complete output of running `npm install --verbose sharp`? Have you checked this output for useful error messages?
|
||||
### Are you using the latest version of sharp?
|
||||
|
||||
What is the output of running `npx envinfo --binaries --system`?
|
||||
<!-- Please place an [x] in the box to confirm. -->
|
||||
|
||||
- [ ] I am using the latest version of `sharp` as reported by `npm view sharp dist-tags.latest`.
|
||||
|
||||
If you cannot confirm this, please upgrade to the latest version and try again before opening an issue.
|
||||
|
||||
If you are using another package which depends on a version of `sharp` that is not the latest,
|
||||
please open an issue against that package instead.
|
||||
|
||||
### Are you using a supported runtime?
|
||||
|
||||
<!-- Please place an [x] in the relevant box to confirm. -->
|
||||
|
||||
- [ ] I am using Node.js with a version that satisfies `^18.17.0 || ^20.3.0 || >=21.0.0`
|
||||
- [ ] I am using Deno
|
||||
- [ ] I am using Bun
|
||||
|
||||
If you cannot confirm any of these,
|
||||
please upgrade to the latest version
|
||||
and try again before opening an issue.
|
||||
|
||||
### Are you using a supported package manager and installing optional dependencies?
|
||||
|
||||
<!-- Please place an [x] in the relevant box to confirm. -->
|
||||
|
||||
- [ ] I am using npm >= 9.6.5 with `--include=optional`
|
||||
- [ ] I am using yarn >= 3.2.0
|
||||
- [ ] I am using pnpm >= 7.1.0 with `--no-optional=false`
|
||||
- [ ] I am using Deno
|
||||
- [ ] I am using Bun
|
||||
|
||||
If you cannot confirm any of these, please upgrade to the latest version of your chosen package manager
|
||||
and ensure you are allowing the installation of optional or multi-platform dependencies before opening an issue.
|
||||
|
||||
### What is the complete error message, including the full stack trace?
|
||||
|
||||
<!-- Please provide the error message and stack trace here. -->
|
||||
|
||||
### What is the complete output of running `npm install --verbose --foreground-scripts sharp` in an empty directory?
|
||||
|
||||
<details>
|
||||
|
||||
<!-- Please provide output of `npm install --verbose --foreground-scripts sharp` in an empty directory here. -->
|
||||
|
||||
</details>
|
||||
|
||||
### What is the output of running `npx envinfo --binaries --system --npmPackages=sharp --npmGlobalPackages=sharp`?
|
||||
|
||||
<!-- Please provide output of `npx envinfo --binaries --system --npmPackages=sharp --npmGlobalPackages=sharp` here. -->
|
||||
|
||||
41
.github/ISSUE_TEMPLATE/possible-bug.md
vendored
41
.github/ISSUE_TEMPLATE/possible-bug.md
vendored
@@ -7,14 +7,43 @@ labels: triage
|
||||
|
||||
<!-- If this issue relates to installation, please use https://github.com/lovell/sharp/issues/new?labels=installation&template=installation.md instead. -->
|
||||
|
||||
Are you using the latest version? Is the version currently in use as reported by `npm ls sharp` the same as the latest version as reported by `npm view sharp dist-tags.latest`?
|
||||
## Possible bug
|
||||
|
||||
What are the steps to reproduce?
|
||||
### Is this a possible bug in a feature of sharp, unrelated to installation?
|
||||
|
||||
What is the expected behaviour?
|
||||
<!-- Please place an [x] in the box to confirm. -->
|
||||
|
||||
Are you able to provide a minimal, standalone code sample, without other dependencies, that demonstrates this problem?
|
||||
- [ ] Running `npm install sharp` completes without error.
|
||||
- [ ] Running `node -e "require('sharp')"` completes without error.
|
||||
|
||||
Are you able to provide a sample image that helps explain the problem?
|
||||
If you cannot confirm both of these, please open an [installation issue](https://github.com/lovell/sharp/issues/new?labels=installation&template=installation.md) instead.
|
||||
|
||||
What is the output of running `npx envinfo --binaries --system`?
|
||||
### Are you using the latest version of sharp?
|
||||
|
||||
<!-- Please place an [x] in the box to confirm. -->
|
||||
|
||||
- [ ] I am using the latest version of `sharp` as reported by `npm view sharp dist-tags.latest`.
|
||||
|
||||
If you cannot confirm this, please upgrade to the latest version and try again before opening an issue.
|
||||
|
||||
If you are using another package which depends on a version of `sharp` that is not the latest, please open an issue against that package instead.
|
||||
|
||||
### What is the output of running `npx envinfo --binaries --system --npmPackages=sharp --npmGlobalPackages=sharp`?
|
||||
|
||||
<!-- Please provide output of the above command here. -->
|
||||
|
||||
### What are the steps to reproduce?
|
||||
|
||||
<!-- Please enter steps to reproduce here. -->
|
||||
|
||||
### What is the expected behaviour?
|
||||
|
||||
<!-- Please enter the expected behaviour here. -->
|
||||
|
||||
### Please provide a minimal, standalone code sample, without other dependencies, that demonstrates this problem
|
||||
|
||||
<!-- Please provide either formatted code or a link to a repo/gist that allows someone else to reproduce here. -->
|
||||
|
||||
### Please provide sample image(s) that help explain this problem
|
||||
|
||||
<!-- Please provide links to one or more images here. -->
|
||||
|
||||
18
.github/ISSUE_TEMPLATE/question.md
vendored
18
.github/ISSUE_TEMPLATE/question.md
vendored
@@ -7,10 +7,20 @@ labels: question
|
||||
|
||||
<!-- If this issue relates to installation, please use https://github.com/lovell/sharp/issues/new?labels=installation&template=installation.md instead. -->
|
||||
|
||||
What are you trying to achieve?
|
||||
## Question about an existing feature
|
||||
|
||||
Have you searched for similar questions?
|
||||
### What are you trying to achieve?
|
||||
|
||||
Are you able to provide a minimal, standalone code sample that demonstrates this question?
|
||||
<!-- Please provide context here. -->
|
||||
|
||||
Are you able to provide a sample image that helps explain the question?
|
||||
### When you searched for similar issues, what did you find that might be related?
|
||||
|
||||
<!-- Please demonstrate your research here. -->
|
||||
|
||||
### Please provide a minimal, standalone code sample, without other dependencies, that demonstrates this question
|
||||
|
||||
<!-- Please provide either formatted code or a link to a repo/gist that helps someone else understand here. -->
|
||||
|
||||
### Please provide sample image(s) that help explain this question
|
||||
|
||||
<!-- Please provide links to one or more images here. -->
|
||||
|
||||
18
.github/SECURITY.md
vendored
Normal file
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.
|
||||
206
.github/workflows/ci.yml
vendored
Normal file
206
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,206 @@
|
||||
name: CI
|
||||
on:
|
||||
- push
|
||||
- pull_request
|
||||
permissions: {}
|
||||
jobs:
|
||||
github-runner:
|
||||
permissions:
|
||||
contents: write
|
||||
name: ${{ matrix.platform }} - Node.js ${{ matrix.nodejs_version_major }} ${{ matrix.prebuild && '- prebuild' }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
container: ${{ matrix.container }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-22.04
|
||||
container: rockylinux:8
|
||||
nodejs_arch: x64
|
||||
nodejs_version: "^18.17.0"
|
||||
nodejs_version_major: 18
|
||||
platform: linux-x64
|
||||
prebuild: true
|
||||
- os: ubuntu-22.04
|
||||
container: rockylinux:8
|
||||
nodejs_arch: x64
|
||||
nodejs_version: "^20.3.0"
|
||||
nodejs_version_major: 20
|
||||
platform: linux-x64
|
||||
- os: ubuntu-22.04
|
||||
container: node:18-alpine3.17
|
||||
nodejs_version_major: 18
|
||||
platform: linuxmusl-x64
|
||||
prebuild: true
|
||||
- os: ubuntu-22.04
|
||||
container: node:20-alpine3.18
|
||||
nodejs_version_major: 20
|
||||
platform: linuxmusl-x64
|
||||
- os: macos-11
|
||||
nodejs_arch: x64
|
||||
nodejs_version: "^18.17.0"
|
||||
nodejs_version_major: 18
|
||||
platform: darwin-x64
|
||||
prebuild: true
|
||||
- os: macos-11
|
||||
nodejs_arch: x64
|
||||
nodejs_version: "^20.3.0"
|
||||
nodejs_version_major: 20
|
||||
platform: darwin-x64
|
||||
- os: macos-14
|
||||
nodejs_arch: arm64
|
||||
nodejs_version: "^18.17.0"
|
||||
nodejs_version_major: 18
|
||||
platform: darwin-arm64
|
||||
prebuild: true
|
||||
- os: macos-14
|
||||
nodejs_arch: arm64
|
||||
nodejs_version: "^20.3.0"
|
||||
nodejs_version_major: 20
|
||||
platform: darwin-arm64
|
||||
- os: windows-2019
|
||||
nodejs_arch: x86
|
||||
nodejs_version: "18.18.2" # pinned to avoid 18.19.0 and npm 10
|
||||
nodejs_version_major: 18
|
||||
platform: win32-ia32
|
||||
prebuild: true
|
||||
- os: windows-2019
|
||||
nodejs_arch: x86
|
||||
nodejs_version: "^20.3.0"
|
||||
nodejs_version_major: 20
|
||||
platform: win32-ia32
|
||||
- os: windows-2019
|
||||
nodejs_arch: x64
|
||||
nodejs_version: "^18.17.0"
|
||||
nodejs_version_major: 18
|
||||
platform: win32-x64
|
||||
prebuild: true
|
||||
- os: windows-2019
|
||||
nodejs_arch: x64
|
||||
nodejs_version: "^20.3.0"
|
||||
nodejs_version_major: 20
|
||||
platform: win32-x64
|
||||
steps:
|
||||
- name: Dependencies (Rocky Linux glibc)
|
||||
if: contains(matrix.container, 'rockylinux')
|
||||
run: |
|
||||
dnf install -y gcc-toolset-11-gcc-c++ make git python3 fontconfig google-noto-sans-fonts
|
||||
echo "/opt/rh/gcc-toolset-11/root/usr/bin" >> $GITHUB_PATH
|
||||
- name: Dependencies (Linux musl)
|
||||
if: contains(matrix.container, 'alpine')
|
||||
run: apk add build-base git python3 font-noto --update-cache
|
||||
- name: Dependencies (Python 3.11 - macOS, Windows)
|
||||
if: contains(matrix.os, 'macos') || contains(matrix.os, 'windows')
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- name: Dependencies (Node.js)
|
||||
if: "!contains(matrix.platform, 'linuxmusl')"
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.nodejs_version }}
|
||||
architecture: ${{ matrix.nodejs_arch }}
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Install
|
||||
run: npm install --build-from-source
|
||||
- name: Test
|
||||
run: npm test
|
||||
- name: Test packaging
|
||||
run: |
|
||||
npm run package-from-local-build
|
||||
npm pkg set "optionalDependencies.@img/sharp-${{ matrix.platform }}=file:./npm/${{ matrix.platform }}"
|
||||
npm run clean
|
||||
npm install --ignore-scripts
|
||||
npm test
|
||||
- name: Prebuild
|
||||
if: matrix.prebuild && startsWith(github.ref, 'refs/tags/')
|
||||
env:
|
||||
prebuild_upload: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
node -e "require('fs').cpSync('package.json', 'src/package.json')"
|
||||
cd src
|
||||
npx prebuild
|
||||
github-runner-qemu:
|
||||
permissions:
|
||||
contents: write
|
||||
name: ${{ matrix.platform }} - Node.js ${{ matrix.nodejs_version_major }} - prebuild
|
||||
runs-on: ubuntu-22.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- platform: linux-arm
|
||||
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
|
||||
run_on_arch: s390x
|
||||
nodejs_arch: s390x
|
||||
nodejs_hostname: nodejs.org
|
||||
nodejs_version: "18.17.0"
|
||||
nodejs_version_major: 18
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: uraimo/run-on-arch-action@v2
|
||||
with:
|
||||
arch: ${{ matrix.run_on_arch }}
|
||||
distro: buster
|
||||
env: |
|
||||
prebuild_upload: "${{ startsWith(github.ref, 'refs/tags/') && secrets.GITHUB_TOKEN || '' }}"
|
||||
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
|
||||
npm pkg set "optionalDependencies.@img/sharp-${{ matrix.platform }}=file:./npm/${{ matrix.platform }}"
|
||||
npm run clean
|
||||
npm install --ignore-scripts
|
||||
npx mocha --no-config --spec=test/unit/io.js --timeout=30000
|
||||
[[ -n $prebuild_upload ]] && cd src && ln -s ../package.json && npx prebuild || true
|
||||
github-runner-emscripten:
|
||||
permissions:
|
||||
contents: write
|
||||
name: wasm32 - prebuild
|
||||
runs-on: ubuntu-22.04
|
||||
container: "emscripten/emsdk:3.1.56"
|
||||
steps:
|
||||
- name: Checkout
|
||||
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: Test packaging
|
||||
run: |
|
||||
emmake npm run package-from-local-build
|
||||
npm pkg set "optionalDependencies.@img/sharp-wasm32=file:./npm/wasm32"
|
||||
npm run clean
|
||||
rm -rf node_modules/@img/sharp-linux-x64
|
||||
npm install --cpu=wasm32
|
||||
npm test
|
||||
- name: Prebuild
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
env:
|
||||
npm_config_nodedir: emscripten
|
||||
prebuild_upload: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: cd src && ln -s ../package.json && emmake npx prebuild --platform=emscripten --arch=wasm32 --strip=0
|
||||
174
.github/workflows/npm.yml
vendored
Normal file
174
.github/workflows/npm.yml
vendored
Normal file
@@ -0,0 +1,174 @@
|
||||
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-22.04
|
||||
runtime: node
|
||||
package-manager: npm
|
||||
- name: linux-x64-node-pnpm
|
||||
runs-on: ubuntu-22.04
|
||||
runtime: node
|
||||
package-manager: pnpm
|
||||
- name: linux-x64-node-yarn
|
||||
runs-on: ubuntu-22.04
|
||||
runtime: node
|
||||
package-manager: yarn
|
||||
- name: linux-x64-node-yarn-pnp
|
||||
runs-on: ubuntu-22.04
|
||||
runtime: node
|
||||
package-manager: yarn-pnp
|
||||
- name: linux-x64-deno
|
||||
runs-on: ubuntu-22.04
|
||||
runtime: deno
|
||||
- name: linux-x64-bun
|
||||
runs-on: ubuntu-22.04
|
||||
runtime: bun
|
||||
|
||||
- name: darwin-x64-node-npm
|
||||
runs-on: macos-11
|
||||
runtime: node
|
||||
package-manager: npm
|
||||
- name: darwin-x64-node-pnpm
|
||||
runs-on: macos-11
|
||||
runtime: node
|
||||
package-manager: pnpm
|
||||
- name: darwin-x64-node-yarn
|
||||
runs-on: macos-11
|
||||
runtime: node
|
||||
package-manager: yarn
|
||||
- name: darwin-x64-node-yarn-pnp
|
||||
runs-on: macos-11
|
||||
runtime: node
|
||||
package-manager: yarn-pnp
|
||||
- name: darwin-x64-deno
|
||||
runs-on: macos-11
|
||||
runtime: deno
|
||||
- name: darwin-x64-bun
|
||||
runs-on: macos-11
|
||||
runtime: bun
|
||||
|
||||
- name: win32-x64-node-npm
|
||||
runs-on: windows-2019
|
||||
runtime: node
|
||||
package-manager: npm
|
||||
- name: win32-x64-node-pnpm
|
||||
runs-on: windows-2019
|
||||
runtime: node
|
||||
package-manager: pnpm
|
||||
- name: win32-x64-node-yarn
|
||||
runs-on: windows-2019
|
||||
runtime: node
|
||||
package-manager: yarn
|
||||
- name: win32-x64-node-yarn-pnp
|
||||
runs-on: windows-2019
|
||||
runtime: node
|
||||
package-manager: yarn-pnp
|
||||
- name: win32-x64-deno
|
||||
runs-on: windows-2019
|
||||
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@v2
|
||||
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@v1
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Version
|
||||
id: version
|
||||
uses: actions/github-script@v6
|
||||
with:
|
||||
script: |
|
||||
core.setOutput('semver', context.ref.replace('refs/tags/v',''))
|
||||
- name: Create package.json
|
||||
uses: DamianReeves/write-file-action@v1.2
|
||||
with:
|
||||
path: package.json
|
||||
contents: |
|
||||
{
|
||||
"dependencies": {
|
||||
"sharp": "${{ steps.version.outputs.semver }}"
|
||||
},
|
||||
"type": "module"
|
||||
}
|
||||
- name: Create release.mjs
|
||||
uses: DamianReeves/write-file-action@v1.2
|
||||
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 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
|
||||
12
.gitignore
vendored
12
.gitignore
vendored
@@ -1,15 +1,13 @@
|
||||
build
|
||||
src/build
|
||||
src/node_modules
|
||||
node_modules
|
||||
/coverage
|
||||
npm/*/*
|
||||
!npm/*/package.json
|
||||
test/bench/node_modules
|
||||
test/fixtures/output*
|
||||
test/fixtures/vips-properties.xml
|
||||
test/leak/libvips.supp
|
||||
test/saliency/report.json
|
||||
test/saliency/Image*
|
||||
test/saliency/[Uu]serData*
|
||||
!test/saliency/userData.js
|
||||
vendor
|
||||
.gitattributes
|
||||
.DS_Store
|
||||
.nyc_output
|
||||
.vscode/
|
||||
|
||||
7
.mocharc.jsonc
Normal file
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 +1,6 @@
|
||||
{
|
||||
"include-regex": "(sharp\\.node|libvips-cpp\\.dll)",
|
||||
"runtime": "napi",
|
||||
"include-regex": "(sharp-.+\\.node|libvips-.+\\.dll)",
|
||||
"prerelease": true,
|
||||
"strip": true
|
||||
}
|
||||
|
||||
139
.travis.yml
139
.travis.yml
@@ -1,139 +0,0 @@
|
||||
jobs:
|
||||
include:
|
||||
- name: "Linux x64 (CentOS 7, glibc 2.17) - Node.js 10"
|
||||
os: linux
|
||||
dist: bionic
|
||||
language: shell
|
||||
before_install:
|
||||
- sudo docker run -dit --name sharp --env CI --env TRAVIS_TAG --env prebuild_upload --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp centos:7
|
||||
- sudo docker exec sharp bash -c "curl -sL https://rpm.nodesource.com/setup_10.x | bash -"
|
||||
- sudo docker exec sharp yum install -y gcc-c++ make git nodejs
|
||||
install: sudo docker exec sharp bash -c "npm install --unsafe-perm"
|
||||
script: sudo docker exec sharp bash -c "npm test"
|
||||
|
||||
- name: "Linux x64 (CentOS 7, glibc 2.17) - Node.js 12"
|
||||
os: linux
|
||||
dist: bionic
|
||||
language: shell
|
||||
before_install:
|
||||
- sudo docker run -dit --name sharp --env CI --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp centos:7
|
||||
- sudo docker exec sharp bash -c "curl -sL https://rpm.nodesource.com/setup_12.x | bash -"
|
||||
- sudo docker exec sharp yum install -y gcc-c++ make git nodejs
|
||||
install: sudo docker exec sharp bash -c "npm install --unsafe-perm"
|
||||
script: sudo docker exec sharp bash -c "npm test"
|
||||
|
||||
- name: "Linux x64 (CentOS 7, glibc 2.17) - Node.js 14"
|
||||
os: linux
|
||||
dist: bionic
|
||||
language: shell
|
||||
before_install:
|
||||
- sudo docker run -dit --name sharp --env CI --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp centos:7
|
||||
- sudo docker exec sharp bash -c "curl -sL https://rpm.nodesource.com/setup_14.x | bash -"
|
||||
- sudo docker exec sharp yum install -y gcc-c++ make git nodejs
|
||||
install: sudo docker exec sharp bash -c "npm install --unsafe-perm"
|
||||
script: sudo docker exec sharp bash -c "npm test"
|
||||
|
||||
- name: "Linux x64 (Alpine 3.9, musl 1.1.20) - Node.js 10"
|
||||
os: linux
|
||||
dist: bionic
|
||||
language: shell
|
||||
before_install:
|
||||
- sudo docker run -dit --name sharp --env CI --env TRAVIS_TAG --env prebuild_upload --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp node:10.17.0-alpine3.9 # https://github.com/nodejs/docker-node/issues/1158
|
||||
- sudo docker exec sharp apk add build-base git python2 --update-cache
|
||||
install: sudo docker exec sharp sh -c "npm install --unsafe-perm"
|
||||
script: sudo docker exec sharp sh -c "npm test"
|
||||
|
||||
- name: "Linux x64 (Alpine 3.11, musl 1.1.20) - Node.js 12"
|
||||
os: linux
|
||||
dist: bionic
|
||||
language: shell
|
||||
before_install:
|
||||
- sudo docker run -dit --name sharp --env CI --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp node:12.0-alpine
|
||||
- sudo docker exec sharp apk add build-base git python2 --update-cache
|
||||
install: sudo docker exec sharp sh -c "npm install --unsafe-perm"
|
||||
script: sudo docker exec sharp sh -c "npm test"
|
||||
|
||||
- name: "Linux x64 (Alpine 3.11, musl 1.1.20) - Node.js 14"
|
||||
os: linux
|
||||
dist: bionic
|
||||
language: shell
|
||||
before_install:
|
||||
- sudo docker run -dit --name sharp --env CI --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp node:14.0-alpine
|
||||
- sudo docker exec sharp apk add build-base git python2 --update-cache
|
||||
install: sudo docker exec sharp sh -c "npm install --unsafe-perm"
|
||||
script: sudo docker exec sharp sh -c "npm test"
|
||||
|
||||
- name: "Linux ARM64v8 (Debian 11, glibc 2.29) - Node.js 10"
|
||||
arch: arm64
|
||||
os: linux
|
||||
dist: bionic
|
||||
language: shell
|
||||
before_install:
|
||||
- sudo docker run -dit --name sharp --env CI --env TRAVIS_TAG --env prebuild_upload --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 python2 curl"
|
||||
- sudo docker exec sharp sh -c "curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -"
|
||||
- sudo docker exec sharp sh -c "echo 'deb https://deb.nodesource.com/node_10.x buster main' >/etc/apt/sources.list.d/nodesource.list"
|
||||
- sudo docker exec sharp sh -c "apt-get update && apt-get install -y nodejs=10.*"
|
||||
install: sudo docker exec sharp sh -c "npm install --unsafe-perm"
|
||||
script: sudo docker exec sharp sh -c "npm test"
|
||||
|
||||
- name: "Linux ARM64v8 (Debian 11, glibc 2.29) - Node.js 12"
|
||||
arch: arm64
|
||||
os: linux
|
||||
dist: bionic
|
||||
language: shell
|
||||
before_install:
|
||||
- sudo docker run -dit --name sharp --env CI --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 python2 curl"
|
||||
- sudo docker exec sharp sh -c "curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -"
|
||||
- sudo docker exec sharp sh -c "echo 'deb https://deb.nodesource.com/node_12.x buster main' >/etc/apt/sources.list.d/nodesource.list"
|
||||
- sudo docker exec sharp sh -c "apt-get update && apt-get install -y nodejs"
|
||||
install: sudo docker exec sharp sh -c "npm install --unsafe-perm"
|
||||
script: sudo docker exec sharp sh -c "npm test"
|
||||
|
||||
- name: "Linux ARM64v8 (Debian 11, glibc 2.29) - Node.js 14"
|
||||
arch: arm64
|
||||
os: linux
|
||||
dist: bionic
|
||||
language: shell
|
||||
before_install:
|
||||
- sudo docker run -dit --name sharp --env CI --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 python2 curl"
|
||||
- sudo docker exec sharp sh -c "curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -"
|
||||
- sudo docker exec sharp sh -c "echo 'deb https://deb.nodesource.com/node_14.x buster main' >/etc/apt/sources.list.d/nodesource.list"
|
||||
- sudo docker exec sharp sh -c "apt-get update && apt-get install -y nodejs"
|
||||
install: sudo docker exec sharp sh -c "npm install --unsafe-perm"
|
||||
script: sudo docker exec sharp sh -c "npm test"
|
||||
|
||||
- name: "macOS (10.13) - Node.js 10"
|
||||
os: osx
|
||||
osx_image: xcode10.1
|
||||
language: node_js
|
||||
node_js: "10"
|
||||
|
||||
- name: "macOS (10.13) - Node.js 12"
|
||||
os: osx
|
||||
osx_image: xcode10.1
|
||||
language: node_js
|
||||
node_js: "12"
|
||||
before_install: unset prebuild_upload
|
||||
|
||||
- name: "macOS (10.13) - Node.js 14"
|
||||
os: osx
|
||||
osx_image: xcode10.1
|
||||
language: node_js
|
||||
node_js: "14"
|
||||
before_install: unset prebuild_upload
|
||||
|
||||
- name: "Unit test coverage report"
|
||||
os: linux
|
||||
dist: bionic
|
||||
language: node_js
|
||||
node_js: "13"
|
||||
before_install: unset prebuild_upload
|
||||
after_success:
|
||||
- npm install coveralls
|
||||
- cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js
|
||||
|
||||
cache:
|
||||
npm: false
|
||||
40
README.md
40
README.md
@@ -1,10 +1,14 @@
|
||||
# sharp
|
||||
|
||||
<img src="https://cdn.jsdelivr.net/gh/lovell/sharp@master/docs/image/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right">
|
||||
<img src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right">
|
||||
|
||||
The typical use case for this high speed Node.js module
|
||||
The typical use case for this high speed Node-API module
|
||||
is to convert large images in common formats to
|
||||
smaller, web-friendly JPEG, PNG and WebP 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
|
||||
quickest ImageMagick and GraphicsMagick settings
|
||||
@@ -16,9 +20,17 @@ Lanczos resampling ensures quality is not sacrificed for speed.
|
||||
As well as image resizing, operations such as
|
||||
rotation, extraction, compositing and gamma correction are available.
|
||||
|
||||
Most modern macOS, Windows and Linux systems running Node.js v10.16.0+
|
||||
Most modern macOS, Windows and Linux systems
|
||||
do not require any additional install or runtime dependencies.
|
||||
|
||||
## Documentation
|
||||
|
||||
Visit [sharp.pixelplumbing.com](https://sharp.pixelplumbing.com/) for complete
|
||||
[installation instructions](https://sharp.pixelplumbing.com/install),
|
||||
[API documentation](https://sharp.pixelplumbing.com/api-constructor),
|
||||
[benchmark tests](https://sharp.pixelplumbing.com/performance) and
|
||||
[changelog](https://sharp.pixelplumbing.com/changelog).
|
||||
|
||||
## Examples
|
||||
|
||||
```sh
|
||||
@@ -43,6 +55,7 @@ sharp(inputBuffer)
|
||||
sharp('input.jpg')
|
||||
.rotate()
|
||||
.resize(200)
|
||||
.jpeg({ mozjpeg: true })
|
||||
.toBuffer()
|
||||
.then( data => { ... })
|
||||
.catch( err => { ... });
|
||||
@@ -84,25 +97,14 @@ readableStream
|
||||
.pipe(writableStream);
|
||||
```
|
||||
|
||||
[](https://coveralls.io/r/lovell/sharp?branch=master)
|
||||
[](https://nodejs.org/dist/latest/docs/api/n-api.html#n_api_n_api_version_matrix)
|
||||
## Contributing
|
||||
|
||||
### Documentation
|
||||
|
||||
Visit [sharp.pixelplumbing.com](https://sharp.pixelplumbing.com/) for complete
|
||||
[installation instructions](https://sharp.pixelplumbing.com/install),
|
||||
[API documentation](https://sharp.pixelplumbing.com/api-constructor),
|
||||
[benchmark tests](https://sharp.pixelplumbing.com/performance) and
|
||||
[changelog](https://sharp.pixelplumbing.com/changelog).
|
||||
|
||||
### Contributing
|
||||
|
||||
A [guide for contributors](https://github.com/lovell/sharp/blob/master/.github/CONTRIBUTING.md)
|
||||
A [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md)
|
||||
covers reporting bugs, requesting features and submitting code changes.
|
||||
|
||||
### Licensing
|
||||
## Licensing
|
||||
|
||||
Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Lovell Fuller and contributors.
|
||||
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.
|
||||
|
||||
26
appveyor.yml
26
appveyor.yml
@@ -1,26 +0,0 @@
|
||||
os: Visual Studio 2017
|
||||
version: "{build}"
|
||||
build: off
|
||||
environment:
|
||||
matrix:
|
||||
- nodejs_version: "10"
|
||||
platform: x86
|
||||
- nodejs_version: "10"
|
||||
platform: x64
|
||||
- nodejs_version: "12"
|
||||
platform: x86
|
||||
prebuild_upload: ""
|
||||
- nodejs_version: "12"
|
||||
platform: x64
|
||||
prebuild_upload: ""
|
||||
- nodejs_version: "14.2.0"
|
||||
platform: x86
|
||||
prebuild_upload: ""
|
||||
- nodejs_version: "14"
|
||||
platform: x64
|
||||
prebuild_upload: ""
|
||||
install:
|
||||
- ps: Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version) $env:platform
|
||||
- npm install
|
||||
test_script:
|
||||
- npm test
|
||||
232
binding.gyp
232
binding.gyp
@@ -1,232 +0,0 @@
|
||||
{
|
||||
'variables': {
|
||||
'vips_version': '<!(node -p "require(\'./lib/libvips\').minimumLibvipsVersion")',
|
||||
'sharp_vendor_dir': '<(module_root_dir)/vendor/<(vips_version)'
|
||||
},
|
||||
'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/VError.cpp',
|
||||
'src/libvips/cplusplus/VConnection.cpp',
|
||||
'src/libvips/cplusplus/VInterpolate.cpp',
|
||||
'src/libvips/cplusplus/VImage.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,
|
||||
'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',
|
||||
'defines': [
|
||||
'NAPI_VERSION=3'
|
||||
],
|
||||
'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")',
|
||||
],
|
||||
'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',
|
||||
'libvips.42.dylib'
|
||||
]
|
||||
},
|
||||
'xcode_settings': {
|
||||
'OTHER_LDFLAGS': [
|
||||
# Ensure runtime linking is relative to sharp.node
|
||||
'-Wl,-rpath,\'@loader_path/../../vendor/<(vips_version)/lib\''
|
||||
]
|
||||
}
|
||||
}],
|
||||
['OS == "linux"', {
|
||||
'defines': [
|
||||
'_GLIBCXX_USE_CXX11_ABI=0'
|
||||
],
|
||||
'link_settings': {
|
||||
'library_dirs': ['<(sharp_vendor_dir)/lib'],
|
||||
'libraries': [
|
||||
'-l:libvips-cpp.so.42',
|
||||
'-l:libvips.so.42'
|
||||
],
|
||||
'ldflags': [
|
||||
# Ensure runtime linking is relative to sharp.node
|
||||
'-Wl,-s -Wl,--disable-new-dtags -Wl,-rpath=\'$$ORIGIN/../../vendor/<(vips_version)/lib\''
|
||||
]
|
||||
}
|
||||
}]
|
||||
]
|
||||
}]
|
||||
],
|
||||
'cflags_cc': [
|
||||
'-std=c++0x',
|
||||
'-fexceptions',
|
||||
'-Wall',
|
||||
'-O3'
|
||||
],
|
||||
'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',
|
||||
'-O3'
|
||||
]
|
||||
},
|
||||
'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,
|
||||
'WholeProgramOptimization': 'true'
|
||||
},
|
||||
'VCLibrarianTool': {
|
||||
'AdditionalOptions': [
|
||||
'/LTCG:INCREMENTAL'
|
||||
]
|
||||
},
|
||||
'VCLinkerTool': {
|
||||
'ImageHasSafeExceptionHandlers': 'false',
|
||||
'OptimizeReferences': 2,
|
||||
'EnableCOMDATFolding': 2,
|
||||
'LinkIncremental': 1,
|
||||
'AdditionalOptions': [
|
||||
'/LTCG:INCREMENTAL'
|
||||
]
|
||||
}
|
||||
},
|
||||
'msvs_disabled_warnings': [
|
||||
4275
|
||||
]
|
||||
}]
|
||||
]
|
||||
}
|
||||
},
|
||||
}]
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
# sharp
|
||||
|
||||
<img src="https://cdn.jsdelivr.net/gh/lovell/sharp@master/docs/image/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right">
|
||||
<img src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right">
|
||||
|
||||
The typical use case for this high speed Node.js module
|
||||
The typical use case for this high speed Node-API module
|
||||
is to convert large images in common formats to
|
||||
smaller, web-friendly JPEG, PNG and WebP 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
|
||||
quickest ImageMagick and GraphicsMagick settings
|
||||
@@ -16,14 +20,14 @@ Lanczos resampling ensures quality is not sacrificed for speed.
|
||||
As well as image resizing, operations such as
|
||||
rotation, extraction, compositing and gamma correction are available.
|
||||
|
||||
Most modern macOS, Windows and Linux systems running Node.js v10.16.0+
|
||||
Most modern macOS, Windows and Linux systems
|
||||
do not require any additional install or runtime dependencies.
|
||||
|
||||
### Formats
|
||||
|
||||
This module supports reading JPEG, PNG, WebP, TIFF, GIF and SVG images.
|
||||
This module supports reading JPEG, PNG, WebP, GIF, AVIF, TIFF and SVG images.
|
||||
|
||||
Output images can be in JPEG, PNG, WebP and TIFF formats as well as uncompressed raw pixel data.
|
||||
Output images can be in JPEG, PNG, WebP, GIF, AVIF and TIFF formats as well as uncompressed raw pixel data.
|
||||
|
||||
Streams, Buffer objects and the filesystem can be used for input and output.
|
||||
|
||||
@@ -50,6 +54,10 @@ no child processes are spawned and Promises/async/await are supported.
|
||||
|
||||
### Optimal
|
||||
|
||||
The features of `mozjpeg` and `pngquant` can be used
|
||||
to optimise the file size of JPEG and PNG images respectively,
|
||||
without having to invoke separate `imagemin` processes.
|
||||
|
||||
Huffman tables are optimised when generating JPEG output images
|
||||
without having to use separate command line tools like
|
||||
[jpegoptim](https://github.com/tjko/jpegoptim) and
|
||||
@@ -59,14 +67,18 @@ PNG filtering is disabled by default,
|
||||
which for diagrams and line art often produces the same result
|
||||
as [pngcrush](https://pmt.sourceforge.io/pngcrush/).
|
||||
|
||||
The file size of animated GIF output is optimised
|
||||
without having to use separate command line tools such as
|
||||
[gifsicle](https://www.lcdf.org/gifsicle/).
|
||||
|
||||
### Contributing
|
||||
|
||||
A [guide for contributors](https://github.com/lovell/sharp/blob/master/.github/CONTRIBUTING.md)
|
||||
A [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md)
|
||||
covers reporting bugs, requesting features and submitting code changes.
|
||||
|
||||
### Licensing
|
||||
|
||||
Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Lovell Fuller and contributors.
|
||||
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.
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
|
||||
|
||||
## removeAlpha
|
||||
> removeAlpha() ⇒ <code>Sharp</code>
|
||||
|
||||
Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel.
|
||||
|
||||
### Examples
|
||||
See also [flatten](/api-operation#flatten).
|
||||
|
||||
```javascript
|
||||
|
||||
**Example**
|
||||
```js
|
||||
sharp('rgba.png')
|
||||
.removeAlpha()
|
||||
.toFile('rgb.png', function(err, info) {
|
||||
@@ -14,86 +15,117 @@ sharp('rgba.png')
|
||||
});
|
||||
```
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## ensureAlpha
|
||||
> ensureAlpha([alpha]) ⇒ <code>Sharp</code>
|
||||
|
||||
Ensure alpha channel, if missing. The added alpha channel will be fully opaque. This is a no-op if the image already has an alpha channel.
|
||||
Ensure the output image has an alpha transparency channel.
|
||||
If missing, the added alpha channel will have the specified
|
||||
transparency level, defaulting to fully-opaque (1).
|
||||
This is a no-op if the image already has an alpha channel.
|
||||
|
||||
### Examples
|
||||
|
||||
```javascript
|
||||
sharp('rgb.jpg')
|
||||
**Throws**:
|
||||
|
||||
- <code>Error</code> Invalid alpha transparency level
|
||||
|
||||
**Since**: 0.21.2
|
||||
|
||||
| Param | Type | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| [alpha] | <code>number</code> | <code>1</code> | alpha transparency level (0=fully-transparent, 1=fully-opaque) |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
// rgba.png will be a 4 channel image with a fully-opaque alpha channel
|
||||
await sharp('rgb.jpg')
|
||||
.ensureAlpha()
|
||||
.toFile('rgba.png', function(err, info) {
|
||||
// rgba.png is a 4 channel image with a fully opaque alpha channel
|
||||
});
|
||||
.toFile('rgba.png')
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
// rgba is a 4 channel image with a fully-transparent alpha channel
|
||||
const rgba = await sharp(rgb)
|
||||
.ensureAlpha(0)
|
||||
.toBuffer();
|
||||
```
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
**Meta**
|
||||
|
||||
- **since**: 0.21.2
|
||||
|
||||
## extractChannel
|
||||
> extractChannel(channel) ⇒ <code>Sharp</code>
|
||||
|
||||
Extract a single channel from a multi-channel image.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `channel` **([number][1] \| [string][2])** zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`.
|
||||
**Throws**:
|
||||
|
||||
### Examples
|
||||
- <code>Error</code> Invalid channel
|
||||
|
||||
```javascript
|
||||
sharp(input)
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| channel | <code>number</code> \| <code>string</code> | zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`. |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
// green.jpg is a greyscale image containing the green channel of the input
|
||||
await sharp(input)
|
||||
.extractChannel('green')
|
||||
.toColourspace('b-w')
|
||||
.toFile('green.jpg', function(err, info) {
|
||||
// info.channels === 1
|
||||
// green.jpg is a greyscale image containing the green channel of the input
|
||||
});
|
||||
.toFile('green.jpg');
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
// red1 is the red value of the first pixel, red2 the second pixel etc.
|
||||
const [red1, red2, ...] = await sharp(input)
|
||||
.extractChannel(0)
|
||||
.raw()
|
||||
.toBuffer();
|
||||
```
|
||||
|
||||
- Throws **[Error][3]** Invalid channel
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## joinChannel
|
||||
> joinChannel(images, options) ⇒ <code>Sharp</code>
|
||||
|
||||
Join one or more channels to the image.
|
||||
The meaning of the added channels depends on the output colourspace, set with `toColourspace()`.
|
||||
By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.
|
||||
Channel ordering follows vips convention:
|
||||
- sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha.
|
||||
- CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha.
|
||||
|
||||
- sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha.
|
||||
- CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha.
|
||||
|
||||
Buffers may be any of the image formats supported by sharp: JPEG, PNG, WebP, GIF, SVG, TIFF or raw pixel image data.
|
||||
Buffers may be any of the image formats supported by sharp.
|
||||
For raw pixel input, the `options` object should contain a `raw` attribute, which follows the format of the attribute of the same name in the `sharp()` constructor.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `images` **([Array][4]<([string][2] \| [Buffer][5])> | [string][2] \| [Buffer][5])** one or more images (file paths, Buffers).
|
||||
- `options` **[Object][6]** image options, see `sharp()` constructor.
|
||||
**Throws**:
|
||||
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
|
||||
- Throws **[Error][3]** 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. |
|
||||
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## bandbool
|
||||
> bandbool(boolOp) ⇒ <code>Sharp</code>
|
||||
|
||||
Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `boolOp` **[string][2]** 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')
|
||||
.bandbool(sharp.bool.and)
|
||||
.toFile('1-channel-output.png', function (err, info) {
|
||||
@@ -101,20 +133,4 @@ sharp('3-channel-rgb-input.png')
|
||||
// If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]`
|
||||
// then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`.
|
||||
});
|
||||
```
|
||||
|
||||
- Throws **[Error][3]** Invalid parameters
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
|
||||
|
||||
[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
|
||||
|
||||
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
|
||||
|
||||
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
|
||||
|
||||
[5]: https://nodejs.org/api/buffer.html
|
||||
|
||||
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
|
||||
```
|
||||
@@ -1,20 +1,29 @@
|
||||
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
|
||||
|
||||
## tint
|
||||
> tint(tint) ⇒ <code>Sharp</code>
|
||||
|
||||
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.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `rgb` **([string][1] \| [Object][2])** parsed by the [color][3] module to extract chroma values.
|
||||
**Throws**:
|
||||
|
||||
- <code>Error</code> Invalid parameter
|
||||
|
||||
|
||||
- Throws **[Error][4]** 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();
|
||||
```
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## 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.
|
||||
@@ -23,57 +32,116 @@ 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`)
|
||||
|
||||
Returns **Sharp**
|
||||
| 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`.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `grayscale` **[Boolean][5]** (optional, default `true`)
|
||||
|
||||
Returns **Sharp**
|
||||
| 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).
|
||||
|
||||
This feature is experimental and has not yet been fully-tested with all operations.
|
||||
|
||||
|
||||
**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.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `colourspace` **[string][1]?** output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...][6]
|
||||
**Throws**:
|
||||
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
|
||||
- Throws **[Error][4]** 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')
|
||||
```
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## toColorspace
|
||||
> toColorspace([colorspace]) ⇒ <code>Sharp</code>
|
||||
|
||||
Alternative spelling of `toColourspace`.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `colorspace` **[string][1]?** output colorspace.
|
||||
**Throws**:
|
||||
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
|
||||
- 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]: https://github.com/libvips/libvips/blob/master/libvips/iofuncs/enumtypes.c#L568
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| [colorspace] | <code>string</code> | output colorspace. |
|
||||
@@ -1,12 +1,14 @@
|
||||
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
|
||||
|
||||
## 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`.
|
||||
|
||||
Any resize, rotate or extract 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`,
|
||||
@@ -14,33 +16,70 @@ The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`,
|
||||
`hard-light`, `soft-light`, `difference`, `exclusion`.
|
||||
|
||||
More information about blend modes can be found at
|
||||
[https://libvips.github.io/libvips/API/current/libvips-conversion.html#VipsBlendMode][1]
|
||||
and [https://www.cairographics.org/operators/][2]
|
||||
https://www.libvips.org/API/current/libvips-conversion.html#VipsBlendMode
|
||||
and https://www.cairographics.org/operators/
|
||||
|
||||
### 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[].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]?**
|
||||
**Throws**:
|
||||
|
||||
### Examples
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
```javascript
|
||||
**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[].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)
|
||||
@@ -55,32 +94,4 @@ sharp('input.png')
|
||||
// onto orange background, composited with overlay.png with SE gravity,
|
||||
// sharpened, with metadata, 90% quality WebP image data. Phew!
|
||||
});
|
||||
```
|
||||
|
||||
- Throws **[Error][10]** Invalid parameters
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
**Meta**
|
||||
|
||||
- **since**: 0.22.0
|
||||
|
||||
[1]: https://libvips.github.io/libvips/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]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
|
||||
```
|
||||
@@ -1,48 +1,75 @@
|
||||
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
|
||||
|
||||
## 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 or TIFF format image data can be streamed out from this object.
|
||||
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.
|
||||
Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.
|
||||
|
||||
### Parameters
|
||||
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`.
|
||||
|
||||
- `input` **([Buffer][2] \| [string][3])?** if present, can be
|
||||
a Buffer containing JPEG, PNG, WebP, GIF, SVG, TIFF or raw pixel image data, or
|
||||
a String containing the filesystem path to an JPEG, PNG, WebP, GIF, SVG or TIFF image file.
|
||||
JPEG, PNG, WebP, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present.
|
||||
- `options` **[Object][4]?** if present, is an Object with optional attributes.
|
||||
- `options.failOnError` **[boolean][5]** by default halt processing and raise an error when loading invalid images.
|
||||
Set this flag to `false` if you'd rather apply a "best effort" to decode images, even if the data is corrupt or invalid. (optional, default `true`)
|
||||
- `options.limitInputPixels` **([number][6] \| [boolean][5])** Do not process input images where the number of pixels
|
||||
(width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted.
|
||||
An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). (optional, default `268402689`)
|
||||
- `options.sequentialRead` **[boolean][5]** 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][6]** number representing the DPI for vector images. (optional, default `72`)
|
||||
- `options.pages` **[number][6]** number of pages to extract for multi-page input (GIF, TIFF, PDF), use -1 for all pages. (optional, default `1`)
|
||||
- `options.page` **[number][6]** page number to start extracting from for multi-page input (GIF, TIFF, PDF), zero based. (optional, default `0`)
|
||||
- `options.level` **[number][6]** level to extract from a multi-level input (OpenSlide), zero based. (optional, default `0`)
|
||||
- `options.animated` **[boolean][5]** Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). (optional, default `false`)
|
||||
- `options.raw` **[Object][4]?** describes raw pixel input image data. See `raw()` for pixel ordering.
|
||||
- `options.raw.width` **[number][6]?**
|
||||
- `options.raw.height` **[number][6]?**
|
||||
- `options.raw.channels` **[number][6]?** 1-4
|
||||
- `options.create` **[Object][4]?** describes a new image to be created.
|
||||
- `options.create.width` **[number][6]?**
|
||||
- `options.create.height` **[number][6]?**
|
||||
- `options.create.channels` **[number][6]?** 3-4
|
||||
- `options.create.background` **([string][3] \| [Object][4])?** parsed by the [color][7] module to extract values for red, green, blue and alpha.
|
||||
**Throws**:
|
||||
|
||||
### Examples
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
```javascript
|
||||
|
||||
| Param | Type | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| [input] | <code>Buffer</code> \| <code>ArrayBuffer</code> \| <code>Uint8Array</code> \| <code>Uint8ClampedArray</code> \| <code>Int8Array</code> \| <code>Uint16Array</code> \| <code>Int16Array</code> \| <code>Uint32Array</code> \| <code>Int32Array</code> \| <code>Float32Array</code> \| <code>Float64Array</code> \| <code>string</code> | | if present, can be a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or a TypedArray containing raw pixel image data, or a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. |
|
||||
| [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.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.subifd] | <code>number</code> | <code>-1</code> | subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. |
|
||||
| [options.level] | <code>number</code> | <code>0</code> | level to extract from a multi-level input (OpenSlide), zero based. |
|
||||
| [options.animated] | <code>boolean</code> | <code>false</code> | Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`. |
|
||||
| [options.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.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.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> | | mean of pixels in generated noise. |
|
||||
| [options.create.noise.sigma] | <code>number</code> | | standard deviation of pixels in 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'. |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
sharp('input.jpg')
|
||||
.resize(300, 200)
|
||||
.toFile('output.jpg', function(err) {
|
||||
@@ -50,22 +77,24 @@ sharp('input.jpg')
|
||||
// containing a scaled and cropped version of input.jpg
|
||||
});
|
||||
```
|
||||
|
||||
```javascript
|
||||
// Read image data from readableStream,
|
||||
**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
|
||||
var transformer = sharp()
|
||||
const { body } = fetch('https://...');
|
||||
const readableStream = Readable.fromWeb(body);
|
||||
const transformer = sharp()
|
||||
.resize(300)
|
||||
.on('info', function(info) {
|
||||
console.log('Image height is ' + info.height);
|
||||
.on('info', ({ height }) => {
|
||||
console.log(`Image height is ${height}`);
|
||||
});
|
||||
readableStream.pipe(transformer).pipe(writableStream);
|
||||
```
|
||||
|
||||
```javascript
|
||||
// Create a blank 300x200 PNG image of semi-transluent red pixels
|
||||
**Example**
|
||||
```js
|
||||
// Create a blank 300x200 PNG image of semi-translucent red pixels
|
||||
sharp({
|
||||
create: {
|
||||
width: 300,
|
||||
@@ -78,25 +107,77 @@ sharp({
|
||||
.toBuffer()
|
||||
.then( ... );
|
||||
```
|
||||
|
||||
```javascript
|
||||
**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');
|
||||
```
|
||||
|
||||
- Throws **[Error][8]** Invalid parameters
|
||||
|
||||
Returns **[Sharp][9]**
|
||||
|
||||
## 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.
|
||||
|
||||
### Examples
|
||||
|
||||
```javascript
|
||||
**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);
|
||||
@@ -104,15 +185,13 @@ readableStream.pipe(pipeline);
|
||||
// firstWritableStream receives auto-rotated, resized readableStream
|
||||
// secondWritableStream receives auto-rotated, extracted region of readableStream
|
||||
```
|
||||
|
||||
```javascript
|
||||
**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({
|
||||
failOnError: false
|
||||
});
|
||||
const sharpStream = sharp({ failOn: 'none' });
|
||||
|
||||
const promises = [];
|
||||
|
||||
@@ -139,7 +218,7 @@ promises.push(
|
||||
.toFile("optimized-500.webp")
|
||||
);
|
||||
|
||||
// https://github.com/sindresorhus/got#gotstreamurl-options
|
||||
// https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md
|
||||
got.stream("https://www.example.com/some-file.jpg").pipe(sharpStream);
|
||||
|
||||
Promise.all(promises)
|
||||
@@ -152,24 +231,4 @@ Promise.all(promises)
|
||||
fs.unlinkSync("optimized-500.webp");
|
||||
} catch (e) {}
|
||||
});
|
||||
```
|
||||
|
||||
Returns **[Sharp][9]**
|
||||
|
||||
[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/String
|
||||
|
||||
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
|
||||
|
||||
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
|
||||
|
||||
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
|
||||
|
||||
[7]: https://www.npmjs.org/package/color
|
||||
|
||||
[8]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
|
||||
|
||||
[9]: #sharp
|
||||
```
|
||||
@@ -1,42 +1,60 @@
|
||||
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
|
||||
|
||||
## 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).
|
||||
|
||||
Fast access to (uncached) image metadata without decoding any compressed image data.
|
||||
A `Promise` is returned when `callback` is not provided.
|
||||
|
||||
- `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg`
|
||||
- `size`: Total size of image in bytes, for Stream and Buffer input only
|
||||
- `width`: Number of pixels wide (EXIF orientation is not taken into consideration)
|
||||
- `height`: Number of pixels high (EXIF orientation is not taken into consideration)
|
||||
- `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...][1]
|
||||
- `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK
|
||||
- `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...][2]
|
||||
- `density`: Number of pixels per inch (DPI), if present
|
||||
- `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK
|
||||
- `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan
|
||||
- `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP
|
||||
- `pageHeight`: Number of pixels high each page in a multi-page image will be.
|
||||
- `loop`: Number of times to loop an animated image, zero refers to a continuous loop.
|
||||
- `delay`: Delay in ms between each page in an animated image, provided as an array of integers.
|
||||
- `pagePrimary`: Number of the primary page in a HEIF image
|
||||
- `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide
|
||||
- `hasProfile`: Boolean indicating the presence of an embedded ICC profile
|
||||
- `hasAlpha`: Boolean indicating the presence of an alpha transparency channel
|
||||
- `orientation`: Number value of the EXIF Orientation header, if present
|
||||
- `exif`: Buffer containing raw EXIF data, if present
|
||||
- `icc`: Buffer containing raw [ICC][3] profile data, if present
|
||||
- `iptc`: Buffer containing raw IPTC data, if present
|
||||
- `xmp`: Buffer containing raw XMP data, if present
|
||||
- `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present
|
||||
- `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg`
|
||||
- `size`: Total size of image in bytes, for Stream and Buffer input only
|
||||
- `width`: Number of pixels wide (EXIF orientation is not taken into consideration, 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
|
||||
- `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.
|
||||
- `paletteBitDepth`: Bit depth of palette-based image (GIF, PNG).
|
||||
- `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](https://www.npmjs.com/package/icc) profile data, if present
|
||||
- `iptc`: Buffer containing raw IPTC data, if present
|
||||
- `xmp`: Buffer containing raw XMP data, if present
|
||||
- `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present
|
||||
- `formatMagick`: String containing format for images loaded via *magick
|
||||
|
||||
### Parameters
|
||||
|
||||
- `callback` **[Function][4]?** called with the arguments `(err, metadata)`
|
||||
|
||||
### Examples
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| [callback] | <code>function</code> | called with the arguments `(err, metadata)` |
|
||||
|
||||
```javascript
|
||||
**Example**
|
||||
```js
|
||||
const metadata = await sharp(input).metadata();
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
const image = sharp(inputJpg);
|
||||
image
|
||||
.metadata()
|
||||
@@ -50,37 +68,53 @@ image
|
||||
// data contains a WebP image half the width and height of the original JPEG
|
||||
});
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
// 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][5]<[Object][6]> | Sharp)**
|
||||
|
||||
## 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 (experimental)
|
||||
- `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any (experimental)
|
||||
- `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram (experimental)
|
||||
- `channels`: Array of channel statistics for each channel in the image. Each channel statistic contains
|
||||
- `min` (minimum value in the channel)
|
||||
- `max` (maximum value in the channel)
|
||||
- `sum` (sum of all values in a channel)
|
||||
- `squaresSum` (sum of squared values in a channel)
|
||||
- `mean` (mean of the values in a channel)
|
||||
- `stdev` (standard deviation for the values in a channel)
|
||||
- `minX` (x-coordinate of one of the pixel where the minimum lies)
|
||||
- `minY` (y-coordinate of one of the pixel where the minimum lies)
|
||||
- `maxX` (x-coordinate of one of the pixel where the maximum lies)
|
||||
- `maxY` (y-coordinate of one of the pixel where the maximum lies)
|
||||
- `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque.
|
||||
- `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any.
|
||||
- `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.
|
||||
|
||||
### Parameters
|
||||
**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).
|
||||
|
||||
- `callback` **[Function][4]?** called with the arguments `(err, stats)`
|
||||
|
||||
### Examples
|
||||
|
||||
```javascript
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| [callback] | <code>function</code> | called with the arguments `(err, stats)` |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
const image = sharp(inputJpg);
|
||||
image
|
||||
.stats()
|
||||
@@ -88,22 +122,16 @@ image
|
||||
// stats contains the channel-wise statistics array and the isOpaque value
|
||||
});
|
||||
```
|
||||
|
||||
```javascript
|
||||
**Example**
|
||||
```js
|
||||
const { entropy, sharpness, dominant } = await sharp(input).stats();
|
||||
const { r, g, b } = dominant;
|
||||
```
|
||||
|
||||
Returns **[Promise][5]<[Object][6]>**
|
||||
|
||||
[1]: https://libvips.github.io/libvips/API/current/VipsImage.html#VipsInterpretation
|
||||
|
||||
[2]: https://libvips.github.io/libvips/API/current/VipsImage.html#VipsBandFormat
|
||||
|
||||
[3]: https://www.npmjs.com/package/icc
|
||||
|
||||
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function
|
||||
|
||||
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise
|
||||
|
||||
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
|
||||
**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();
|
||||
```
|
||||
@@ -1,12 +1,11 @@
|
||||
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
|
||||
|
||||
## rotate
|
||||
> rotate([angle], [options]) ⇒ <code>Sharp</code>
|
||||
|
||||
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.
|
||||
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.
|
||||
@@ -14,20 +13,30 @@ 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.
|
||||
The use of `rotate` without an angle will remove the EXIF `Orientation` tag, if any.
|
||||
|
||||
Method order is important when both rotating and extracting regions,
|
||||
for example `rotate(x).extract(y)` will produce a different result to `extract(y).rotate(x)`.
|
||||
Only one rotation can occur per pipeline.
|
||||
Previous calls to `rotate` in the same pipeline will be ignored.
|
||||
|
||||
### Parameters
|
||||
Multi-page images can only be rotated by 180 degrees.
|
||||
|
||||
- `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"`)
|
||||
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)`.
|
||||
|
||||
### Examples
|
||||
|
||||
```javascript
|
||||
**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 pipeline = sharp()
|
||||
.rotate()
|
||||
.resize(null, 200)
|
||||
@@ -38,92 +47,273 @@ const pipeline = sharp()
|
||||
});
|
||||
readableStream.pipe(pipeline);
|
||||
```
|
||||
**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();
|
||||
```
|
||||
|
||||
- Throws **[Error][5]** Invalid parameters
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## flip
|
||||
> flip([flip]) ⇒ <code>Sharp</code>
|
||||
|
||||
Flip the image about the vertical Y axis. This always occurs after rotation, if any.
|
||||
The use of `flip` implies the removal of the EXIF `Orientation` tag, if any.
|
||||
Mirror the image vertically (up-down) about the x-axis.
|
||||
This always occurs before rotation, if any.
|
||||
|
||||
### Parameters
|
||||
This operation does not work correctly with multi-page images.
|
||||
|
||||
- `flip` **[Boolean][6]** (optional, default `true`)
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
| 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>
|
||||
|
||||
Flop the image about the horizontal X axis. This always occurs after rotation, if any.
|
||||
The use of `flop` implies the removal of the EXIF `Orientation` tag, if any.
|
||||
Mirror the image horizontally (left-right) about the y-axis.
|
||||
This always occurs before rotation, if any.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `flop` **[Boolean][6]** (optional, default `true`)
|
||||
|
||||
Returns **Sharp**
|
||||
| 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 color 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.
|
||||
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.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `sigma` **[number][1]?** the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
|
||||
- `flat` **[number][1]** the level of sharpening to apply to "flat" areas. (optional, default `1.0`)
|
||||
- `jagged` **[number][1]** the level of sharpening to apply to "jagged" areas. (optional, default `2.0`)
|
||||
See [libvips sharpen](https://www.libvips.org/API/current/libvips-convolution.html#vips-sharpen) operation.
|
||||
|
||||
|
||||
- Throws **[Error][5]** Invalid parameters
|
||||
**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();
|
||||
```
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## median
|
||||
> median([size]) ⇒ <code>Sharp</code>
|
||||
|
||||
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`)
|
||||
**Throws**:
|
||||
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
|
||||
- Throws **[Error][5]** 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();
|
||||
```
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## blur
|
||||
> blur([sigma]) ⇒ <code>Sharp</code>
|
||||
|
||||
Blur the image.
|
||||
When used without parameters, performs a fast, mild blur of the output 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`.
|
||||
**Throws**:
|
||||
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
|
||||
- Throws **[Error][5]** Invalid parameters
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| [sigma] | <code>number</code> | a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
const boxBlurred = await sharp(input)
|
||||
.blur()
|
||||
.toBuffer();
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
const gaussianBlurred = await sharp(input)
|
||||
.blur(5)
|
||||
.toBuffer();
|
||||
```
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## flatten
|
||||
> flatten([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Merge alpha transparency channel, if any, with a background.
|
||||
Merge alpha transparency channel, if any, with a background, then remove the alpha channel.
|
||||
|
||||
### Parameters
|
||||
See also [removeAlpha](/api-channel#removealpha).
|
||||
|
||||
- `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}`)
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
| 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`.
|
||||
@@ -133,62 +323,153 @@ 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**:
|
||||
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
|
||||
- Throws **[Error][5]** 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`) |
|
||||
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## negate
|
||||
> negate([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Produce the "negative" of the image.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `negate` **[Boolean][6]** (optional, default `true`)
|
||||
|
||||
Returns **Sharp**
|
||||
| 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 the full dynamic range.
|
||||
Enhance output image contrast by stretching its luminance to cover a full dynamic range.
|
||||
|
||||
### Parameters
|
||||
Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes.
|
||||
|
||||
- `normalise` **[Boolean][6]** (optional, default `true`)
|
||||
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();
|
||||
```
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## normalize
|
||||
> normalize([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Alternative spelling of normalise.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `normalize` **[Boolean][6]** (optional, default `true`)
|
||||
|
||||
Returns **Sharp**
|
||||
| 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.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `kernel` **[Object][2]**
|
||||
- `kernel.width` **[number][1]** width of the kernel in pixels.
|
||||
- `kernel.height` **[number][1]** width of the kernel in pixels.
|
||||
- `kernel.kernel` **[Array][7]<[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`)
|
||||
**Throws**:
|
||||
|
||||
### Examples
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
```javascript
|
||||
|
||||
| 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,
|
||||
@@ -202,73 +483,107 @@ sharp(input)
|
||||
});
|
||||
```
|
||||
|
||||
- Throws **[Error][5]** Invalid parameters
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## threshold
|
||||
> threshold([threshold], [options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Any pixel value greather 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`)
|
||||
Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0.
|
||||
|
||||
|
||||
- Throws **[Error][5]** Invalid parameters
|
||||
**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. |
|
||||
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## 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.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `operand` **([Buffer][8] \| [string][3])** Buffer containing image data or string containing the path to an image file.
|
||||
- `operator` **[string][3]** one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.
|
||||
- `options` **[Object][2]?**
|
||||
- `options.raw` **[Object][2]?** describes operand when using raw pixel data.
|
||||
- `options.raw.width` **[number][1]?**
|
||||
- `options.raw.height` **[number][1]?**
|
||||
- `options.raw.channels` **[number][1]?**
|
||||
**Throws**:
|
||||
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
|
||||
- Throws **[Error][5]** 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> | |
|
||||
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## linear
|
||||
> linear([a], [b]) ⇒ <code>Sharp</code>
|
||||
|
||||
Apply the linear formula a \* input + b to the image (levels adjustment)
|
||||
Apply the linear formula `a` * input + `b` to the image to adjust image levels.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `a` **[number][1]** multiplier (optional, default `1.0`)
|
||||
- `b` **[number][1]** offset (optional, default `0.0`)
|
||||
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 **[Error][5]** Invalid parameters
|
||||
**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();
|
||||
```
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## recomb
|
||||
> recomb(inputMatrix) ⇒ <code>Sharp</code>
|
||||
|
||||
Recomb the image with the specified matrix.
|
||||
Recombine the image with the specified matrix.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `inputMatrix` **[Array][7]<[Array][7]<[number][1]>>** 3x3 Recombination matrix
|
||||
**Throws**:
|
||||
|
||||
### Examples
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
```javascript
|
||||
**Since**: 0.21.1
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| inputMatrix | <code>Array.<Array.<number>></code> | 3x3 Recombination matrix |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
sharp(input)
|
||||
.recomb([
|
||||
[0.3588, 0.7044, 0.1368],
|
||||
@@ -277,70 +592,65 @@ sharp(input)
|
||||
])
|
||||
.raw()
|
||||
.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
|
||||
});
|
||||
```
|
||||
|
||||
- Throws **[Error][5]** Invalid parameters
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
**Meta**
|
||||
|
||||
- **since**: 0.21.1
|
||||
|
||||
## modulate
|
||||
> modulate([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Transforms the image using brightness, saturation and hue rotation.
|
||||
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
|
||||
**Since**: 0.22.1
|
||||
|
||||
### Examples
|
||||
| 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 |
|
||||
|
||||
```javascript
|
||||
sharp(input)
|
||||
**Example**
|
||||
```js
|
||||
// increase brightness by a factor of 2
|
||||
const output = await sharp(input)
|
||||
.modulate({
|
||||
brightness: 2 // increase lightness by a factor of 2
|
||||
});
|
||||
|
||||
sharp(input)
|
||||
brightness: 2
|
||||
})
|
||||
.toBuffer();
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
// hue-rotate by 180 degrees
|
||||
const output = await sharp(input)
|
||||
.modulate({
|
||||
hue: 180 // hue-rotate by 180 degrees
|
||||
});
|
||||
|
||||
// decreate brightness and saturation while also hue-rotating by 90 degrees
|
||||
sharp(input)
|
||||
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
|
||||
});
|
||||
```
|
||||
|
||||
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://nodejs.org/api/buffer.html
|
||||
hue: 90,
|
||||
})
|
||||
.toBuffer();
|
||||
```
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,58 +1,64 @@
|
||||
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
|
||||
|
||||
## 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.
|
||||
|
||||
- `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](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property.
|
||||
|
||||
Some of these values are based on the [object-fit][1] CSS property.
|
||||
<img alt="Examples of various values for the fit property when resizing" width="100%" style="aspect-ratio: 998/243" src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/api-resize-fit.svg">
|
||||
|
||||
When using a `fit` of `cover` or `contain`, the default **position** is `centre`. Other options are:
|
||||
When using a **fit** of `cover` or `contain`, the default **position** is `centre`. Other options are:
|
||||
- `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`.
|
||||
- `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`.
|
||||
- `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy.
|
||||
|
||||
- `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`.
|
||||
- `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`.
|
||||
- `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy.
|
||||
|
||||
Some of these values are based on the [object-position][2] CSS property.
|
||||
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
|
||||
then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.
|
||||
|
||||
- `entropy`: focus on the region with the highest [Shannon entropy][3].
|
||||
- `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
|
||||
- `entropy`: focus on the region with the highest [Shannon entropy](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 interpolation kernels are:
|
||||
- `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation).
|
||||
- `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).
|
||||
|
||||
- `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 using a `fit` of `contain`, parsed by the [color][11] module, defaults to black without transparency. (optional, default `{r:0,g:0,b:0,alpha:1}`)
|
||||
- `options.kernel` **[String][10]** the kernel to use for image reduction. (optional, default `'lanczos3'`)
|
||||
- `options.withoutEnlargement` **[Boolean][12]** do not enlarge if the width _or_ height are already less than the specified dimensions, equivalent to GraphicsMagick's `>` geometry option. (optional, default `false`)
|
||||
- `options.fastShrinkOnLoad` **[Boolean][12]** take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern on some images. (optional, default `true`)
|
||||
**Throws**:
|
||||
|
||||
### Examples
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
```javascript
|
||||
|
||||
| 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. 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()
|
||||
@@ -60,8 +66,8 @@ sharp(input)
|
||||
// 100 pixels wide, auto-scaled height
|
||||
});
|
||||
```
|
||||
|
||||
```javascript
|
||||
**Example**
|
||||
```js
|
||||
sharp(input)
|
||||
.resize({ height: 100 })
|
||||
.toBuffer()
|
||||
@@ -69,8 +75,8 @@ sharp(input)
|
||||
// 100 pixels high, auto-scaled width
|
||||
});
|
||||
```
|
||||
|
||||
```javascript
|
||||
**Example**
|
||||
```js
|
||||
sharp(input)
|
||||
.resize(200, 300, {
|
||||
kernel: sharp.kernel.nearest,
|
||||
@@ -85,8 +91,8 @@ sharp(input)
|
||||
// contained within the north-east corner of a semi-transparent white canvas
|
||||
});
|
||||
```
|
||||
|
||||
```javascript
|
||||
**Example**
|
||||
```js
|
||||
const transformer = sharp()
|
||||
.resize({
|
||||
width: 200,
|
||||
@@ -100,8 +106,8 @@ readableStream
|
||||
.pipe(transformer)
|
||||
.pipe(writableStream);
|
||||
```
|
||||
|
||||
```javascript
|
||||
**Example**
|
||||
```js
|
||||
sharp(input)
|
||||
.resize(200, 200, {
|
||||
fit: sharp.fit.inside,
|
||||
@@ -115,8 +121,23 @@ sharp(input)
|
||||
// and no larger than the input image
|
||||
});
|
||||
```
|
||||
|
||||
```javascript
|
||||
**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)
|
||||
@@ -125,27 +146,32 @@ const scaleByHalf = await sharp(input)
|
||||
);
|
||||
```
|
||||
|
||||
- Throws **[Error][13]** Invalid parameters
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## extend
|
||||
> extend(extend) ⇒ <code>Sharp</code>
|
||||
|
||||
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.
|
||||
|
||||
### 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]?**
|
||||
- `extend.left` **[number][8]?**
|
||||
- `extend.bottom` **[number][8]?**
|
||||
- `extend.right` **[number][8]?**
|
||||
- `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}`)
|
||||
**Throws**:
|
||||
|
||||
### Examples
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
```javascript
|
||||
|
||||
| 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)
|
||||
@@ -159,38 +185,61 @@ sharp(input)
|
||||
})
|
||||
...
|
||||
```
|
||||
**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'
|
||||
})
|
||||
...
|
||||
```
|
||||
|
||||
- Throws **[Error][13]** Invalid parameters
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## 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` before and after for both.
|
||||
- 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.
|
||||
|
||||
### 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
|
||||
**Throws**:
|
||||
|
||||
### Examples
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
```javascript
|
||||
|
||||
| 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.
|
||||
});
|
||||
```
|
||||
|
||||
```javascript
|
||||
**Example**
|
||||
```js
|
||||
sharp(input)
|
||||
.extract({ left: leftOffsetPre, top: topOffsetPre, width: widthPre, height: heightPre })
|
||||
.resize(width, height)
|
||||
@@ -200,48 +249,64 @@ sharp(input)
|
||||
});
|
||||
```
|
||||
|
||||
- Throws **[Error][13]** Invalid parameters
|
||||
|
||||
Returns **Sharp**
|
||||
|
||||
## trim
|
||||
> trim([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Trim "boring" pixels from all edges that contain values similar to the top-left pixel.
|
||||
Images consisting entirely of a single colour will calculate "boring" using the alpha channel, if any.
|
||||
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.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `threshold` **[number][8]** the allowed difference from the top-left pixel, a number greater than zero. (optional, default `10`)
|
||||
**Throws**:
|
||||
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
|
||||
- Throws **[Error][13]** 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? |
|
||||
|
||||
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
|
||||
**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();
|
||||
```
|
||||
@@ -1,139 +1,233 @@
|
||||
<!-- 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]**
|
||||
|
||||
## versions
|
||||
> versions
|
||||
|
||||
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.
|
||||
|
||||
### Examples
|
||||
|
||||
```javascript
|
||||
**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.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `options` **([Object][1] \| [boolean][2])** Object with the following attributes, or boolean where true uses default cache settings and false removes all caching (optional, default `true`)
|
||||
- `options.memory` **[number][3]** is the maximum memory in MB to use for this cache (optional, default `50`)
|
||||
- `options.files` **[number][3]** is the maximum number of files to hold open (optional, default `20`)
|
||||
- `options.items` **[number][3]** is the maximum number of operations to cache (optional, default `100`)
|
||||
|
||||
### Examples
|
||||
| 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 |
|
||||
|
||||
```javascript
|
||||
**Example**
|
||||
```js
|
||||
const stats = sharp.cache();
|
||||
```
|
||||
|
||||
```javascript
|
||||
**Example**
|
||||
```js
|
||||
sharp.cache( { items: 200 } );
|
||||
sharp.cache( { files: 0 } );
|
||||
sharp.cache(false);
|
||||
```
|
||||
|
||||
Returns **[Object][1]**
|
||||
|
||||
## concurrency
|
||||
> concurrency([concurrency]) ⇒ <code>number</code>
|
||||
|
||||
Gets or, when a concurrency is provided, sets
|
||||
the number of threads _libvips'_ should create to process each image.
|
||||
The default value is the number of CPU cores.
|
||||
A value of `0` will reset to this default.
|
||||
|
||||
The maximum number of images that can be processed in parallel
|
||||
is limited by libuv's `UV_THREADPOOL_SIZE` environment variable.
|
||||
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.
|
||||
|
||||
### Parameters
|
||||
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.
|
||||
|
||||
- `concurrency` **[number][3]?**
|
||||
A value of `0` will reset this to the number of CPU cores.
|
||||
|
||||
### Examples
|
||||
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.
|
||||
|
||||
```javascript
|
||||
The maximum number of images that sharp can process in parallel
|
||||
is controlled by libuv's `UV_THREADPOOL_SIZE` environment variable,
|
||||
which defaults to 4.
|
||||
|
||||
https://nodejs.org/api/cli.html#uv_threadpool_sizesize
|
||||
|
||||
For example, by default, a machine with 8 CPU cores will process
|
||||
4 images in parallel and use up to 8 threads per image,
|
||||
so there will be up to 32 concurrent threads.
|
||||
|
||||
|
||||
**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
|
||||
```
|
||||
|
||||
Returns **[number][3]** 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
|
||||
> 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.
|
||||
|
||||
- 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
|
||||
**Example**
|
||||
```js
|
||||
const counters = sharp.counters(); // { queue: 2, process: 4 }
|
||||
```
|
||||
|
||||
Returns **[Object][1]**
|
||||
|
||||
## simd
|
||||
> simd([simd]) ⇒ <code>boolean</code>
|
||||
|
||||
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
|
||||
by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.
|
||||
|
||||
### Parameters
|
||||
|
||||
- `simd` **[boolean][2]** (optional, default `true`)
|
||||
|
||||
### Examples
|
||||
| Param | Type | Default |
|
||||
| --- | --- | --- |
|
||||
| [simd] | <code>boolean</code> | <code>true</code> |
|
||||
|
||||
```javascript
|
||||
**Example**
|
||||
```js
|
||||
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
|
||||
```
|
||||
|
||||
```javascript
|
||||
**Example**
|
||||
```js
|
||||
const simd = sharp.simd(false);
|
||||
// prevent libvips from using liborc at runtime
|
||||
// prevent libvips from using highway at runtime
|
||||
```
|
||||
|
||||
Returns **[boolean][2]**
|
||||
|
||||
[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
|
||||
## block
|
||||
> block(options)
|
||||
|
||||
[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
|
||||
Block libvips operations at runtime.
|
||||
|
||||
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
|
||||
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']
|
||||
});
|
||||
```
|
||||
38
docs/build.js
Normal file
38
docs/build.js
Normal file
@@ -0,0 +1,38 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
const jsdoc2md = require('jsdoc-to-markdown');
|
||||
|
||||
[
|
||||
'constructor',
|
||||
'input',
|
||||
'resize',
|
||||
'composite',
|
||||
'operation',
|
||||
'colour',
|
||||
'channel',
|
||||
'output',
|
||||
'utility'
|
||||
].forEach(async (m) => {
|
||||
const input = path.join('lib', `${m}.js`);
|
||||
const output = path.join('docs', `api-${m}.md`);
|
||||
|
||||
const ast = await jsdoc2md.getTemplateData({ files: input });
|
||||
const markdown = await jsdoc2md.render({
|
||||
data: ast,
|
||||
'global-index-format': 'none',
|
||||
'module-index-format': 'none'
|
||||
});
|
||||
|
||||
const cleanMarkdown = markdown
|
||||
.replace(/(## )([A-Za-z0-9]+)([^\n]*)/g, '$1$2\n> $2$3\n') // simplify headings to match those of documentationjs, ensures existing URLs work
|
||||
.replace(/<a name="[A-Za-z0-9+]+"><\/a>/g, '') // remove anchors, let docute add these (at markdown to HTML render time)
|
||||
.replace(/\*\*Kind\*\*: global[^\n]+/g, '') // remove all "global" Kind labels (requires JSDoc refactoring)
|
||||
.trim();
|
||||
|
||||
await fs.writeFile(output, cleanMarkdown);
|
||||
});
|
||||
@@ -1,10 +1,821 @@
|
||||
# Changelog
|
||||
|
||||
## v0.33 - *gauge*
|
||||
|
||||
Requires libvips v8.15.2
|
||||
|
||||
### v0.33.3 - TBD
|
||||
|
||||
* 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*
|
||||
|
||||
Requires libvips v8.13.3
|
||||
|
||||
### v0.31.3 - 21st December 2022
|
||||
|
||||
* Add experimental support for JPEG-XL images. Requires libvips compiled with libjxl.
|
||||
[#2731](https://github.com/lovell/sharp/issues/2731)
|
||||
|
||||
* Add runtime detection of V8 memory cage, ensures compatibility with Electron 21 onwards.
|
||||
[#3384](https://github.com/lovell/sharp/issues/3384)
|
||||
|
||||
* Expose `interFrameMaxError` and `interPaletteMaxError` GIF optimisation properties.
|
||||
[#3401](https://github.com/lovell/sharp/issues/3401)
|
||||
|
||||
* Allow installation on Linux with glibc patch versions e.g. Fedora 38.
|
||||
[#3423](https://github.com/lovell/sharp/issues/3423)
|
||||
|
||||
* Expand range of existing `sharpen` parameters to match libvips.
|
||||
[#3427](https://github.com/lovell/sharp/issues/3427)
|
||||
|
||||
* Prevent possible race condition awaiting metadata of Stream-based input.
|
||||
[#3451](https://github.com/lovell/sharp/issues/3451)
|
||||
|
||||
* Improve `extractChannel` support for 16-bit output colourspaces.
|
||||
[#3453](https://github.com/lovell/sharp/issues/3453)
|
||||
|
||||
* Ignore `sequentialRead` option when calculating image statistics.
|
||||
[#3462](https://github.com/lovell/sharp/issues/3462)
|
||||
|
||||
* Small performance improvement for operations that introduce a non-opaque background.
|
||||
[#3465](https://github.com/lovell/sharp/issues/3465)
|
||||
|
||||
* Ensure integral output of `linear` operation.
|
||||
[#3468](https://github.com/lovell/sharp/issues/3468)
|
||||
|
||||
### v0.31.2 - 4th November 2022
|
||||
|
||||
* Upgrade to libvips v8.13.3 for upstream bug fixes.
|
||||
|
||||
* Ensure manual flip, rotate, resize operation ordering (regression in 0.31.1)
|
||||
[#3391](https://github.com/lovell/sharp/issues/3391)
|
||||
|
||||
* Ensure auto-rotation works without resize (regression in 0.31.1)
|
||||
[#3422](https://github.com/lovell/sharp/issues/3422)
|
||||
|
||||
### v0.31.1 - 29th September 2022
|
||||
|
||||
* Upgrade to libvips v8.13.2 for upstream bug fixes.
|
||||
|
||||
* Ensure `close` event occurs after `end` event for Stream-based output.
|
||||
[#3313](https://github.com/lovell/sharp/issues/3313)
|
||||
|
||||
* Ensure `limitInputPixels` constructor option uses uint64.
|
||||
[#3349](https://github.com/lovell/sharp/pull/3349)
|
||||
[@marcosc90](https://github.com/marcosc90)
|
||||
|
||||
* Ensure auto-rotation works with shrink-on-load and extract (regression in 0.31.0).
|
||||
[#3352](https://github.com/lovell/sharp/issues/3352)
|
||||
|
||||
* Ensure AVIF output is always 8-bit.
|
||||
[#3358](https://github.com/lovell/sharp/issues/3358)
|
||||
|
||||
* Ensure greyscale images can be trimmed (regression in 0.31.0).
|
||||
[#3386](https://github.com/lovell/sharp/issues/3386)
|
||||
|
||||
### v0.31.0 - 5th September 2022
|
||||
|
||||
* Drop support for Node.js 12, now requires Node.js >= 14.15.0.
|
||||
|
||||
* GIF output now re-uses input palette if possible. Use `reoptimise` option to generate a new palette.
|
||||
|
||||
* Add WebP `minSize` and `mixed` options for greater control over animation frames.
|
||||
|
||||
* Remove previously-deprecated WebP `reductionEffort` and HEIF `speed` options. Use `effort` to control these.
|
||||
|
||||
* The `flip` and `flop` operations will now occur before the `rotate` operation.
|
||||
|
||||
* Improve `normalise` operation with use of histogram.
|
||||
[#200](https://github.com/lovell/sharp/issues/200)
|
||||
|
||||
* Use combined bounding box of alpha and non-alpha channels for `trim` operation.
|
||||
[#2166](https://github.com/lovell/sharp/issues/2166)
|
||||
|
||||
* Add Buffer and Stream support to tile-based output.
|
||||
[#2238](https://github.com/lovell/sharp/issues/2238)
|
||||
|
||||
* Add input `fileSuffix` and output `alias` to `format` information.
|
||||
[#2642](https://github.com/lovell/sharp/issues/2642)
|
||||
|
||||
* Re-introduce support for greyscale ICC profiles (temporarily removed in 0.30.2).
|
||||
[#3114](https://github.com/lovell/sharp/issues/3114)
|
||||
|
||||
* Add support for WebP and PackBits `compression` options with TIFF output.
|
||||
[#3198](https://github.com/lovell/sharp/issues/3198)
|
||||
|
||||
* Ensure OpenSlide and FITS input works with custom libvips.
|
||||
[#3226](https://github.com/lovell/sharp/issues/3226)
|
||||
|
||||
* Ensure `trim` operation is a no-op when it would reduce an image to nothing.
|
||||
[#3223](https://github.com/lovell/sharp/issues/3223)
|
||||
|
||||
* Expose `vips_text` to create an image containing rendered text.
|
||||
[#3252](https://github.com/lovell/sharp/pull/3252)
|
||||
[@brahima](https://github.com/brahima)
|
||||
|
||||
* Ensure only properties owned by the `withMetadata` EXIF Object are parsed.
|
||||
[#3292](https://github.com/lovell/sharp/issues/3292)
|
||||
|
||||
* Expand `linear` operation to allow use of per-channel arrays.
|
||||
[#3303](https://github.com/lovell/sharp/pull/3303)
|
||||
[@antonmarsden](https://github.com/antonmarsden)
|
||||
|
||||
* Ensure the order of `rotate`, `resize` and `extend` operations is respected where possible.
|
||||
Emit warnings when previous calls in the same pipeline will be ignored.
|
||||
[#3319](https://github.com/lovell/sharp/issues/3319)
|
||||
|
||||
* Ensure PNG bitdepth can be set for non-palette output.
|
||||
[#3322](https://github.com/lovell/sharp/issues/3322)
|
||||
|
||||
* Add trim option to provide a specific background colour.
|
||||
[#3332](https://github.com/lovell/sharp/pull/3332)
|
||||
[@mart-jansink](https://github.com/mart-jansink)
|
||||
|
||||
* Ensure resized image is unpremultiplied before composite.
|
||||
[#3334](https://github.com/lovell/sharp/issues/3334)
|
||||
|
||||
## v0.30 - *dresser*
|
||||
|
||||
Requires libvips v8.12.2
|
||||
|
||||
### v0.30.7 - 22nd June 2022
|
||||
|
||||
* Ensure tiled composition always works with outside resizing.
|
||||
[#3227](https://github.com/lovell/sharp/issues/3227)
|
||||
|
||||
* Allow WebP encoding effort of 0.
|
||||
[#3261](https://github.com/lovell/sharp/pull/3261)
|
||||
[@AlexanderTheGrey](https://github.com/AlexanderTheGrey)
|
||||
|
||||
* Prevent upsampling via libwebp.
|
||||
[#3267](https://github.com/lovell/sharp/pull/3267)
|
||||
[@blacha](https://github.com/blacha)
|
||||
|
||||
### v0.30.6 - 30th May 2022
|
||||
|
||||
* Allow values for `limitInputPixels` larger than 32-bit.
|
||||
[#3238](https://github.com/lovell/sharp/issues/3238)
|
||||
|
||||
* Ensure brew-installed `vips` can be detected (regression in 0.30.5).
|
||||
[#3239](https://github.com/lovell/sharp/issues/3239)
|
||||
|
||||
### v0.30.5 - 23rd May 2022
|
||||
|
||||
* Install: pass `PKG_CONFIG_PATH` via env rather than substitution.
|
||||
[@dwisiswant0](https://github.com/dwisiswant0)
|
||||
|
||||
* Add support for `--libc` flag to improve cross-platform installation.
|
||||
[#3160](https://github.com/lovell/sharp/pull/3160)
|
||||
[@joonamo](https://github.com/joonamo)
|
||||
|
||||
* Allow installation of prebuilt libvips binaries from filesystem.
|
||||
[#3196](https://github.com/lovell/sharp/pull/3196)
|
||||
[@ankurparihar](https://github.com/ankurparihar)
|
||||
|
||||
* Fix rotate-then-extract for EXIF orientation 2.
|
||||
[#3218](https://github.com/lovell/sharp/pull/3218)
|
||||
[@jakob0fischl](https://github.com/jakob0fischl)
|
||||
|
||||
### v0.30.4 - 18th April 2022
|
||||
|
||||
* Increase control over sensitivity to invalid images via `failOn`, deprecate `failOnError` (equivalent to `failOn: 'warning'`).
|
||||
|
||||
* Ensure `create` input image has correct bit depth and colour space.
|
||||
[#3139](https://github.com/lovell/sharp/issues/3139)
|
||||
|
||||
* Add support for `TypedArray` input with `byteOffset` and `length`.
|
||||
[#3146](https://github.com/lovell/sharp/pull/3146)
|
||||
[@codepage949](https://github.com/codepage949)
|
||||
|
||||
* Improve error message when attempting to render SVG input greater than 32767x32767.
|
||||
[#3167](https://github.com/lovell/sharp/issues/3167)
|
||||
|
||||
* Add missing file name to 'Input file is missing' error message.
|
||||
[#3178](https://github.com/lovell/sharp/pull/3178)
|
||||
[@Brodan](https://github.com/Brodan)
|
||||
|
||||
### v0.30.3 - 14th March 2022
|
||||
|
||||
* Allow `sharpen` options to be provided more consistently as an Object.
|
||||
[#2561](https://github.com/lovell/sharp/issues/2561)
|
||||
|
||||
* Expose `x1`, `y2` and `y3` parameters of `sharpen` operation.
|
||||
[#2935](https://github.com/lovell/sharp/issues/2935)
|
||||
|
||||
* Prevent double unpremultiply with some composite blend modes (regression in 0.30.2).
|
||||
[#3118](https://github.com/lovell/sharp/issues/3118)
|
||||
|
||||
### v0.30.2 - 2nd March 2022
|
||||
|
||||
* Improve performance and accuracy when compositing multiple images.
|
||||
[#2286](https://github.com/lovell/sharp/issues/2286)
|
||||
|
||||
* Expand pkgconfig search path for wider BSD support.
|
||||
[#3106](https://github.com/lovell/sharp/issues/3106)
|
||||
|
||||
* Ensure Windows C++ runtime is linked statically (regression in 0.30.0).
|
||||
[#3110](https://github.com/lovell/sharp/pull/3110)
|
||||
[@kleisauke](https://github.com/kleisauke)
|
||||
|
||||
* Temporarily ignore greyscale ICC profiles to workaround lcms bug.
|
||||
[#3112](https://github.com/lovell/sharp/issues/3112)
|
||||
|
||||
### v0.30.1 - 9th February 2022
|
||||
|
||||
* Allow use of `toBuffer` and `toFile` on the same instance.
|
||||
[#3044](https://github.com/lovell/sharp/issues/3044)
|
||||
|
||||
* Skip shrink-on-load for known libjpeg rounding errors.
|
||||
[#3066](https://github.com/lovell/sharp/issues/3066)
|
||||
[@kleisauke](https://github.com/kleisauke)
|
||||
|
||||
* Ensure withoutReduction does not interfere with contain/crop/embed.
|
||||
[#3081](https://github.com/lovell/sharp/pull/3081)
|
||||
[@kleisauke](https://github.com/kleisauke)
|
||||
|
||||
* Ensure affine interpolator is correctly finalised.
|
||||
[#3083](https://github.com/lovell/sharp/pull/3083)
|
||||
[@kleisauke](https://github.com/kleisauke)
|
||||
|
||||
### v0.30.0 - 1st February 2022
|
||||
|
||||
* Add support for GIF output to prebuilt binaries.
|
||||
|
||||
* Reduce minimum Linux ARM64v8 glibc requirement to 2.17.
|
||||
|
||||
* Verify prebuilt binaries with a Subresource Integrity check.
|
||||
|
||||
* Standardise WebP `effort` option name, deprecate `reductionEffort`.
|
||||
|
||||
* Standardise HEIF `effort` option name, deprecate `speed`.
|
||||
|
||||
* Add support for IIIF v3 tile-based output.
|
||||
|
||||
* Expose control over CPU effort for palette-based PNG output.
|
||||
[#2541](https://github.com/lovell/sharp/issues/2541)
|
||||
|
||||
* Improve animated (multi-page) image resize and extract.
|
||||
[#2789](https://github.com/lovell/sharp/pull/2789)
|
||||
[@kleisauke](https://github.com/kleisauke)
|
||||
|
||||
* Expose platform and architecture of vendored binaries as `sharp.vendor`.
|
||||
[#2928](https://github.com/lovell/sharp/issues/2928)
|
||||
|
||||
* Ensure 16-bit PNG output uses correct bitdepth.
|
||||
[#2958](https://github.com/lovell/sharp/pull/2958)
|
||||
[@gforge](https://github.com/gforge)
|
||||
|
||||
* Properly emit close events for duplex streams.
|
||||
[#2976](https://github.com/lovell/sharp/pull/2976)
|
||||
[@driannaude](https://github.com/driannaude)
|
||||
|
||||
* Expose `unlimited` option for SVG and PNG input, switches off safety features.
|
||||
[#2984](https://github.com/lovell/sharp/issues/2984)
|
||||
|
||||
* Add `withoutReduction` option to resize operation.
|
||||
[#3006](https://github.com/lovell/sharp/pull/3006)
|
||||
[@christopherbradleybanks](https://github.com/christopherbradleybanks)
|
||||
|
||||
* Add `resolutionUnit` as `tiff` option and expose in metadata.
|
||||
[#3023](https://github.com/lovell/sharp/pull/3023)
|
||||
[@ompal-sisodiya](https://github.com/ompal-sisodiya)
|
||||
|
||||
* Ensure rotate-then-extract works with EXIF mirroring.
|
||||
[#3024](https://github.com/lovell/sharp/issues/3024)
|
||||
|
||||
## v0.29 - *circle*
|
||||
|
||||
Requires libvips v8.11.3
|
||||
|
||||
### v0.29.3 - 14th November 2021
|
||||
|
||||
* Ensure correct dimensions when containing image resized to 1px.
|
||||
[#2951](https://github.com/lovell/sharp/issues/2951)
|
||||
|
||||
* Impute TIFF `xres`/`yres` from `density` provided to `withMetadata`.
|
||||
[#2952](https://github.com/lovell/sharp/pull/2952)
|
||||
[@mbklein](https://github.com/mbklein)
|
||||
|
||||
### v0.29.2 - 21st October 2021
|
||||
|
||||
* Add `timeout` function to limit processing time.
|
||||
|
||||
* Ensure `sharp.versions` is populated from vendored libvips.
|
||||
|
||||
* Remove animation properties from single page images.
|
||||
[#2890](https://github.com/lovell/sharp/issues/2890)
|
||||
|
||||
* Allow use of 'tif' to select TIFF output.
|
||||
[#2893](https://github.com/lovell/sharp/pull/2893)
|
||||
[@erf](https://github.com/erf)
|
||||
|
||||
* Improve error message on Windows for version conflict.
|
||||
[#2918](https://github.com/lovell/sharp/pull/2918)
|
||||
[@dkrnl](https://github.com/dkrnl)
|
||||
|
||||
* Throw error rather than exit when invalid binaries detected.
|
||||
[#2931](https://github.com/lovell/sharp/issues/2931)
|
||||
|
||||
### v0.29.1 - 7th September 2021
|
||||
|
||||
* Add `lightness` option to `modulate` operation.
|
||||
[#2846](https://github.com/lovell/sharp/pull/2846)
|
||||
|
||||
* Ensure correct PNG bitdepth is set based on number of colours.
|
||||
[#2855](https://github.com/lovell/sharp/issues/2855)
|
||||
|
||||
* Ensure background is always premultiplied when compositing.
|
||||
[#2858](https://github.com/lovell/sharp/issues/2858)
|
||||
|
||||
* Ensure images with P3 profiles retain full gamut.
|
||||
[#2862](https://github.com/lovell/sharp/issues/2862)
|
||||
|
||||
* Add support for libvips compiled with OpenJPEG.
|
||||
[#2868](https://github.com/lovell/sharp/pull/2868)
|
||||
|
||||
* Remove unsupported animation properties from AVIF output.
|
||||
[#2870](https://github.com/lovell/sharp/issues/2870)
|
||||
|
||||
* Resolve paths before comparing input/output filenames.
|
||||
[#2878](https://github.com/lovell/sharp/pull/2878)
|
||||
[@rexxars](https://github.com/rexxars)
|
||||
|
||||
* Allow use of speed 9 (fastest) for HEIF encoding.
|
||||
[#2879](https://github.com/lovell/sharp/pull/2879)
|
||||
[@rexxars](https://github.com/rexxars)
|
||||
|
||||
### v0.29.0 - 17th August 2021
|
||||
|
||||
* Drop support for Node.js 10, now requires Node.js >= 12.13.0.
|
||||
|
||||
* Add `background` property to PNG and GIF image metadata.
|
||||
|
||||
* Add `compression` property to HEIF image metadata.
|
||||
[#2504](https://github.com/lovell/sharp/issues/2504)
|
||||
|
||||
* AVIF encoding now defaults to `4:4:4` chroma subsampling.
|
||||
[#2562](https://github.com/lovell/sharp/issues/2562)
|
||||
|
||||
* Allow multiple platform-arch binaries in same `node_modules` installation tree.
|
||||
[#2575](https://github.com/lovell/sharp/issues/2575)
|
||||
|
||||
* Default to single-channel `b-w` space when `extractChannel` is used.
|
||||
[#2658](https://github.com/lovell/sharp/issues/2658)
|
||||
|
||||
* Allow installation directory to contain spaces (regression in v0.26.0).
|
||||
[#2777](https://github.com/lovell/sharp/issues/2777)
|
||||
|
||||
* Add `pipelineColourspace` operator to set the processing space.
|
||||
[#2704](https://github.com/lovell/sharp/pull/2704)
|
||||
[@Daiz](https://github.com/Daiz)
|
||||
|
||||
* Allow bit depth to be set when using raw input and output.
|
||||
[#2762](https://github.com/lovell/sharp/pull/2762)
|
||||
[@mart-jansink](https://github.com/mart-jansink)
|
||||
|
||||
* Allow `negate` to act only on non-alpha channels.
|
||||
[#2808](https://github.com/lovell/sharp/pull/2808)
|
||||
[@rexxars](https://github.com/rexxars)
|
||||
|
||||
## v0.28 - *bijou*
|
||||
|
||||
Requires libvips v8.10.6
|
||||
|
||||
### v0.28.3 - 24th May 2021
|
||||
|
||||
* Ensure presence of libvips, vendored or global, before invoking node-gyp.
|
||||
|
||||
* Skip shrink-on-load for multi-page WebP.
|
||||
[#2714](https://github.com/lovell/sharp/issues/2714)
|
||||
|
||||
* Add contrast limiting adaptive histogram equalization (CLAHE) operator.
|
||||
[#2726](https://github.com/lovell/sharp/pull/2726)
|
||||
[@baparham](https://github.com/baparham)
|
||||
|
||||
### v0.28.2 - 10th May 2021
|
||||
|
||||
* Allow `withMetadata` to set `density`.
|
||||
[#967](https://github.com/lovell/sharp/issues/967)
|
||||
|
||||
* Skip shrink-on-load where one dimension <4px.
|
||||
[#2653](https://github.com/lovell/sharp/issues/2653)
|
||||
|
||||
* Allow escaped proxy credentials.
|
||||
[#2664](https://github.com/lovell/sharp/pull/2664)
|
||||
[@msalettes](https://github.com/msalettes)
|
||||
|
||||
* Add `premultiplied` flag for raw pixel data input.
|
||||
[#2685](https://github.com/lovell/sharp/pull/2685)
|
||||
[@mnutt](https://github.com/mnutt)
|
||||
|
||||
* Detect empty input and throw a helpful error.
|
||||
[#2687](https://github.com/lovell/sharp/pull/2687)
|
||||
[@JakobJingleheimer](https://github.com/JakobJingleheimer)
|
||||
|
||||
* Add install-time flag to skip version compatibility checks.
|
||||
[#2692](https://github.com/lovell/sharp/pull/2692)
|
||||
[@xemle](https://github.com/xemle)
|
||||
|
||||
### v0.28.1 - 5th April 2021
|
||||
|
||||
* Ensure all installation errors are logged with a more obvious prefix.
|
||||
|
||||
* Allow `withMetadata` to set and update EXIF metadata.
|
||||
[#650](https://github.com/lovell/sharp/issues/650)
|
||||
|
||||
* Add support for OME-TIFF Sub Image File Directories (subIFD).
|
||||
[#2557](https://github.com/lovell/sharp/issues/2557)
|
||||
|
||||
* Allow `ensureAlpha` to set the alpha transparency level.
|
||||
[#2634](https://github.com/lovell/sharp/issues/2634)
|
||||
|
||||
### v0.28.0 - 29th March 2021
|
||||
|
||||
* Prebuilt binaries now include mozjpeg and libimagequant (BSD 2-Clause).
|
||||
|
||||
* Prebuilt binaries limit AVIF support to the most common 8-bit depth.
|
||||
|
||||
* Add `mozjpeg` option to `jpeg` method, sets mozjpeg defaults.
|
||||
|
||||
* Reduce the default PNG `compressionLevel` to the more commonly used 6.
|
||||
|
||||
* Reduce concurrency on glibc-based Linux when using the default memory allocator to help prevent fragmentation.
|
||||
|
||||
* Default missing edge properties of extend operation to zero.
|
||||
[#2578](https://github.com/lovell/sharp/issues/2578)
|
||||
|
||||
* Ensure composite does not clip top and left offsets.
|
||||
[#2594](https://github.com/lovell/sharp/pull/2594)
|
||||
[@SHG42](https://github.com/SHG42)
|
||||
|
||||
* Improve error handling of network failure at install time.
|
||||
[#2608](https://github.com/lovell/sharp/pull/2608)
|
||||
[@abradley](https://github.com/abradley)
|
||||
|
||||
* Ensure `@id` attribute can be set for IIIF tile-based output.
|
||||
[#2612](https://github.com/lovell/sharp/issues/2612)
|
||||
[@edsilv](https://github.com/edsilv)
|
||||
|
||||
* Ensure composite replicates the correct number of tiles for centred gravities.
|
||||
[#2626](https://github.com/lovell/sharp/issues/2626)
|
||||
|
||||
## v0.27 - *avif*
|
||||
|
||||
Requires libvips v8.10.5
|
||||
|
||||
### v0.27.2 - 22nd February 2021
|
||||
|
||||
* macOS: Prevent use of globally-installed ARM64 libvips with Rosetta x64 emulation.
|
||||
[#2460](https://github.com/lovell/sharp/issues/2460)
|
||||
|
||||
* Linux (musl): Prevent use of prebuilt linuxmusl-x64 binaries with musl >= 1.2.0.
|
||||
[#2570](https://github.com/lovell/sharp/issues/2570)
|
||||
|
||||
* Improve 16-bit grey+alpha support by using libvips' `has_alpha` detection.
|
||||
[#2569](https://github.com/lovell/sharp/issues/2569)
|
||||
|
||||
* Allow the use of non lower case extensions with `toFormat`.
|
||||
[#2581](https://github.com/lovell/sharp/pull/2581)
|
||||
[@florian-busch](https://github.com/florian-busch)
|
||||
|
||||
* Allow use of `recomb` operation with single channel input.
|
||||
[#2584](https://github.com/lovell/sharp/issues/2584)
|
||||
|
||||
### v0.27.1 - 27th January 2021
|
||||
|
||||
* Ensure TIFF is cast when using float predictor.
|
||||
[#2502](https://github.com/lovell/sharp/pull/2502)
|
||||
[@randyridge](https://github.com/randyridge)
|
||||
|
||||
* Add support for Uint8Array and Uint8ClampedArray input.
|
||||
[#2511](https://github.com/lovell/sharp/pull/2511)
|
||||
[@leon](https://github.com/leon)
|
||||
|
||||
* Revert: ensure all platforms use fontconfig for font rendering.
|
||||
[#2515](https://github.com/lovell/sharp/issues/2515)
|
||||
|
||||
* Expose libvips gaussnoise operation to allow creation of Gaussian noise.
|
||||
[#2527](https://github.com/lovell/sharp/pull/2527)
|
||||
[@alza54](https://github.com/alza54)
|
||||
|
||||
### v0.27.0 - 22nd December 2020
|
||||
|
||||
* Add support for AVIF to prebuilt binaries.
|
||||
|
||||
* Remove experimental status from `heif` output, defaults are now AVIF-centric.
|
||||
|
||||
* Allow negative top/left offsets for composite operation.
|
||||
[#2391](https://github.com/lovell/sharp/pull/2391)
|
||||
[@CurosMJ](https://github.com/CurosMJ)
|
||||
|
||||
* Ensure all platforms use fontconfig for font rendering.
|
||||
[#2399](https://github.com/lovell/sharp/issues/2399)
|
||||
|
||||
## v0.26 - *zoom*
|
||||
|
||||
Requires libvips v8.10.0
|
||||
|
||||
### v0.26.0 - TBD
|
||||
### v0.26.3 - 16th November 2020
|
||||
|
||||
* Expose libvips' affine operation.
|
||||
[#2336](https://github.com/lovell/sharp/pull/2336)
|
||||
[@guillevc](https://github.com/guillevc)
|
||||
|
||||
* Fallback to tar.gz for prebuilt libvips when Brotli not available.
|
||||
[#2412](https://github.com/lovell/sharp/pull/2412)
|
||||
[@ascorbic](https://github.com/ascorbic)
|
||||
|
||||
### v0.26.2 - 14th October 2020
|
||||
|
||||
* Add support for EXR input. Requires libvips compiled with OpenEXR.
|
||||
[#698](https://github.com/lovell/sharp/issues/698)
|
||||
|
||||
* Ensure support for yarn v2.
|
||||
[#2379](https://github.com/lovell/sharp/pull/2379)
|
||||
[@jalovatt](https://github.com/jalovatt)
|
||||
|
||||
* Add centre/center option to tile-based output.
|
||||
[#2397](https://github.com/lovell/sharp/pull/2397)
|
||||
[@beig](https://github.com/beig)
|
||||
|
||||
### v0.26.1 - 20th September 2020
|
||||
|
||||
* Ensure correct pageHeight when verifying multi-page image dimensions.
|
||||
[#2343](https://github.com/lovell/sharp/pull/2343)
|
||||
[@derom](https://github.com/derom)
|
||||
|
||||
* Allow input density range up to 100000 DPI.
|
||||
[#2348](https://github.com/lovell/sharp/pull/2348)
|
||||
[@stefanprobst](https://github.com/stefanprobst)
|
||||
|
||||
* Ensure animation-related properties can be set for Stream-based input.
|
||||
[#2369](https://github.com/lovell/sharp/pull/2369)
|
||||
[@AcrylicShrimp](https://github.com/AcrylicShrimp)
|
||||
|
||||
* Ensure `stats` can be calculated for 1x1 input.
|
||||
[#2372](https://github.com/lovell/sharp/issues/2372)
|
||||
|
||||
* Ensure animated GIF output is optimised.
|
||||
[#2376](https://github.com/lovell/sharp/issues/2376)
|
||||
|
||||
### v0.26.0 - 25th August 2020
|
||||
|
||||
* Prebuilt libvips binaries are now statically-linked and Brotli-compressed, requiring Node.js 10.16.0+.
|
||||
|
||||
|
||||
1
docs/docute.min.js
vendored
Normal file
1
docs/docute.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
@@ -4,8 +4,8 @@
|
||||
"public": ".",
|
||||
"ignore": [
|
||||
".*",
|
||||
"build.js",
|
||||
"firebase.json",
|
||||
"*.md",
|
||||
"image/**",
|
||||
"search-index/**"
|
||||
],
|
||||
@@ -13,10 +13,9 @@
|
||||
{
|
||||
"source": "**",
|
||||
"headers": [
|
||||
{
|
||||
"key": "Cache-Control",
|
||||
"value": "max-age=86400"
|
||||
}
|
||||
{ "key": "Cache-Control", "value": "max-age=86400" },
|
||||
{ "key": "X-Content-Type-Options", "value": "nosniff" },
|
||||
{ "key": "X-Frame-Options", "value": "SAMEORIGIN" }
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -197,3 +197,96 @@ GitHub: https://github.com/deftomat
|
||||
|
||||
Name: Robert O'Rourke
|
||||
GitHub: https://github.com/roborourke
|
||||
|
||||
Name: Denis Soldatov
|
||||
GitHub: https://github.com/derom
|
||||
|
||||
Name: Stefan Probst
|
||||
GitHub: https://github.com/stefanprobst
|
||||
|
||||
Name: Thomas Beiganz
|
||||
GitHub: https://github.com/beig
|
||||
|
||||
Name: Florian Busch
|
||||
GitHub: https://github.com/florian-busch
|
||||
|
||||
Name: Matthieu Salettes
|
||||
GitHub: https://github.com/msalettes
|
||||
|
||||
Name: Taneli Vatanen
|
||||
GitHub: https://github.com/Daiz
|
||||
|
||||
Name: Mart Jansink
|
||||
GitHub: https://github.com/mart-jansink
|
||||
|
||||
Name: Tenpi
|
||||
GitHub: https://github.com/Tenpi
|
||||
|
||||
Name: Zaruike
|
||||
GitHub: https://github.com/Zaruike
|
||||
|
||||
Name: Erlend F
|
||||
GitHub: https://github.com/erf
|
||||
|
||||
Name: Drian Naude
|
||||
GitHub: https://github.com/driannaude
|
||||
|
||||
Name: Max Gordon
|
||||
GitHub: https://github.com/gforge
|
||||
|
||||
Name: Chris Banks
|
||||
GitHub: https://github.com/christopherbradleybanks
|
||||
|
||||
Name: codepage949
|
||||
GitHub: https://github.com/codepage949
|
||||
|
||||
Name: Chris Hranj
|
||||
GitHub: https://github.com/Brodan
|
||||
|
||||
Name: Ankur Parihar
|
||||
GitHub: https://github.com/ankurparihar
|
||||
|
||||
Name: Joona Heinikoski
|
||||
GitHub: https://github.com/joonamo
|
||||
|
||||
Name: AlexanderTheGrey
|
||||
GitHub: https://github.com/AlexanderTheGrey
|
||||
|
||||
Name: Blayne Chard
|
||||
GitHub: https://github.com/blacha
|
||||
|
||||
Name: Brahim
|
||||
GitHub: https://github.com/brahima
|
||||
|
||||
Name: Anton Marsden
|
||||
GitHub: https://github.com/antonmarsden
|
||||
|
||||
Name: Marcos Casagrande
|
||||
GitHub: https://github.com/marcosc90
|
||||
|
||||
Name: Emanuel Jöbstl
|
||||
GitHub: https://github.com/ejoebstl
|
||||
|
||||
Name: Tomasz Janowski
|
||||
GitHub: https://github.com/janaz
|
||||
|
||||
Name: Lachlan Newman
|
||||
GitHub: https://github.com/LachlanNewman
|
||||
|
||||
Name: BJJ
|
||||
GitHub: https://github.com/bianjunjie1981
|
||||
|
||||
Name: Dennis Beatty
|
||||
GitHub: https://github.com/dnsbty
|
||||
|
||||
Name: Ingvar Stepanyan
|
||||
GitHub: https://github.com/RReverser
|
||||
|
||||
Name: Tamás András Horváth
|
||||
GitHub: https://github.com/icetee
|
||||
|
||||
Name: Aaron Che
|
||||
GitHub: https://github.com/yolopunk
|
||||
|
||||
Name: Mert Alev
|
||||
GitHub: https://github.com/mertalev
|
||||
|
||||
61
docs/image/api-resize-fit.svg
Normal file
61
docs/image/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 |
BIN
docs/image/sharp-logo-32.png
Normal file
BIN
docs/image/sharp-logo-32.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 652 B |
BIN
docs/image/sharp-logo-600.png
Normal file
BIN
docs/image/sharp-logo-600.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.8 KiB |
11
docs/image/sharp-logo-mono.svg
Normal file
11
docs/image/sharp-logo-mono.svg
Normal file
@@ -0,0 +1,11 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="86 86 550 550">
|
||||
<!-- Creative Commons CC0 1.0 Universal Public Domain Dedication -->
|
||||
<defs>
|
||||
<mask id="c">
|
||||
<path fill="none" stroke="#fff" stroke-width="80" d="M258.411 285.777l200.176-26.8M244.113 466.413L451.44 438.66m.001 0V238.484m0-150.121v171.572l178.725-23.917m-359.843 19.584V477.22m2.387 156.95V462.591L93.984 486.515"/>
|
||||
<path fill="none" stroke="#000" stroke-width="112" d="M451.441 610.246V438.66l178.725-23.91M269.688 112.59v171.58L90.964 308.093"/>
|
||||
</mask>
|
||||
</defs>
|
||||
<path mask="url(#c)" fill="none" stroke="#000" stroke-width="80" d="M258.411 285.777l200.176-26.8M244.113 466.413L451.44 438.66m.001 0V238.484m0-150.121v171.572l178.725-23.917m-359.843 19.584V477.22m2.387 156.95V462.591L93.984 486.515"/>
|
||||
<path fill="none" stroke="#000" stroke-width="80" d="M451.441 610.246V438.66l178.725-23.91M269.688 112.59v171.58L90.964 308.093"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 929 B |
@@ -1,5 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="86 86 550 550">
|
||||
<!-- Copyright 2019 Lovell Fuller. This work is licensed under the Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) License. -->
|
||||
<!-- 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>
|
||||
|
Before Width: | Height: | Size: 592 B After Width: | Height: | Size: 508 B |
File diff suppressed because one or more lines are too long
333
docs/install.md
333
docs/install.md
@@ -1,120 +1,139 @@
|
||||
# Installation
|
||||
|
||||
Works with your choice of JavaScript package manager.
|
||||
|
||||
> ⚠️ **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
|
||||
```
|
||||
|
||||
```sh
|
||||
yarn add sharp
|
||||
```
|
||||
|
||||
```sh
|
||||
# yarn v1 (maintenance mode)
|
||||
yarn add sharp --ignore-engines
|
||||
```
|
||||
|
||||
```sh
|
||||
bun add sharp
|
||||
```
|
||||
|
||||
```sh
|
||||
deno run --allow-ffi ...
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
* Node.js v10.16.0+
|
||||
* 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 with
|
||||
Node.js v10.16.0+ on the most common platforms:
|
||||
Ready-compiled sharp and libvips binaries are provided for use on the most common platforms:
|
||||
|
||||
* macOS x64 (>= 10.13)
|
||||
* Linux x64 (glibc >= 2.17, musl >= 1.1.24)
|
||||
* Linux ARM64 (glibc >= 2.29)
|
||||
* Windows
|
||||
|
||||
A ~7MB tarball containing libvips and its most commonly used dependencies
|
||||
is downloaded via HTTPS and stored within `node_modules/sharp/vendor` during `npm install`.
|
||||
* macOS ARM64
|
||||
* Linux ARM (glibc >= 2.28)
|
||||
* Linux ARM64 (glibc >= 2.26, musl >= 1.2.2)
|
||||
* Linux s390x (glibc >= 2.28)
|
||||
* Linux x64 (glibc >= 2.26, musl >= 1.2.2, CPU with SSE4.2)
|
||||
* Windows x64
|
||||
* Windows x86
|
||||
|
||||
This provides support for the
|
||||
JPEG, PNG, WebP, TIFF, GIF (input) and SVG (input) image formats.
|
||||
JPEG, PNG, WebP, AVIF (limited to 8-bit depth), TIFF, GIF and SVG (input) image formats.
|
||||
|
||||
The following platforms have prebuilt libvips but not sharp:
|
||||
## Cross-platform
|
||||
|
||||
* Linux ARMv6
|
||||
* Linux ARMv7 (glibc >= 2.28)
|
||||
At install time, package managers will automatically select prebuilt binaries
|
||||
for the current OS platform and CPU architecture, where available.
|
||||
|
||||
The following platforms require compilation of both libvips and sharp from source:
|
||||
Some package managers support multiple platforms and architectures
|
||||
within the same installation tree and/or using the same lockfile.
|
||||
|
||||
* Linux x86
|
||||
* Linux x64 (glibc <= 2.16, includes RHEL/CentOS 6)
|
||||
* Linux ARM64 (glibc <= 2.28, musl)
|
||||
* Linux PowerPC
|
||||
* FreeBSD
|
||||
* OpenBSD
|
||||
### npm v10+
|
||||
|
||||
## Common problems
|
||||
> ⚠️ **npm `package-lock.json` files can cause installation problems due to [npm bug #4828](https://github.com/npm/cli/issues/4828)**
|
||||
|
||||
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.
|
||||
Provides limited support via `--os`, `--cpu` and `--libc` flags.
|
||||
|
||||
The `npm install --unsafe-perm` flag must be used when installing as `root` or a `sudo` user.
|
||||
Example to support both Intel and ARM CPUs on macOS:
|
||||
```sh
|
||||
npm install --cpu=x64 --os=darwin sharp
|
||||
npm install --cpu=arm64 --os=darwin sharp
|
||||
```
|
||||
|
||||
The `npm install --ignore-scripts=false` flag must be used when `npm` has been configured to ignore installation scripts.
|
||||
Example to support both glibc and musl-based Linux:
|
||||
```sh
|
||||
npm install --cpu=x64 --os=linux sharp
|
||||
npm install --cpu=x64 --os=linux --libc=musl sharp
|
||||
```
|
||||
|
||||
Check the output of running `npm install --verbose sharp` for useful error messages.
|
||||
### yarn v3+
|
||||
|
||||
Use the [supportedArchitectures](https://yarnpkg.com/configuration/yarnrc#supportedArchitectures) configuration.
|
||||
|
||||
### pnpm v8+
|
||||
|
||||
Use the [supportedArchitectures](https://pnpm.io/package_json#pnpmsupportedarchitectures) 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
|
||||
make sure it is at least the version listed under `engines.libvips` in the `package.json` file
|
||||
and that it can be located using `pkg-config --modversion vips-cpp`.
|
||||
|
||||
For help compiling libvips from source, please see
|
||||
[https://libvips.github.io/libvips/install.html#building-libvips-from-a-source-tarball](https://libvips.github.io/libvips/install.html#building-libvips-from-a-source-tarball).
|
||||
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.
|
||||
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 (set the `SHARP_IGNORE_GLOBAL_LIBVIPS` environment variable to skip this),
|
||||
* prebuilt binaries do not exist for the current platform and Node.js version, or
|
||||
* a globally-installed libvips is detected (set the `SHARP_IGNORE_GLOBAL_LIBVIPS` environment variable to skip this), 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
|
||||
* [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
|
||||
|
||||
## Custom prebuilt binaries
|
||||
|
||||
This is an advanced approach that most people will not require.
|
||||
|
||||
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 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.
|
||||
|
||||
The version subpath and file name are appended to these.
|
||||
|
||||
For example, if `sharp_libvips_binary_host` is set to `https://hostname/path`
|
||||
and the libvips version is `1.2.3` then the resultant URL will be
|
||||
`https://hostname/path/v1.2.3/libvips-1.2.3-platform-arch.tar.br`.
|
||||
|
||||
See the Chinese mirror below for a further example.
|
||||
|
||||
## Chinese mirror
|
||||
|
||||
Alibaba provide a mirror site based in China containing binaries for both sharp and libvips.
|
||||
|
||||
To use this either set the following configuration:
|
||||
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 config set sharp_binary_host "https://npm.taobao.org/mirrors/sharp"
|
||||
npm config set sharp_libvips_binary_host "https://npm.taobao.org/mirrors/sharp-libvips"
|
||||
npm install sharp
|
||||
npm install --save node-addon-api node-gyp
|
||||
```
|
||||
|
||||
or set the following environment variables:
|
||||
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.
|
||||
|
||||
```sh
|
||||
npm_config_sharp_binary_host="https://npm.taobao.org/mirrors/sharp" \
|
||||
npm_config_sharp_libvips_binary_host="https://npm.taobao.org/mirrors/sharp-libvips" \
|
||||
npm install sharp
|
||||
npm install --cpu=wasm32 sharp
|
||||
```
|
||||
|
||||
## FreeBSD
|
||||
@@ -129,58 +148,168 @@ pkg install -y pkgconf vips
|
||||
cd /usr/ports/graphics/vips/ && make install clean
|
||||
```
|
||||
|
||||
## Heroku
|
||||
## Linux memory allocator
|
||||
|
||||
Add the
|
||||
[jemalloc buildpack](https://github.com/gaffneyc/heroku-buildpack-jemalloc)
|
||||
to reduce the effects of memory fragmentation.
|
||||
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.
|
||||
|
||||
Set
|
||||
[NODE_MODULES_CACHE](https://devcenter.heroku.com/articles/nodejs-support#cache-behavior)
|
||||
to `false` when using the `yarn` package manager.
|
||||
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
|
||||
|
||||
Set the Lambda runtime to `nodejs12.x`.
|
||||
|
||||
The binaries in the `node_modules` directory of the
|
||||
The `node_modules` directory of the
|
||||
[deployment package](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-package.html)
|
||||
must be for the Linux x64 platform.
|
||||
must include binaries for either the linux-x64 or linux-arm64 platforms
|
||||
depending on the chosen architecture.
|
||||
|
||||
On machines other than Linux x64, such as macOS and Windows, run the following:
|
||||
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.
|
||||
|
||||
```sh
|
||||
rm -rf node_modules/sharp
|
||||
npm install --arch=x64 --platform=linux sharp
|
||||
```
|
||||
|
||||
Alternatively a Docker container closely matching the Lambda runtime can be used:
|
||||
|
||||
```sh
|
||||
rm -rf node_modules/sharp
|
||||
docker run -v "$PWD":/var/task lambci/lambda:build-nodejs12.x npm install sharp
|
||||
```
|
||||
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.
|
||||
|
||||
## Electron
|
||||
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).
|
||||
|
||||
Electron provides versions of the V8 JavaScript engine
|
||||
that are incompatible with Node.js.
|
||||
To ensure the correct binaries are used, run the following:
|
||||
## Bundlers
|
||||
|
||||
```sh
|
||||
npm install
|
||||
npx electron-rebuild
|
||||
### webpack
|
||||
|
||||
Ensure sharp is excluded from bundling via the
|
||||
[externals](https://webpack.js.org/configuration/externals/)
|
||||
configuration.
|
||||
|
||||
```js
|
||||
externals: {
|
||||
'sharp': 'commonjs sharp'
|
||||
}
|
||||
```
|
||||
|
||||
Further help can be found at
|
||||
[https://electronjs.org/docs/tutorial/using-native-node-modules](https://electronjs.org/docs/tutorial/using-native-node-modules)
|
||||
### esbuild
|
||||
|
||||
## Worker threads
|
||||
Ensure sharp is excluded from bundling via the
|
||||
[external](https://esbuild.github.io/api/#external)
|
||||
configuration.
|
||||
|
||||
The main thread must call `require('sharp')`
|
||||
before worker threads are created
|
||||
to ensure shared libraries remain loaded in memory
|
||||
until after all threads are complete.
|
||||
```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
|
||||
|
||||
Ensure `sharp` is unpacked from the ASAR archive file using the
|
||||
[asarUnpack](https://www.electron.build/configuration/configuration.html)
|
||||
option.
|
||||
|
||||
```json
|
||||
{
|
||||
"build": {
|
||||
"asar": true,
|
||||
"asarUnpack": [
|
||||
"**/node_modules/sharp/**/*",
|
||||
"**/node_modules/@img/**/*"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 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.
|
||||
```
|
||||
|
||||
@@ -2,67 +2,110 @@
|
||||
|
||||
A test to benchmark the performance of this module relative to alternatives.
|
||||
|
||||
## The contenders
|
||||
|
||||
* [jimp](https://www.npmjs.com/package/jimp) v0.9.3 - Image processing in pure JavaScript. Provides bicubic interpolation.
|
||||
* [mapnik](https://www.npmjs.org/package/mapnik) v4.3.1 - 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.
|
||||
* sharp v0.24.0 / libvips v8.9.0 - 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 [c5.large](https://aws.amazon.com/ec2/instance-types/c5/) (2x Xeon Platinum 8124M CPU @ 3.00GHz)
|
||||
* Ubuntu 18.04 (hvm-ssd/ubuntu-bionic-18.04-amd64-server-20180912 ami-00035f41c82244dab)
|
||||
* Node.js v12.14.1
|
||||
|
||||
## Results
|
||||
|
||||
| Module | Input | Output | Ops/sec | Speed-up |
|
||||
| :----------------- | :----- | :----- | ------: | -------: |
|
||||
| jimp | buffer | buffer | 0.72 | 1.0 |
|
||||
| mapnik | buffer | buffer | 3.02 | 4.2 |
|
||||
| gm | buffer | buffer | 3.90 | 5.4 |
|
||||
| gm | file | file | 3.94 | 5.5 |
|
||||
| imagemagick | file | file | 4.30 | 6.0 |
|
||||
| sharp | stream | stream | 23.65 | 32.8 |
|
||||
| sharp | file | file | 24.66 | 34.3 |
|
||||
| sharp | buffer | buffer | 25.14 | 34.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.
|
||||
|
||||
## Contenders
|
||||
|
||||
* [jimp](https://www.npmjs.com/package/jimp) v0.22.10 - Image processing in pure JavaScript.
|
||||
* [imagemagick](https://www.npmjs.com/package/imagemagick) v0.1.3 - Supports filesystem only and "*has been unmaintained for a long time*".
|
||||
* [gm](https://www.npmjs.com/package/gm) v1.25.0 - Fully featured wrapper around GraphicsMagick's `gm` command line utility.
|
||||
* [@squoosh/lib](https://www.npmjs.com/package/@squoosh/lib) v0.5.3 - Image libraries transpiled to WebAssembly, includes GPLv3 code, but "*Project no longer maintained*".
|
||||
* [@squoosh/cli](https://www.npmjs.com/package/@squoosh/cli) v0.7.3 - Command line wrapper around `@squoosh/lib`, avoids GPLv3 by spawning process, but "*Project no longer maintained*".
|
||||
* sharp v0.33.0 / libvips v8.15.0 - Caching within libvips disabled to ensure a fair comparison.
|
||||
|
||||
## Environment
|
||||
|
||||
### AMD64
|
||||
|
||||
* AWS EC2 us-east-2 [c7a.xlarge](https://aws.amazon.com/ec2/instance-types/c7a/) (4x AMD EPYC 9R14)
|
||||
* Ubuntu 23.10 [13f233a16be2](https://hub.docker.com/layers/library/ubuntu/23.10/images/sha256-13f233a16be210b57907b98b0d927ceff7571df390701e14fe1f3901b2c4a4d7)
|
||||
* Node.js 20.10.0
|
||||
|
||||
### ARM64
|
||||
|
||||
* AWS EC2 us-east-2 [c7g.xlarge](https://aws.amazon.com/ec2/instance-types/c7g/) (4x ARM Graviton3)
|
||||
* Ubuntu 23.10 [7708743264cb](https://hub.docker.com/layers/library/ubuntu/23.10/images/sha256-7708743264cbb7f6cf7fc13e915faece45a6cdda455748bc55e58e8de3d27b63)
|
||||
* Node.js 20.10.0
|
||||
|
||||
## Task: JPEG
|
||||
|
||||
Decompress a 2725x2225 JPEG image,
|
||||
resize to 720x588 using Lanczos 3 resampling (where available),
|
||||
then compress to JPEG at a "quality" setting of 80.
|
||||
|
||||
Note: jimp does not support Lanczos 3, bicubic resampling used instead.
|
||||
|
||||
#### Results: JPEG (AMD64)
|
||||
|
||||
| Module | Input | Output | Ops/sec | Speed-up |
|
||||
| :----------------- | :----- | :----- | ------: | -------: |
|
||||
| jimp | buffer | buffer | 0.84 | 1.0 |
|
||||
| squoosh-cli | file | file | 1.54 | 1.8 |
|
||||
| squoosh-lib | buffer | buffer | 2.24 | 2.7 |
|
||||
| imagemagick | file | file | 11.75 | 14.0 |
|
||||
| gm | buffer | buffer | 12.66 | 15.1 |
|
||||
| gm | file | file | 12.72 | 15.1 |
|
||||
| sharp | stream | stream | 48.31 | 57.5 |
|
||||
| sharp | file | file | 51.42 | 61.2 |
|
||||
| sharp | buffer | buffer | 52.41 | 62.4 |
|
||||
|
||||
#### Results: JPEG (ARM64)
|
||||
|
||||
| Module | Input | Output | Ops/sec | Speed-up |
|
||||
| :----------------- | :----- | :----- | ------: | -------: |
|
||||
| jimp | buffer | buffer | 0.88 | 1.0 |
|
||||
| squoosh-cli | file | file | 1.18 | 1.3 |
|
||||
| squoosh-lib | buffer | buffer | 1.99 | 2.3 |
|
||||
| gm | buffer | buffer | 6.06 | 6.9 |
|
||||
| gm | file | file | 10.81 | 12.3 |
|
||||
| imagemagick | file | file | 10.95 | 12.4 |
|
||||
| sharp | stream | stream | 33.15 | 37.7 |
|
||||
| sharp | file | file | 34.99 | 39.8 |
|
||||
| sharp | buffer | buffer | 36.05 | 41.0 |
|
||||
|
||||
## Task: PNG
|
||||
|
||||
Decompress a 2048x1536 RGBA PNG image,
|
||||
premultiply the alpha channel,
|
||||
resize to 720x540 using Lanczos 3 resampling (where available),
|
||||
unpremultiply then compress as PNG with a "default" zlib compression level of 6
|
||||
and without adaptive filtering.
|
||||
|
||||
Note: jimp does not support premultiply/unpremultiply.
|
||||
|
||||
### Results: PNG (AMD64)
|
||||
|
||||
| Module | Input | Output | Ops/sec | Speed-up |
|
||||
| :----------------- | :----- | :----- | ------: | -------: |
|
||||
| squoosh-cli | file | file | 0.34 | 1.0 |
|
||||
| squoosh-lib | buffer | buffer | 0.51 | 1.5 |
|
||||
| jimp | buffer | buffer | 3.59 | 10.6 |
|
||||
| gm | file | file | 8.54 | 25.1 |
|
||||
| imagemagick | file | file | 9.23 | 27.1 |
|
||||
| sharp | file | file | 25.43 | 74.8 |
|
||||
| sharp | buffer | buffer | 25.70 | 75.6 |
|
||||
|
||||
### Results: PNG (ARM64)
|
||||
|
||||
| Module | Input | Output | Ops/sec | Speed-up |
|
||||
| :----------------- | :----- | :----- | ------: | -------: |
|
||||
| squoosh-cli | file | file | 0.33 | 1.0 |
|
||||
| squoosh-lib | buffer | buffer | 0.46 | 1.4 |
|
||||
| jimp | buffer | buffer | 3.51 | 10.6 |
|
||||
| gm | file | file | 7.47 | 22.6 |
|
||||
| imagemagick | file | file | 8.06 | 24.4 |
|
||||
| sharp | file | file | 17.31 | 52.5 |
|
||||
| sharp | buffer | buffer | 17.66 | 53.5 |
|
||||
|
||||
## Running the benchmark test
|
||||
|
||||
Requires _ImageMagick_, _GraphicsMagick_ and _Mapnik_:
|
||||
|
||||
```sh
|
||||
brew install imagemagick
|
||||
brew install graphicsmagick
|
||||
brew install mapnik
|
||||
```
|
||||
|
||||
```sh
|
||||
sudo apt-get install imagemagick libmagick++-dev graphicsmagick libmapnik-dev
|
||||
```
|
||||
|
||||
```sh
|
||||
sudo yum install ImageMagick-devel ImageMagick-c++-devel GraphicsMagick mapnik-devel
|
||||
```
|
||||
Requires Docker.
|
||||
|
||||
```sh
|
||||
git clone https://github.com/lovell/sharp.git
|
||||
cd sharp
|
||||
npm install
|
||||
cd test/bench
|
||||
npm install
|
||||
npm test
|
||||
cd sharp/test/bench
|
||||
./run-with-docker.sh
|
||||
```
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,14 +1,18 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const { extractDescription, extractKeywords } = require('./extract');
|
||||
const path = require('path');
|
||||
const { extractDescription, extractKeywords, extractParameters } = require('./extract');
|
||||
|
||||
const searchIndex = [];
|
||||
|
||||
// Install
|
||||
const contents = fs.readFileSync(`${__dirname}/../install.md`, 'utf8');
|
||||
const contents = fs.readFileSync(path.join(__dirname, '..', 'install.md'), 'utf8');
|
||||
const matches = contents.matchAll(
|
||||
/## (?<title>[A-Za-z ]+)\n\n(?<body>[^#]+)/gs
|
||||
/## (?<title>[A-Za-z0-9 ]+)\n\n(?<body>[^#]+)/gs
|
||||
);
|
||||
for (const match of matches) {
|
||||
const { title, body } = match.groups;
|
||||
@@ -34,26 +38,27 @@ for (const match of matches) {
|
||||
'colour',
|
||||
'utility'
|
||||
].forEach((section) => {
|
||||
const contents = fs.readFileSync(`${__dirname}/../api-${section}.md`, 'utf8');
|
||||
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/gs
|
||||
/## (?<title>[A-Za-z]+)\n[^\n]+\n(?<firstparagraph>.+?)\n\n.+?(?<parameters>\| Param .+?\n\n)?\*\*Example/gs
|
||||
);
|
||||
for (const match of matches) {
|
||||
const { title, firstparagraph } = match.groups;
|
||||
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}`),
|
||||
k: extractKeywords(`${title} ${description} ${parameterNames}`),
|
||||
l: `/api-${section}#${title.toLowerCase()}`
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
fs.writeFileSync(
|
||||
`${__dirname}/../search-index.json`,
|
||||
path.join(__dirname, '..', 'search-index.json'),
|
||||
JSON.stringify(searchIndex)
|
||||
);
|
||||
|
||||
@@ -1,80 +1,34 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const stopWords = [
|
||||
'a',
|
||||
'about',
|
||||
'all',
|
||||
'already',
|
||||
'always',
|
||||
'an',
|
||||
'and',
|
||||
'any',
|
||||
'are',
|
||||
'as',
|
||||
'at',
|
||||
'be',
|
||||
'been',
|
||||
'by',
|
||||
'can',
|
||||
'do',
|
||||
'does',
|
||||
'each',
|
||||
'either',
|
||||
'etc',
|
||||
'for',
|
||||
'from',
|
||||
'get',
|
||||
'gets',
|
||||
'has',
|
||||
'have',
|
||||
'how',
|
||||
'if',
|
||||
'in',
|
||||
'is',
|
||||
'it',
|
||||
'its',
|
||||
'may',
|
||||
'more',
|
||||
'much',
|
||||
'no',
|
||||
'not',
|
||||
'of',
|
||||
'on',
|
||||
'or',
|
||||
'over',
|
||||
'set',
|
||||
'sets',
|
||||
'should',
|
||||
'that',
|
||||
'the',
|
||||
'their',
|
||||
'there',
|
||||
'therefore',
|
||||
'these',
|
||||
'this',
|
||||
'to',
|
||||
'use',
|
||||
'using',
|
||||
'when',
|
||||
'which',
|
||||
'will',
|
||||
'with'
|
||||
];
|
||||
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, ' ')
|
||||
.substr(0, 140)
|
||||
.substring(0, 200)
|
||||
.trim();
|
||||
|
||||
const extractKeywords = (str) =>
|
||||
str
|
||||
.split(/[ -/]/)
|
||||
.map((word) => word.toLowerCase().replace(/[^a-z]/g, ''))
|
||||
.filter((word) => word.length > 2 && !stopWords.includes(word))
|
||||
const extractParameters = (str) =>
|
||||
[...str.matchAll(/options\.(?<name>[^.`\] ]+)/gs)]
|
||||
.map((match) => match.groups.name)
|
||||
.map((name) => name.replace(/([A-Z])/g, ' $1').toLowerCase())
|
||||
.join(' ');
|
||||
|
||||
module.exports = { extractDescription, extractKeywords };
|
||||
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 };
|
||||
|
||||
135
docs/search-index/stop-words.js
Normal file
135
docs/search-index/stop-words.js
Normal file
@@ -0,0 +1,135 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
module.exports = [
|
||||
'about',
|
||||
'after',
|
||||
'all',
|
||||
'allows',
|
||||
'already',
|
||||
'also',
|
||||
'alternative',
|
||||
'always',
|
||||
'and',
|
||||
'any',
|
||||
'are',
|
||||
'available',
|
||||
'based',
|
||||
'been',
|
||||
'before',
|
||||
'best',
|
||||
'both',
|
||||
'call',
|
||||
'callback',
|
||||
'can',
|
||||
'containing',
|
||||
'contains',
|
||||
'created',
|
||||
'current',
|
||||
'date',
|
||||
'default',
|
||||
'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',
|
||||
'now',
|
||||
'occur',
|
||||
'occurs',
|
||||
'one',
|
||||
'options',
|
||||
'other',
|
||||
'out',
|
||||
'over',
|
||||
'part',
|
||||
'perform',
|
||||
'performs',
|
||||
'please',
|
||||
'pre',
|
||||
'previously',
|
||||
'produce',
|
||||
'provide',
|
||||
'provided',
|
||||
'ready',
|
||||
'requires',
|
||||
'requiresharp',
|
||||
'returned',
|
||||
'run',
|
||||
'same',
|
||||
'see',
|
||||
'set',
|
||||
'sets',
|
||||
'sharp',
|
||||
'should',
|
||||
'since',
|
||||
'site',
|
||||
'some',
|
||||
'specified',
|
||||
'spelling',
|
||||
'such',
|
||||
'support',
|
||||
'supported',
|
||||
'sure',
|
||||
'take',
|
||||
'task',
|
||||
'than',
|
||||
'that',
|
||||
'the',
|
||||
'their',
|
||||
'then',
|
||||
'there',
|
||||
'therefore',
|
||||
'these',
|
||||
'this',
|
||||
'under',
|
||||
'unless',
|
||||
'unmaintained',
|
||||
'unsuitable',
|
||||
'until',
|
||||
'use',
|
||||
'used',
|
||||
'using',
|
||||
'value',
|
||||
'values',
|
||||
'via',
|
||||
'were',
|
||||
'when',
|
||||
'which',
|
||||
'while',
|
||||
'will',
|
||||
'with',
|
||||
'without',
|
||||
'you',
|
||||
'your'
|
||||
];
|
||||
41
install/check.js
Normal file
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 {
|
||||
require('node-addon-api');
|
||||
log('Found node-addon-api');
|
||||
} catch (err) {
|
||||
log('Please add node-addon-api to your dependencies');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const gyp = require('node-gyp');
|
||||
log(`Found node-gyp version ${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()) {
|
||||
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 npmLog = require('npmlog');
|
||||
|
||||
const minimumLibvipsVersion = libvips.minimumLibvipsVersion;
|
||||
|
||||
const platform = process.env.npm_config_platform || process.platform;
|
||||
if (platform === 'win32') {
|
||||
const buildDir = path.join(__dirname, '..', 'build');
|
||||
const buildReleaseDir = path.join(buildDir, 'Release');
|
||||
npmLog.info('sharp', `Creating ${buildReleaseDir}`);
|
||||
try {
|
||||
libvips.mkdirSync(buildDir);
|
||||
libvips.mkdirSync(buildReleaseDir);
|
||||
} catch (err) {}
|
||||
const vendorLibDir = path.join(__dirname, '..', 'vendor', minimumLibvipsVersion, 'lib');
|
||||
npmLog.info('sharp', `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) {
|
||||
npmLog.error('sharp', err.message);
|
||||
}
|
||||
}
|
||||
@@ -1,124 +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 detectLibc = require('detect-libc');
|
||||
const npmLog = require('npmlog');
|
||||
const semver = require('semver');
|
||||
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.29',
|
||||
x64: '2.17'
|
||||
};
|
||||
|
||||
const { minimumLibvipsVersion, minimumLibvipsVersionLabelled } = libvips;
|
||||
const distHost = process.env.npm_config_sharp_libvips_binary_host || 'https://github.com/lovell/sharp-libvips/releases/download';
|
||||
const distBaseUrl = process.env.npm_config_sharp_dist_base_url || process.env.SHARP_DIST_BASE_URL || `${distHost}/v${minimumLibvipsVersionLabelled}/`;
|
||||
|
||||
const fail = function (err) {
|
||||
npmLog.error('sharp', err.message);
|
||||
if (err.code === 'EACCES') {
|
||||
npmLog.info('sharp', 'Are you trying to install as a root or sudo user? Try again with the --unsafe-perm flag');
|
||||
}
|
||||
npmLog.info('sharp', 'Attempting to build from source via node-gyp but this may fail due to the above error');
|
||||
npmLog.info('sharp', 'Please see https://sharp.pixelplumbing.com/install for required dependencies');
|
||||
process.exit(1);
|
||||
};
|
||||
|
||||
const extractTarball = function (tarPath) {
|
||||
const vendorPath = path.join(__dirname, '..', 'vendor');
|
||||
libvips.mkdirSync(vendorPath);
|
||||
const versionedVendorPath = path.join(vendorPath, minimumLibvipsVersion);
|
||||
libvips.mkdirSync(versionedVendorPath);
|
||||
stream.pipeline(
|
||||
fs.createReadStream(tarPath),
|
||||
new zlib.BrotliDecompress(),
|
||||
tarFs.extract(versionedVendorPath),
|
||||
function (err) {
|
||||
if (err) {
|
||||
if (/unexpected end of file/.test(err.message)) {
|
||||
npmLog.error('sharp', `Please delete ${tarPath} as it is not a valid tarball`);
|
||||
}
|
||||
fail(err);
|
||||
}
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
try {
|
||||
const useGlobalLibvips = libvips.useGlobalLibvips();
|
||||
if (useGlobalLibvips) {
|
||||
const globalLibvipsVersion = libvips.globalLibvipsVersion();
|
||||
npmLog.info('sharp', `Detected globally-installed libvips v${globalLibvipsVersion}`);
|
||||
npmLog.info('sharp', 'Building from source via node-gyp');
|
||||
process.exit(1);
|
||||
} else if (libvips.hasVendoredLibvips()) {
|
||||
npmLog.info('sharp', `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 === 'freebsd-x64' || platformAndArch === 'openbsd-x64' || platformAndArch === 'sunos-x64') {
|
||||
throw new Error(`BSD/SunOS systems require manual installation of libvips >= ${minimumLibvipsVersion}`);
|
||||
}
|
||||
if (detectLibc.family === detectLibc.GLIBC && detectLibc.version) {
|
||||
if (semver.lt(`${detectLibc.version}.0`, `${minimumGlibcVersionByArch[arch]}.0`)) {
|
||||
throw new Error(`Use with glibc ${detectLibc.version} requires manual installation of libvips >= ${minimumLibvipsVersion}`);
|
||||
}
|
||||
}
|
||||
// Download to per-process temporary file
|
||||
const tarFilename = ['libvips', minimumLibvipsVersion, platformAndArch].join('-') + '.tar.br';
|
||||
const tarPathCache = path.join(libvips.cachePath(), tarFilename);
|
||||
if (fs.existsSync(tarPathCache)) {
|
||||
npmLog.info('sharp', `Using cached ${tarPathCache}`);
|
||||
extractTarball(tarPathCache);
|
||||
} else {
|
||||
const tarPathTemp = path.join(os.tmpdir(), `${process.pid}-${tarFilename}`);
|
||||
const tmpFile = fs.createWriteStream(tarPathTemp);
|
||||
const url = distBaseUrl + tarFilename;
|
||||
npmLog.info('sharp', `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 {
|
||||
response
|
||||
.on('error', fail)
|
||||
.pipe(tmpFile);
|
||||
}
|
||||
});
|
||||
tmpFile
|
||||
.on('error', fail)
|
||||
.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);
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const { spawnSync } = require('child_process');
|
||||
|
||||
const { prebuild_upload: hasToken, APPVEYOR_REPO_TAG_NAME, TRAVIS_TAG } = process.env;
|
||||
|
||||
if (hasToken && (APPVEYOR_REPO_TAG_NAME || TRAVIS_TAG)) {
|
||||
spawnSync('node',
|
||||
['./node_modules/prebuild/bin.js', '--runtime', 'napi', '--target', '3'],
|
||||
{ shell: true, stdio: 'inherit' }
|
||||
);
|
||||
}
|
||||
40
lib/agent.js
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
|
||||
? `${proxy.username}:${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';
|
||||
|
||||
const is = require('./is');
|
||||
@@ -15,6 +18,8 @@ const bool = {
|
||||
/**
|
||||
* Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel.
|
||||
*
|
||||
* See also {@link /api-operation#flatten|flatten}.
|
||||
*
|
||||
* @example
|
||||
* sharp('rgba.png')
|
||||
* .removeAlpha()
|
||||
@@ -30,21 +35,39 @@ function removeAlpha () {
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure alpha channel, if missing. The added alpha channel will be fully opaque. This is a no-op if the image already has an alpha channel.
|
||||
* Ensure the output image has an alpha transparency channel.
|
||||
* If missing, the added alpha channel will have the specified
|
||||
* transparency level, defaulting to fully-opaque (1).
|
||||
* This is a no-op if the image already has an alpha channel.
|
||||
*
|
||||
* @since 0.21.2
|
||||
*
|
||||
* @example
|
||||
* sharp('rgb.jpg')
|
||||
* // rgba.png will be a 4 channel image with a fully-opaque alpha channel
|
||||
* await sharp('rgb.jpg')
|
||||
* .ensureAlpha()
|
||||
* .toFile('rgba.png', function(err, info) {
|
||||
* // rgba.png is a 4 channel image with a fully opaque alpha channel
|
||||
* });
|
||||
* .toFile('rgba.png')
|
||||
*
|
||||
* @example
|
||||
* // rgba is a 4 channel image with a fully-transparent alpha channel
|
||||
* const rgba = await sharp(rgb)
|
||||
* .ensureAlpha(0)
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {number} [alpha=1] - alpha transparency level (0=fully-transparent, 1=fully-opaque)
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid alpha transparency level
|
||||
*/
|
||||
function ensureAlpha () {
|
||||
this.options.ensureAlpha = true;
|
||||
function ensureAlpha (alpha) {
|
||||
if (is.defined(alpha)) {
|
||||
if (is.number(alpha) && is.inRange(alpha, 0, 1)) {
|
||||
this.options.ensureAlpha = alpha;
|
||||
} else {
|
||||
throw is.invalidParameterError('alpha', 'number between 0 and 1', alpha);
|
||||
}
|
||||
} else {
|
||||
this.options.ensureAlpha = 1;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -52,13 +75,17 @@ function ensureAlpha () {
|
||||
* Extract a single channel from a multi-channel image.
|
||||
*
|
||||
* @example
|
||||
* sharp(input)
|
||||
* // green.jpg is a greyscale image containing the green channel of the input
|
||||
* await sharp(input)
|
||||
* .extractChannel('green')
|
||||
* .toColourspace('b-w')
|
||||
* .toFile('green.jpg', function(err, info) {
|
||||
* // info.channels === 1
|
||||
* // green.jpg is a greyscale image containing the green channel of the input
|
||||
* });
|
||||
* .toFile('green.jpg');
|
||||
*
|
||||
* @example
|
||||
* // red1 is the red value of the first pixel, red2 the second pixel etc.
|
||||
* const [red1, red2, ...] = await sharp(input)
|
||||
* .extractChannel(0)
|
||||
* .raw()
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {number|string} channel - zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`.
|
||||
* @returns {Sharp}
|
||||
@@ -85,7 +112,7 @@ function extractChannel (channel) {
|
||||
* - sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha.
|
||||
* - CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha.
|
||||
*
|
||||
* Buffers may be any of the image formats supported by sharp: JPEG, PNG, WebP, GIF, SVG, TIFF or raw pixel image data.
|
||||
* Buffers may be any of the image formats supported by sharp.
|
||||
* For raw pixel input, the `options` object should contain a `raw` attribute, which follows the format of the attribute of the same name in the `sharp()` constructor.
|
||||
*
|
||||
* @param {Array<string|Buffer>|string|Buffer} images - one or more images (file paths, Buffers).
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const color = require('color');
|
||||
@@ -16,17 +19,20 @@ 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.
|
||||
*
|
||||
* @param {string|Object} rgb - parsed by the [color](https://www.npmjs.org/package/color) module to extract chroma values.
|
||||
* @example
|
||||
* const output = await sharp(input)
|
||||
* .tint({ r: 255, g: 240, b: 16 })
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {string|Object} tint - Parsed by the [color](https://www.npmjs.org/package/color) module.
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameter
|
||||
*/
|
||||
function tint (rgb) {
|
||||
const colour = color(rgb);
|
||||
this.options.tintA = colour.a();
|
||||
this.options.tintB = colour.b();
|
||||
function tint (tint) {
|
||||
this._setBackgroundColourOption('tint', tint);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -37,6 +43,10 @@ function tint (rgb) {
|
||||
* 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.
|
||||
*
|
||||
* @example
|
||||
* const output = await sharp(input).greyscale().toBuffer();
|
||||
*
|
||||
* @param {Boolean} [greyscale=true]
|
||||
* @returns {Sharp}
|
||||
*/
|
||||
@@ -54,10 +64,57 @@ function grayscale (grayscale) {
|
||||
return this.greyscale(grayscale);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the pipeline colourspace.
|
||||
*
|
||||
* The input image will be converted to the provided colourspace at the start of the pipeline.
|
||||
* All operations will use this colourspace before converting to the output colourspace,
|
||||
* as defined by {@link #tocolourspace|toColourspace}.
|
||||
*
|
||||
* This feature is experimental and has not yet been fully-tested with all operations.
|
||||
*
|
||||
* @since 0.29.0
|
||||
*
|
||||
* @example
|
||||
* // Run pipeline in 16 bits per channel RGB while converting final result to 8 bits per channel sRGB.
|
||||
* await sharp(input)
|
||||
* .pipelineColourspace('rgb16')
|
||||
* .toColourspace('srgb')
|
||||
* .toFile('16bpc-pipeline-to-8bpc-output.png')
|
||||
*
|
||||
* @param {string} [colourspace] - pipeline colourspace e.g. `rgb16`, `scrgb`, `lab`, `grey16` [...](https://github.com/libvips/libvips/blob/41cff4e9d0838498487a00623462204eb10ee5b8/libvips/iofuncs/enumtypes.c#L774)
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function pipelineColourspace (colourspace) {
|
||||
if (!is.string(colourspace)) {
|
||||
throw is.invalidParameterError('colourspace', 'string', colourspace);
|
||||
}
|
||||
this.options.colourspacePipeline = colourspace;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Alternative spelling of `pipelineColourspace`.
|
||||
* @param {string} [colorspace] - pipeline colorspace.
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function pipelineColorspace (colorspace) {
|
||||
return this.pipelineColourspace(colorspace);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the output colourspace.
|
||||
* By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.
|
||||
* @param {string} [colourspace] - output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/libvips/libvips/blob/master/libvips/iofuncs/enumtypes.c#L568)
|
||||
*
|
||||
* @example
|
||||
* // Output 16 bits per pixel RGB
|
||||
* await sharp(input)
|
||||
* .toColourspace('rgb16')
|
||||
* .toFile('16-bpp.png')
|
||||
*
|
||||
* @param {string} [colourspace] - output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/libvips/libvips/blob/3c0bfdf74ce1dc37a6429bed47fa76f16e2cd70a/libvips/iofuncs/enumtypes.c#L777-L794)
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
@@ -112,6 +169,8 @@ module.exports = function (Sharp) {
|
||||
tint,
|
||||
greyscale,
|
||||
grayscale,
|
||||
pipelineColourspace,
|
||||
pipelineColorspace,
|
||||
toColourspace,
|
||||
toColorspace,
|
||||
// Private
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const is = require('./is');
|
||||
@@ -43,6 +46,9 @@ const blend = {
|
||||
* 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, rotate or extract 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`,
|
||||
@@ -50,12 +56,27 @@ const blend = {
|
||||
* `hard-light`, `soft-light`, `difference`, `exclusion`.
|
||||
*
|
||||
* More information about blend modes can be found at
|
||||
* https://libvips.github.io/libvips/API/current/libvips-conversion.html#VipsBlendMode
|
||||
* https://www.libvips.org/API/current/libvips-conversion.html#VipsBlendMode
|
||||
* and https://www.cairographics.org/operators/
|
||||
*
|
||||
* @since 0.22.0
|
||||
*
|
||||
* @example
|
||||
* await sharp(background)
|
||||
* .composite([
|
||||
* { input: layer1, gravity: 'northwest' },
|
||||
* { input: layer2, gravity: 'southeast' },
|
||||
* ])
|
||||
* .toFile('combined.png');
|
||||
*
|
||||
* @example
|
||||
* const output = await sharp('input.gif', { animated: true })
|
||||
* .composite([
|
||||
* { input: 'overlay.png', tile: true, blend: 'saturate' }
|
||||
* ])
|
||||
* .toBuffer();
|
||||
*
|
||||
* @example
|
||||
* sharp('input.png')
|
||||
* .rotate(180)
|
||||
* .resize(300)
|
||||
@@ -78,17 +99,31 @@ const blend = {
|
||||
* @param {Number} [images[].input.create.height]
|
||||
* @param {Number} [images[].input.create.channels] - 3-4
|
||||
* @param {String|Object} [images[].input.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
|
||||
* @param {Object} [images[].input.text] - describes a new text image to be created.
|
||||
* @param {string} [images[].input.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.
|
||||
* @param {string} [images[].input.text.font] - font name to render with.
|
||||
* @param {string} [images[].input.text.fontfile] - absolute filesystem path to a font file that can be used by `font`.
|
||||
* @param {number} [images[].input.text.width=0] - integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries.
|
||||
* @param {number} [images[].input.text.height=0] - integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0.
|
||||
* @param {string} [images[].input.text.align='left'] - text alignment (`'left'`, `'centre'`, `'center'`, `'right'`).
|
||||
* @param {boolean} [images[].input.text.justify=false] - set this to true to apply justification to the text.
|
||||
* @param {number} [images[].input.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified.
|
||||
* @param {boolean} [images[].input.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like `<span foreground="red">Red!</span>`.
|
||||
* @param {number} [images[].input.text.spacing=0] - text line height in points. Will use the font line height if none is specified.
|
||||
* @param {String} [images[].blend='over'] - how to blend this image with the image below.
|
||||
* @param {String} [images[].gravity='centre'] - gravity at which to place the overlay.
|
||||
* @param {Number} [images[].top] - the pixel offset from the top edge.
|
||||
* @param {Number} [images[].left] - the pixel offset from the left edge.
|
||||
* @param {Boolean} [images[].tile=false] - set to true to repeat the overlay image across the entire image with the given `gravity`.
|
||||
* @param {Boolean} [images[].premultiplied=false] - set to true to avoid 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 {Object} [images[].raw] - describes overlay when using raw pixel data.
|
||||
* @param {Number} [images[].raw.width]
|
||||
* @param {Number} [images[].raw.height]
|
||||
* @param {Number} [images[].raw.channels]
|
||||
* @param {boolean} [images[].animated=false] - Set to `true` to read all frames/pages of an animated image.
|
||||
* @param {string} [images[].failOn='warning'] - @see {@link /api-constructor#parameters|constructor parameters}
|
||||
* @param {number|boolean} [images[].limitInputPixels=268402689] - @see {@link /api-constructor#parameters|constructor parameters}
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
@@ -105,8 +140,9 @@ function composite (images) {
|
||||
input: this._createInputDescriptor(image.input, inputOptions, { allowStream: false }),
|
||||
blend: 'over',
|
||||
tile: false,
|
||||
left: -1,
|
||||
top: -1,
|
||||
left: 0,
|
||||
top: 0,
|
||||
hasOffset: false,
|
||||
gravity: 0,
|
||||
premultiplied: false
|
||||
};
|
||||
@@ -125,21 +161,23 @@ function composite (images) {
|
||||
}
|
||||
}
|
||||
if (is.defined(image.left)) {
|
||||
if (is.integer(image.left) && image.left >= 0) {
|
||||
if (is.integer(image.left)) {
|
||||
composite.left = image.left;
|
||||
} else {
|
||||
throw is.invalidParameterError('left', 'positive integer', image.left);
|
||||
throw is.invalidParameterError('left', 'integer', image.left);
|
||||
}
|
||||
}
|
||||
if (is.defined(image.top)) {
|
||||
if (is.integer(image.top) && image.top >= 0) {
|
||||
if (is.integer(image.top)) {
|
||||
composite.top = image.top;
|
||||
} else {
|
||||
throw is.invalidParameterError('top', 'positive integer', image.top);
|
||||
throw is.invalidParameterError('top', 'integer', image.top);
|
||||
}
|
||||
}
|
||||
if (composite.left !== composite.top && Math.min(composite.left, composite.top) === -1) {
|
||||
if (is.defined(image.top) !== is.defined(image.left)) {
|
||||
throw new Error('Expected both left and top to be set');
|
||||
} else {
|
||||
composite.hasOffset = is.integer(image.top) && is.integer(image.left);
|
||||
}
|
||||
if (is.defined(image.gravity)) {
|
||||
if (is.integer(image.gravity) && is.inRange(image.gravity, 0, 8)) {
|
||||
@@ -157,7 +195,6 @@ function composite (images) {
|
||||
throw is.invalidParameterError('premultiplied', 'boolean', image.premultiplied);
|
||||
}
|
||||
}
|
||||
|
||||
return composite;
|
||||
});
|
||||
return this;
|
||||
|
||||
@@ -1,38 +1,13 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const util = require('util');
|
||||
const stream = require('stream');
|
||||
const util = require('node:util');
|
||||
const stream = require('node:stream');
|
||||
const is = require('./is');
|
||||
|
||||
require('./libvips').hasVendoredLibvips();
|
||||
|
||||
/* istanbul ignore next */
|
||||
try {
|
||||
require('../build/Release/sharp.node');
|
||||
} catch (err) {
|
||||
// Bail early if bindings aren't available
|
||||
const help = ['', 'Something went wrong installing the "sharp" module', '', err.message, ''];
|
||||
if (/NODE_MODULE_VERSION/.test(err.message)) {
|
||||
help.push('- Ensure the version of Node.js used at install time matches that used at runtime');
|
||||
} else if (/invalid ELF header/.test(err.message)) {
|
||||
help.push(`- Ensure "${process.platform}" is used at install time as well as runtime`);
|
||||
} else if (/dylib/.test(err.message) && /Incompatible library version/.test(err.message)) {
|
||||
help.push('- Run "brew update && brew upgrade vips"');
|
||||
} else if (/Cannot find module/.test(err.message)) {
|
||||
help.push('- Run "npm rebuild --verbose sharp" and look for errors');
|
||||
} else {
|
||||
help.push(
|
||||
'- Remove the "node_modules/sharp" directory then run',
|
||||
' "npm install --ignore-scripts=false --verbose" and look for errors'
|
||||
);
|
||||
}
|
||||
help.push(
|
||||
'- Consult the installation documentation at https://sharp.pixelplumbing.com/install',
|
||||
'- Search for this error at https://github.com/lovell/sharp/issues', ''
|
||||
);
|
||||
const error = help.join('\n');
|
||||
throw new Error(error);
|
||||
}
|
||||
require('./sharp');
|
||||
|
||||
// Use NODE_DEBUG=sharp to enable libvips warnings
|
||||
const debuglog = util.debuglog('sharp');
|
||||
@@ -40,13 +15,17 @@ const debuglog = util.debuglog('sharp');
|
||||
/**
|
||||
* Constructor factory to create an instance of `sharp`, to which further methods are chained.
|
||||
*
|
||||
* JPEG, PNG, WebP or TIFF format image data can be streamed out from this object.
|
||||
* JPEG, PNG, WebP, GIF, AVIF or TIFF format image data can be streamed out from this object.
|
||||
* When using Stream based output, derived attributes are available from the `info` event.
|
||||
*
|
||||
* Non-critical problems encountered during processing are emitted as `warning` events.
|
||||
*
|
||||
* Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.
|
||||
*
|
||||
* When loading more than one page/frame of an animated image,
|
||||
* these are combined as a vertically-stacked "toilet roll" image
|
||||
* where the overall height is the `pageHeight` multiplied by the number of `pages`.
|
||||
*
|
||||
* @constructs Sharp
|
||||
*
|
||||
* @emits Sharp#info
|
||||
@@ -61,19 +40,21 @@ const debuglog = util.debuglog('sharp');
|
||||
* });
|
||||
*
|
||||
* @example
|
||||
* // Read image data from readableStream,
|
||||
* // 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
|
||||
* var transformer = sharp()
|
||||
* const { body } = fetch('https://...');
|
||||
* const readableStream = Readable.fromWeb(body);
|
||||
* const transformer = sharp()
|
||||
* .resize(300)
|
||||
* .on('info', function(info) {
|
||||
* console.log('Image height is ' + info.height);
|
||||
* .on('info', ({ height }) => {
|
||||
* console.log(`Image height is ${height}`);
|
||||
* });
|
||||
* readableStream.pipe(transformer).pipe(writableStream);
|
||||
*
|
||||
* @example
|
||||
* // Create a blank 300x200 PNG image of semi-transluent red pixels
|
||||
* // Create a blank 300x200 PNG image of semi-translucent red pixels
|
||||
* sharp({
|
||||
* create: {
|
||||
* width: 300,
|
||||
@@ -90,32 +71,102 @@ const debuglog = util.debuglog('sharp');
|
||||
* // Convert an animated GIF to an animated WebP
|
||||
* await sharp('in.gif', { animated: true }).toFile('out.webp');
|
||||
*
|
||||
* @param {(Buffer|string)} [input] - if present, can be
|
||||
* a Buffer containing JPEG, PNG, WebP, GIF, SVG, TIFF or raw pixel image data, or
|
||||
* a String containing the filesystem path to an JPEG, PNG, WebP, GIF, SVG or TIFF image file.
|
||||
* JPEG, PNG, WebP, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present.
|
||||
* @example
|
||||
* // Read a raw array of pixels and save it to a png
|
||||
* const input = Uint8Array.from([255, 255, 255, 0, 0, 0]); // or Uint8ClampedArray
|
||||
* const image = sharp(input, {
|
||||
* // because the input does not contain its dimensions or how many channels it has
|
||||
* // we need to specify it in the constructor options
|
||||
* raw: {
|
||||
* width: 2,
|
||||
* height: 1,
|
||||
* channels: 3
|
||||
* }
|
||||
* });
|
||||
* await image.toFile('my-two-pixels.png');
|
||||
*
|
||||
* @example
|
||||
* // Generate RGB Gaussian noise
|
||||
* await sharp({
|
||||
* create: {
|
||||
* width: 300,
|
||||
* height: 200,
|
||||
* channels: 3,
|
||||
* noise: {
|
||||
* type: 'gaussian',
|
||||
* mean: 128,
|
||||
* sigma: 30
|
||||
* }
|
||||
* }
|
||||
* }).toFile('noise.png');
|
||||
*
|
||||
* @example
|
||||
* // Generate an image from text
|
||||
* await sharp({
|
||||
* text: {
|
||||
* text: 'Hello, world!',
|
||||
* width: 400, // max width
|
||||
* height: 300 // max height
|
||||
* }
|
||||
* }).toFile('text_bw.png');
|
||||
*
|
||||
* @example
|
||||
* // Generate an rgba image from text using pango markup and font
|
||||
* await sharp({
|
||||
* text: {
|
||||
* text: '<span foreground="red">Red!</span><span background="cyan">blue</span>',
|
||||
* font: 'sans',
|
||||
* rgba: true,
|
||||
* dpi: 300
|
||||
* }
|
||||
* }).toFile('text_rgba.png');
|
||||
*
|
||||
* @param {(Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string)} [input] - if present, can be
|
||||
* a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or
|
||||
* a TypedArray containing raw pixel image data, or
|
||||
* a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file.
|
||||
* 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 {boolean} [options.failOnError=true] - by default halt processing and raise an error when loading invalid images.
|
||||
* Set this flag to `false` if you'd rather apply a "best effort" to decode images, even if the data is corrupt or invalid.
|
||||
* @param {string} [options.failOn='warning'] - When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort.
|
||||
* @param {number|boolean} [options.limitInputPixels=268402689] - Do not process input images where the number of pixels
|
||||
* (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted.
|
||||
* An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF).
|
||||
* @param {boolean} [options.sequentialRead=false] - Set this to `true` to use sequential rather than random access where possible.
|
||||
* This can reduce memory usage and might improve performance on some systems.
|
||||
* @param {number} [options.density=72] - number representing the DPI for vector images.
|
||||
* @param {number} [options.pages=1] - number of pages to extract for multi-page input (GIF, TIFF, PDF), use -1 for all pages.
|
||||
* @param {number} [options.page=0] - page number to start extracting from for multi-page input (GIF, TIFF, PDF), zero based.
|
||||
* @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=true] - Set this to `false` to use random access rather than sequential read. Some operations will do this automatically.
|
||||
* @param {number} [options.density=72] - number representing the DPI for vector images in the range 1 to 100000.
|
||||
* @param {number} [options.ignoreIcc=false] - should the embedded ICC profile, if any, be ignored.
|
||||
* @param {number} [options.pages=1] - Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages.
|
||||
* @param {number} [options.page=0] - Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based.
|
||||
* @param {number} [options.subifd=-1] - subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image.
|
||||
* @param {number} [options.level=0] - level to extract from a multi-level input (OpenSlide), zero based.
|
||||
* @param {boolean} [options.animated=false] - Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`).
|
||||
* @param {boolean} [options.animated=false] - Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`.
|
||||
* @param {Object} [options.raw] - describes raw pixel input image data. See `raw()` for pixel ordering.
|
||||
* @param {number} [options.raw.width]
|
||||
* @param {number} [options.raw.height]
|
||||
* @param {number} [options.raw.channels] - 1-4
|
||||
* @param {number} [options.raw.width] - integral number of pixels wide.
|
||||
* @param {number} [options.raw.height] - integral number of pixels high.
|
||||
* @param {number} [options.raw.channels] - integral number of channels, between 1 and 4.
|
||||
* @param {boolean} [options.raw.premultiplied] - specifies that the raw input has already been premultiplied, set to `true`
|
||||
* to avoid sharp premultiplying the image. (optional, default `false`)
|
||||
* @param {Object} [options.create] - describes a new image to be created.
|
||||
* @param {number} [options.create.width]
|
||||
* @param {number} [options.create.height]
|
||||
* @param {number} [options.create.channels] - 3-4
|
||||
* @param {number} [options.create.width] - integral number of pixels wide.
|
||||
* @param {number} [options.create.height] - integral number of pixels high.
|
||||
* @param {number} [options.create.channels] - integral number of channels, either 3 (RGB) or 4 (RGBA).
|
||||
* @param {string|Object} [options.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
|
||||
* @param {Object} [options.create.noise] - describes a noise to be created.
|
||||
* @param {string} [options.create.noise.type] - type of generated noise, currently only `gaussian` is supported.
|
||||
* @param {number} [options.create.noise.mean] - mean of pixels in generated noise.
|
||||
* @param {number} [options.create.noise.sigma] - standard deviation of pixels in generated noise.
|
||||
* @param {Object} [options.text] - describes a new text image to be created.
|
||||
* @param {string} [options.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.
|
||||
* @param {string} [options.text.font] - font name to render with.
|
||||
* @param {string} [options.text.fontfile] - absolute filesystem path to a font file that can be used by `font`.
|
||||
* @param {number} [options.text.width=0] - Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries.
|
||||
* @param {number} [options.text.height=0] - Maximum integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0.
|
||||
* @param {string} [options.text.align='left'] - Alignment style for multi-line text (`'left'`, `'centre'`, `'center'`, `'right'`).
|
||||
* @param {boolean} [options.text.justify=false] - set this to true to apply justification to the text.
|
||||
* @param {number} [options.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified.
|
||||
* @param {boolean} [options.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`.
|
||||
* @param {number} [options.text.spacing=0] - text line height in points. Will use the font line height if none is specified.
|
||||
* @param {string} [options.text.wrap='word'] - word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'.
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
@@ -154,45 +205,70 @@ const Sharp = function (input, options) {
|
||||
extendLeft: 0,
|
||||
extendRight: 0,
|
||||
extendBackground: [0, 0, 0, 255],
|
||||
extendWith: 'background',
|
||||
withoutEnlargement: false,
|
||||
withoutReduction: false,
|
||||
affineMatrix: [],
|
||||
affineBackground: [0, 0, 0, 255],
|
||||
affineIdx: 0,
|
||||
affineIdy: 0,
|
||||
affineOdx: 0,
|
||||
affineOdy: 0,
|
||||
affineInterpolator: this.constructor.interpolators.bilinear,
|
||||
kernel: 'lanczos3',
|
||||
fastShrinkOnLoad: true,
|
||||
// operations
|
||||
tintA: 128,
|
||||
tintB: 128,
|
||||
tint: [-1, 0, 0, 0],
|
||||
flatten: false,
|
||||
flattenBackground: [0, 0, 0],
|
||||
unflatten: false,
|
||||
negate: false,
|
||||
negateAlpha: true,
|
||||
medianSize: 0,
|
||||
blurSigma: 0,
|
||||
sharpenSigma: 0,
|
||||
sharpenFlat: 1,
|
||||
sharpenJagged: 2,
|
||||
sharpenM1: 1,
|
||||
sharpenM2: 2,
|
||||
sharpenX1: 2,
|
||||
sharpenY2: 10,
|
||||
sharpenY3: 20,
|
||||
threshold: 0,
|
||||
thresholdGrayscale: true,
|
||||
trimThreshold: 0,
|
||||
trimBackground: [],
|
||||
trimThreshold: -1,
|
||||
trimLineArt: false,
|
||||
gamma: 0,
|
||||
gammaOut: 0,
|
||||
greyscale: false,
|
||||
normalise: false,
|
||||
normaliseLower: 1,
|
||||
normaliseUpper: 99,
|
||||
claheWidth: 0,
|
||||
claheHeight: 0,
|
||||
claheMaxSlope: 3,
|
||||
brightness: 1,
|
||||
saturation: 1,
|
||||
hue: 0,
|
||||
lightness: 0,
|
||||
booleanBufferIn: null,
|
||||
booleanFileIn: '',
|
||||
joinChannelIn: [],
|
||||
extractChannel: -1,
|
||||
removeAlpha: false,
|
||||
ensureAlpha: false,
|
||||
ensureAlpha: -1,
|
||||
colourspace: 'srgb',
|
||||
colourspacePipeline: 'last',
|
||||
composite: [],
|
||||
// output
|
||||
fileOut: '',
|
||||
formatOut: 'input',
|
||||
streamOut: false,
|
||||
withMetadata: false,
|
||||
keepMetadata: 0,
|
||||
withMetadataOrientation: -1,
|
||||
withMetadataIcc: '',
|
||||
withMetadataDensity: 0,
|
||||
withIccProfile: '',
|
||||
withExif: {},
|
||||
withExifMerge: true,
|
||||
resolveWithObject: false,
|
||||
// output format
|
||||
jpegQuality: 80,
|
||||
@@ -204,31 +280,57 @@ const Sharp = function (input, options) {
|
||||
jpegOptimiseCoding: true,
|
||||
jpegQuantisationTable: 0,
|
||||
pngProgressive: false,
|
||||
pngCompressionLevel: 9,
|
||||
pngCompressionLevel: 6,
|
||||
pngAdaptiveFiltering: false,
|
||||
pngPalette: false,
|
||||
pngQuality: 100,
|
||||
pngColours: 256,
|
||||
pngEffort: 7,
|
||||
pngBitdepth: 8,
|
||||
pngDither: 1,
|
||||
jp2Quality: 80,
|
||||
jp2TileHeight: 512,
|
||||
jp2TileWidth: 512,
|
||||
jp2Lossless: false,
|
||||
jp2ChromaSubsampling: '4:4:4',
|
||||
webpQuality: 80,
|
||||
webpAlphaQuality: 100,
|
||||
webpLossless: false,
|
||||
webpNearLossless: false,
|
||||
webpSmartSubsample: false,
|
||||
webpReductionEffort: 4,
|
||||
webpPreset: 'default',
|
||||
webpEffort: 4,
|
||||
webpMinSize: false,
|
||||
webpMixed: false,
|
||||
gifBitdepth: 8,
|
||||
gifEffort: 7,
|
||||
gifDither: 1,
|
||||
gifInterFrameMaxError: 0,
|
||||
gifInterPaletteMaxError: 3,
|
||||
gifReuse: true,
|
||||
gifProgressive: false,
|
||||
tiffQuality: 80,
|
||||
tiffCompression: 'jpeg',
|
||||
tiffPredictor: 'horizontal',
|
||||
tiffPyramid: false,
|
||||
tiffMiniswhite: false,
|
||||
tiffBitdepth: 8,
|
||||
tiffTile: false,
|
||||
tiffTileHeight: 256,
|
||||
tiffTileWidth: 256,
|
||||
tiffXres: 1.0,
|
||||
tiffYres: 1.0,
|
||||
heifQuality: 80,
|
||||
tiffResolutionUnit: 'inch',
|
||||
heifQuality: 50,
|
||||
heifLossless: false,
|
||||
heifCompression: 'hevc',
|
||||
heifCompression: 'av1',
|
||||
heifEffort: 4,
|
||||
heifChromaSubsampling: '4:4:4',
|
||||
heifBitdepth: 8,
|
||||
jxlDistance: 1,
|
||||
jxlDecodingTier: 0,
|
||||
jxlEffort: 7,
|
||||
jxlLossless: false,
|
||||
rawDepth: 'uchar',
|
||||
tileSize: 256,
|
||||
tileOverlap: 0,
|
||||
tileContainer: 'fs',
|
||||
@@ -238,8 +340,12 @@ const Sharp = function (input, options) {
|
||||
tileAngle: 0,
|
||||
tileSkipBlanks: -1,
|
||||
tileBackground: [255, 255, 255, 255],
|
||||
linearA: 1,
|
||||
linearB: 0,
|
||||
tileCentre: false,
|
||||
tileId: 'https://example.com/iiif',
|
||||
tileBasename: '',
|
||||
timeoutSeconds: 0,
|
||||
linearA: [],
|
||||
linearB: [],
|
||||
// Function to notify of libvips warnings
|
||||
debuglog: warning => {
|
||||
this.emit('warning', warning);
|
||||
@@ -253,7 +359,8 @@ const Sharp = function (input, options) {
|
||||
this.options.input = this._createInputDescriptor(input, options, { allowStream: true });
|
||||
return this;
|
||||
};
|
||||
util.inherits(Sharp, stream.Duplex);
|
||||
Object.setPrototypeOf(Sharp.prototype, stream.Duplex.prototype);
|
||||
Object.setPrototypeOf(Sharp, stream.Duplex);
|
||||
|
||||
/**
|
||||
* Take a "snapshot" of the Sharp instance, returning a new instance.
|
||||
@@ -273,9 +380,7 @@ util.inherits(Sharp, stream.Duplex);
|
||||
* // Using Promises to know when the pipeline is complete
|
||||
* const fs = require("fs");
|
||||
* const got = require("got");
|
||||
* const sharpStream = sharp({
|
||||
* failOnError: false
|
||||
* });
|
||||
* const sharpStream = sharp({ failOn: 'none' });
|
||||
*
|
||||
* const promises = [];
|
||||
*
|
||||
@@ -302,7 +407,7 @@ util.inherits(Sharp, stream.Duplex);
|
||||
* .toFile("optimized-500.webp")
|
||||
* );
|
||||
*
|
||||
* // https://github.com/sindresorhus/got#gotstreamurl-options
|
||||
* // https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md
|
||||
* got.stream("https://www.example.com/some-file.jpg").pipe(sharpStream);
|
||||
*
|
||||
* Promise.all(promises)
|
||||
@@ -321,13 +426,16 @@ util.inherits(Sharp, stream.Duplex);
|
||||
function clone () {
|
||||
// Clone existing options
|
||||
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
|
||||
if (this._isStreamInput()) {
|
||||
this.on('finish', () => {
|
||||
// Clone inherits input data
|
||||
this._flattenBufferIn();
|
||||
clone.options.bufferIn = this.options.bufferIn;
|
||||
clone.options.input.buffer = this.options.input.buffer;
|
||||
clone.emit('finish');
|
||||
});
|
||||
}
|
||||
|
||||
1727
lib/index.d.ts
vendored
Normal file
1727
lib/index.d.ts
vendored
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,6 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const Sharp = require('./constructor');
|
||||
|
||||
355
lib/input.js
355
lib/input.js
@@ -1,17 +1,32 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const color = require('color');
|
||||
const is = require('./is');
|
||||
const sharp = require('../build/Release/sharp.node');
|
||||
const sharp = require('./sharp');
|
||||
|
||||
/**
|
||||
* Justication alignment
|
||||
* @member
|
||||
* @private
|
||||
*/
|
||||
const align = {
|
||||
left: 'low',
|
||||
center: 'centre',
|
||||
centre: 'centre',
|
||||
right: 'high'
|
||||
};
|
||||
|
||||
/**
|
||||
* Extract input options, if any, from an object.
|
||||
* @private
|
||||
*/
|
||||
function _inputOptionsFromObject (obj) {
|
||||
const { raw, density, limitInputPixels, sequentialRead, failOnError } = obj;
|
||||
return [raw, density, limitInputPixels, sequentialRead, failOnError].some(is.defined)
|
||||
? { raw, density, limitInputPixels, sequentialRead, failOnError }
|
||||
const { raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd } = obj;
|
||||
return [raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd].some(is.defined)
|
||||
? { raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd }
|
||||
: undefined;
|
||||
}
|
||||
|
||||
@@ -21,16 +36,31 @@ function _inputOptionsFromObject (obj) {
|
||||
*/
|
||||
function _createInputDescriptor (input, inputOptions, containerOptions) {
|
||||
const inputDescriptor = {
|
||||
failOnError: true,
|
||||
failOn: 'warning',
|
||||
limitInputPixels: Math.pow(0x3FFF, 2),
|
||||
sequentialRead: false
|
||||
ignoreIcc: false,
|
||||
unlimited: false,
|
||||
sequentialRead: true
|
||||
};
|
||||
if (is.string(input)) {
|
||||
// filesystem
|
||||
inputDescriptor.file = input;
|
||||
} else if (is.buffer(input)) {
|
||||
// Buffer
|
||||
if (input.length === 0) {
|
||||
throw Error('Input Buffer is empty');
|
||||
}
|
||||
inputDescriptor.buffer = input;
|
||||
} else if (is.arrayBuffer(input)) {
|
||||
if (input.byteLength === 0) {
|
||||
throw Error('Input bit Array is empty');
|
||||
}
|
||||
inputDescriptor.buffer = Buffer.from(input, 0, input.byteLength);
|
||||
} else if (is.typedArray(input)) {
|
||||
if (input.length === 0) {
|
||||
throw Error('Input Bit Array is empty');
|
||||
}
|
||||
inputDescriptor.buffer = Buffer.from(input.buffer, input.byteOffset, input.byteLength);
|
||||
} else if (is.plainObject(input) && !is.defined(inputOptions)) {
|
||||
// Plain Object descriptor, e.g. create
|
||||
inputOptions = input;
|
||||
@@ -47,20 +77,36 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
||||
}`);
|
||||
}
|
||||
if (is.object(inputOptions)) {
|
||||
// Fail on error
|
||||
// Deprecated: failOnError
|
||||
if (is.defined(inputOptions.failOnError)) {
|
||||
if (is.bool(inputOptions.failOnError)) {
|
||||
inputDescriptor.failOnError = inputOptions.failOnError;
|
||||
inputDescriptor.failOn = inputOptions.failOnError ? 'warning' : 'none';
|
||||
} else {
|
||||
throw is.invalidParameterError('failOnError', 'boolean', inputOptions.failOnError);
|
||||
}
|
||||
}
|
||||
// failOn
|
||||
if (is.defined(inputOptions.failOn)) {
|
||||
if (is.string(inputOptions.failOn) && is.inArray(inputOptions.failOn, ['none', 'truncated', 'error', 'warning'])) {
|
||||
inputDescriptor.failOn = inputOptions.failOn;
|
||||
} else {
|
||||
throw is.invalidParameterError('failOn', 'one of: none, truncated, error, warning', inputOptions.failOn);
|
||||
}
|
||||
}
|
||||
// Density
|
||||
if (is.defined(inputOptions.density)) {
|
||||
if (is.inRange(inputOptions.density, 1, 2400)) {
|
||||
if (is.inRange(inputOptions.density, 1, 100000)) {
|
||||
inputDescriptor.density = inputOptions.density;
|
||||
} else {
|
||||
throw is.invalidParameterError('density', 'number between 1 and 2400', 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
|
||||
@@ -69,10 +115,18 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
||||
inputDescriptor.limitInputPixels = inputOptions.limitInputPixels
|
||||
? Math.pow(0x3FFF, 2)
|
||||
: 0;
|
||||
} else if (is.integer(inputOptions.limitInputPixels) && inputOptions.limitInputPixels >= 0) {
|
||||
} else if (is.integer(inputOptions.limitInputPixels) && is.inRange(inputOptions.limitInputPixels, 0, Number.MAX_SAFE_INTEGER)) {
|
||||
inputDescriptor.limitInputPixels = inputOptions.limitInputPixels;
|
||||
} else {
|
||||
throw is.invalidParameterError('limitInputPixels', 'integer >= 0', inputOptions.limitInputPixels);
|
||||
throw is.invalidParameterError('limitInputPixels', 'positive integer', inputOptions.limitInputPixels);
|
||||
}
|
||||
}
|
||||
// unlimited
|
||||
if (is.defined(inputOptions.unlimited)) {
|
||||
if (is.bool(inputOptions.unlimited)) {
|
||||
inputDescriptor.unlimited = inputOptions.unlimited;
|
||||
} else {
|
||||
throw is.invalidParameterError('unlimited', 'boolean', inputOptions.unlimited);
|
||||
}
|
||||
}
|
||||
// sequentialRead
|
||||
@@ -94,6 +148,38 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
||||
inputDescriptor.rawWidth = inputOptions.raw.width;
|
||||
inputDescriptor.rawHeight = inputOptions.raw.height;
|
||||
inputDescriptor.rawChannels = inputOptions.raw.channels;
|
||||
inputDescriptor.rawPremultiplied = !!inputOptions.raw.premultiplied;
|
||||
|
||||
switch (input.constructor) {
|
||||
case Uint8Array:
|
||||
case Uint8ClampedArray:
|
||||
inputDescriptor.rawDepth = 'uchar';
|
||||
break;
|
||||
case Int8Array:
|
||||
inputDescriptor.rawDepth = 'char';
|
||||
break;
|
||||
case Uint16Array:
|
||||
inputDescriptor.rawDepth = 'ushort';
|
||||
break;
|
||||
case Int16Array:
|
||||
inputDescriptor.rawDepth = 'short';
|
||||
break;
|
||||
case Uint32Array:
|
||||
inputDescriptor.rawDepth = 'uint';
|
||||
break;
|
||||
case Int32Array:
|
||||
inputDescriptor.rawDepth = 'int';
|
||||
break;
|
||||
case Float32Array:
|
||||
inputDescriptor.rawDepth = 'float';
|
||||
break;
|
||||
case Float64Array:
|
||||
inputDescriptor.rawDepth = 'double';
|
||||
break;
|
||||
default:
|
||||
inputDescriptor.rawDepth = 'uchar';
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
throw new Error('Expected width, height and channels for raw pixel input');
|
||||
}
|
||||
@@ -128,28 +214,146 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
||||
throw is.invalidParameterError('level', 'integer between 0 and 256', inputOptions.level);
|
||||
}
|
||||
}
|
||||
// Sub Image File Directory (TIFF)
|
||||
if (is.defined(inputOptions.subifd)) {
|
||||
if (is.integer(inputOptions.subifd) && is.inRange(inputOptions.subifd, -1, 100000)) {
|
||||
inputDescriptor.subifd = inputOptions.subifd;
|
||||
} else {
|
||||
throw is.invalidParameterError('subifd', 'integer between -1 and 100000', inputOptions.subifd);
|
||||
}
|
||||
}
|
||||
// Create new image
|
||||
if (is.defined(inputOptions.create)) {
|
||||
if (
|
||||
is.object(inputOptions.create) &&
|
||||
is.integer(inputOptions.create.width) && inputOptions.create.width > 0 &&
|
||||
is.integer(inputOptions.create.height) && inputOptions.create.height > 0 &&
|
||||
is.integer(inputOptions.create.channels) && is.inRange(inputOptions.create.channels, 3, 4) &&
|
||||
is.defined(inputOptions.create.background)
|
||||
is.integer(inputOptions.create.channels)
|
||||
) {
|
||||
inputDescriptor.createWidth = inputOptions.create.width;
|
||||
inputDescriptor.createHeight = inputOptions.create.height;
|
||||
inputDescriptor.createChannels = inputOptions.create.channels;
|
||||
const background = color(inputOptions.create.background);
|
||||
inputDescriptor.createBackground = [
|
||||
background.red(),
|
||||
background.green(),
|
||||
background.blue(),
|
||||
Math.round(background.alpha() * 255)
|
||||
];
|
||||
// Noise
|
||||
if (is.defined(inputOptions.create.noise)) {
|
||||
if (!is.object(inputOptions.create.noise)) {
|
||||
throw new Error('Expected noise to be an object');
|
||||
}
|
||||
if (!is.inArray(inputOptions.create.noise.type, ['gaussian'])) {
|
||||
throw new Error('Only gaussian noise is supported at the moment');
|
||||
}
|
||||
if (!is.inRange(inputOptions.create.channels, 1, 4)) {
|
||||
throw is.invalidParameterError('create.channels', 'number between 1 and 4', inputOptions.create.channels);
|
||||
}
|
||||
inputDescriptor.createNoiseType = inputOptions.create.noise.type;
|
||||
if (is.number(inputOptions.create.noise.mean) && is.inRange(inputOptions.create.noise.mean, 0, 10000)) {
|
||||
inputDescriptor.createNoiseMean = inputOptions.create.noise.mean;
|
||||
} else {
|
||||
throw is.invalidParameterError('create.noise.mean', 'number between 0 and 10000', inputOptions.create.noise.mean);
|
||||
}
|
||||
if (is.number(inputOptions.create.noise.sigma) && is.inRange(inputOptions.create.noise.sigma, 0, 10000)) {
|
||||
inputDescriptor.createNoiseSigma = inputOptions.create.noise.sigma;
|
||||
} else {
|
||||
throw is.invalidParameterError('create.noise.sigma', 'number between 0 and 10000', inputOptions.create.noise.sigma);
|
||||
}
|
||||
} else if (is.defined(inputOptions.create.background)) {
|
||||
if (!is.inRange(inputOptions.create.channels, 3, 4)) {
|
||||
throw is.invalidParameterError('create.channels', 'number between 3 and 4', inputOptions.create.channels);
|
||||
}
|
||||
const background = color(inputOptions.create.background);
|
||||
inputDescriptor.createBackground = [
|
||||
background.red(),
|
||||
background.green(),
|
||||
background.blue(),
|
||||
Math.round(background.alpha() * 255)
|
||||
];
|
||||
} else {
|
||||
throw new Error('Expected valid noise or background to create a new input image');
|
||||
}
|
||||
delete inputDescriptor.buffer;
|
||||
} else {
|
||||
throw new Error('Expected width, height, channels and background to create a new input image');
|
||||
throw new Error('Expected valid width, height and channels to create a new input image');
|
||||
}
|
||||
}
|
||||
// Create a new image with text
|
||||
if (is.defined(inputOptions.text)) {
|
||||
if (is.object(inputOptions.text) && is.string(inputOptions.text.text)) {
|
||||
inputDescriptor.textValue = inputOptions.text.text;
|
||||
if (is.defined(inputOptions.text.height) && is.defined(inputOptions.text.dpi)) {
|
||||
throw new Error('Expected only one of dpi or height');
|
||||
}
|
||||
if (is.defined(inputOptions.text.font)) {
|
||||
if (is.string(inputOptions.text.font)) {
|
||||
inputDescriptor.textFont = inputOptions.text.font;
|
||||
} else {
|
||||
throw is.invalidParameterError('text.font', 'string', inputOptions.text.font);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.text.fontfile)) {
|
||||
if (is.string(inputOptions.text.fontfile)) {
|
||||
inputDescriptor.textFontfile = inputOptions.text.fontfile;
|
||||
} else {
|
||||
throw is.invalidParameterError('text.fontfile', 'string', inputOptions.text.fontfile);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.text.width)) {
|
||||
if (is.number(inputOptions.text.width)) {
|
||||
inputDescriptor.textWidth = inputOptions.text.width;
|
||||
} else {
|
||||
throw is.invalidParameterError('text.textWidth', 'number', inputOptions.text.width);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.text.height)) {
|
||||
if (is.number(inputOptions.text.height)) {
|
||||
inputDescriptor.textHeight = inputOptions.text.height;
|
||||
} else {
|
||||
throw is.invalidParameterError('text.height', 'number', inputOptions.text.height);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.text.align)) {
|
||||
if (is.string(inputOptions.text.align) && is.string(this.constructor.align[inputOptions.text.align])) {
|
||||
inputDescriptor.textAlign = this.constructor.align[inputOptions.text.align];
|
||||
} else {
|
||||
throw is.invalidParameterError('text.align', 'valid alignment', inputOptions.text.align);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.text.justify)) {
|
||||
if (is.bool(inputOptions.text.justify)) {
|
||||
inputDescriptor.textJustify = inputOptions.text.justify;
|
||||
} else {
|
||||
throw is.invalidParameterError('text.justify', 'boolean', inputOptions.text.justify);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.text.dpi)) {
|
||||
if (is.number(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 100000)) {
|
||||
inputDescriptor.textDpi = inputOptions.text.dpi;
|
||||
} else {
|
||||
throw is.invalidParameterError('text.dpi', 'number between 1 and 100000', inputOptions.text.dpi);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.text.rgba)) {
|
||||
if (is.bool(inputOptions.text.rgba)) {
|
||||
inputDescriptor.textRgba = inputOptions.text.rgba;
|
||||
} else {
|
||||
throw is.invalidParameterError('text.rgba', 'bool', inputOptions.text.rgba);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.text.spacing)) {
|
||||
if (is.number(inputOptions.text.spacing)) {
|
||||
inputDescriptor.textSpacing = inputOptions.text.spacing;
|
||||
} else {
|
||||
throw is.invalidParameterError('text.spacing', 'number', inputOptions.text.spacing);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.text.wrap)) {
|
||||
if (is.string(inputOptions.text.wrap) && is.inArray(inputOptions.text.wrap, ['word', 'char', 'word-char', 'none'])) {
|
||||
inputDescriptor.textWrap = inputOptions.text.wrap;
|
||||
} else {
|
||||
throw is.invalidParameterError('text.wrap', 'one of: word, char, word-char, none', inputOptions.text.wrap);
|
||||
}
|
||||
}
|
||||
delete inputDescriptor.buffer;
|
||||
} else {
|
||||
throw new Error('Expected a valid string to create an image with text.');
|
||||
}
|
||||
}
|
||||
} else if (is.defined(inputOptions)) {
|
||||
@@ -205,25 +409,38 @@ function _isStreamInput () {
|
||||
}
|
||||
|
||||
/**
|
||||
* Fast access to (uncached) image metadata without decoding any compressed image data.
|
||||
* Fast access to (uncached) image metadata without decoding any compressed pixel data.
|
||||
*
|
||||
* This is read from the header of the input image.
|
||||
* It does not take into consideration any operations to be applied to the output image,
|
||||
* such as resize or rotate.
|
||||
*
|
||||
* Dimensions in the response will respect the `page` and `pages` properties of the
|
||||
* {@link /api-constructor#parameters|constructor parameters}.
|
||||
*
|
||||
* A `Promise` is returned when `callback` is not provided.
|
||||
*
|
||||
* - `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg`
|
||||
* - `size`: Total size of image in bytes, for Stream and Buffer input only
|
||||
* - `width`: Number of pixels wide (EXIF orientation is not taken into consideration)
|
||||
* - `height`: Number of pixels high (EXIF orientation is not taken into consideration)
|
||||
* - `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://libvips.github.io/libvips/API/current/VipsImage.html#VipsInterpretation)
|
||||
* - `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://libvips.github.io/libvips/API/current/VipsImage.html#VipsBandFormat)
|
||||
* - `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...](https://www.libvips.org/API/current/VipsImage.html#VipsBandFormat)
|
||||
* - `density`: Number of pixels per inch (DPI), if present
|
||||
* - `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.
|
||||
* - `paletteBitDepth`: Bit depth of palette-based image (GIF, PNG).
|
||||
* - `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
|
||||
@@ -232,6 +449,10 @@ function _isStreamInput () {
|
||||
* - `iptc`: Buffer containing raw IPTC data, if present
|
||||
* - `xmp`: Buffer containing raw XMP data, if present
|
||||
* - `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present
|
||||
* - `formatMagick`: String containing format for images loaded via *magick
|
||||
*
|
||||
* @example
|
||||
* const metadata = await sharp(input).metadata();
|
||||
*
|
||||
* @example
|
||||
* const image = sharp(inputJpg);
|
||||
@@ -247,39 +468,68 @@ function _isStreamInput () {
|
||||
* // data contains a WebP image half the width and height of the original JPEG
|
||||
* });
|
||||
*
|
||||
* @example
|
||||
* // Based on EXIF rotation metadata, get the right-side-up width and height:
|
||||
*
|
||||
* const size = getNormalSize(await sharp(input).metadata());
|
||||
*
|
||||
* function getNormalSize({ width, height, orientation }) {
|
||||
* return (orientation || 0) >= 5
|
||||
* ? { width: height, height: width }
|
||||
* : { width, height };
|
||||
* }
|
||||
*
|
||||
* @param {Function} [callback] - called with the arguments `(err, metadata)`
|
||||
* @returns {Promise<Object>|Sharp}
|
||||
*/
|
||||
function metadata (callback) {
|
||||
const stack = Error();
|
||||
if (is.fn(callback)) {
|
||||
if (this._isStreamInput()) {
|
||||
this.on('finish', () => {
|
||||
this._flattenBufferIn();
|
||||
sharp.metadata(this.options, callback);
|
||||
sharp.metadata(this.options, (err, metadata) => {
|
||||
if (err) {
|
||||
callback(is.nativeError(err, stack));
|
||||
} else {
|
||||
callback(null, metadata);
|
||||
}
|
||||
});
|
||||
});
|
||||
} 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;
|
||||
} else {
|
||||
if (this._isStreamInput()) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.on('finish', () => {
|
||||
const finished = () => {
|
||||
this._flattenBufferIn();
|
||||
sharp.metadata(this.options, (err, metadata) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
reject(is.nativeError(err, stack));
|
||||
} else {
|
||||
resolve(metadata);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
if (this.writableFinished) {
|
||||
finished();
|
||||
} else {
|
||||
this.once('finish', finished);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
return new Promise((resolve, reject) => {
|
||||
sharp.metadata(this.options, (err, metadata) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
reject(is.nativeError(err, stack));
|
||||
} else {
|
||||
resolve(metadata);
|
||||
}
|
||||
@@ -305,9 +555,12 @@ function metadata (callback) {
|
||||
* - `maxX` (x-coordinate of one of the pixel where the maximum lies)
|
||||
* - `maxY` (y-coordinate of one of the pixel where the maximum lies)
|
||||
* - `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque.
|
||||
* - `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any (experimental)
|
||||
* - `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any (experimental)
|
||||
* - `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram (experimental)
|
||||
* - `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any.
|
||||
* - `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any.
|
||||
* - `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram.
|
||||
*
|
||||
* **Note**: Statistics are derived from the original input image. Any operations performed on the image must first be
|
||||
* written to a buffer in order to run `stats` on the result (see third example).
|
||||
*
|
||||
* @example
|
||||
* const image = sharp(inputJpg);
|
||||
@@ -321,18 +574,38 @@ function metadata (callback) {
|
||||
* const { entropy, sharpness, dominant } = await sharp(input).stats();
|
||||
* const { r, g, b } = dominant;
|
||||
*
|
||||
* @example
|
||||
* const image = sharp(input);
|
||||
* // store intermediate result
|
||||
* const part = await image.extract(region).toBuffer();
|
||||
* // create new instance to obtain statistics of extracted region
|
||||
* const stats = await sharp(part).stats();
|
||||
*
|
||||
* @param {Function} [callback] - called with the arguments `(err, stats)`
|
||||
* @returns {Promise<Object>}
|
||||
*/
|
||||
function stats (callback) {
|
||||
const stack = Error();
|
||||
if (is.fn(callback)) {
|
||||
if (this._isStreamInput()) {
|
||||
this.on('finish', () => {
|
||||
this._flattenBufferIn();
|
||||
sharp.stats(this.options, callback);
|
||||
sharp.stats(this.options, (err, stats) => {
|
||||
if (err) {
|
||||
callback(is.nativeError(err, stack));
|
||||
} else {
|
||||
callback(null, stats);
|
||||
}
|
||||
});
|
||||
});
|
||||
} 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;
|
||||
} else {
|
||||
@@ -342,7 +615,7 @@ function stats (callback) {
|
||||
this._flattenBufferIn();
|
||||
sharp.stats(this.options, (err, stats) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
reject(is.nativeError(err, stack));
|
||||
} else {
|
||||
resolve(stats);
|
||||
}
|
||||
@@ -353,7 +626,7 @@ function stats (callback) {
|
||||
return new Promise((resolve, reject) => {
|
||||
sharp.stats(this.options, (err, stats) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
reject(is.nativeError(err, stack));
|
||||
} else {
|
||||
resolve(stats);
|
||||
}
|
||||
@@ -379,4 +652,6 @@ module.exports = function (Sharp) {
|
||||
metadata,
|
||||
stats
|
||||
});
|
||||
// Class attributes
|
||||
Sharp.align = align;
|
||||
};
|
||||
|
||||
76
lib/is.js
76
lib/is.js
@@ -1,3 +1,6 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
@@ -48,6 +51,37 @@ const buffer = function (val) {
|
||||
return val instanceof Buffer;
|
||||
};
|
||||
|
||||
/**
|
||||
* Is this value a typed array object?. E.g. Uint8Array or Uint8ClampedArray?
|
||||
* @private
|
||||
*/
|
||||
const typedArray = function (val) {
|
||||
if (defined(val)) {
|
||||
switch (val.constructor) {
|
||||
case Uint8Array:
|
||||
case Uint8ClampedArray:
|
||||
case Int8Array:
|
||||
case Uint16Array:
|
||||
case Int16Array:
|
||||
case Uint32Array:
|
||||
case Int32Array:
|
||||
case Float32Array:
|
||||
case Float64Array:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Is this value an ArrayBuffer object?
|
||||
* @private
|
||||
*/
|
||||
const arrayBuffer = function (val) {
|
||||
return val instanceof ArrayBuffer;
|
||||
};
|
||||
|
||||
/**
|
||||
* Is this value a non-empty string?
|
||||
* @private
|
||||
@@ -103,17 +137,33 @@ const invalidParameterError = function (name, expected, actual) {
|
||||
);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
defined: defined,
|
||||
object: object,
|
||||
plainObject: plainObject,
|
||||
fn: fn,
|
||||
bool: bool,
|
||||
buffer: buffer,
|
||||
string: string,
|
||||
number: number,
|
||||
integer: integer,
|
||||
inRange: inRange,
|
||||
inArray: inArray,
|
||||
invalidParameterError: invalidParameterError
|
||||
/**
|
||||
* Ensures an Error from C++ contains a JS stack.
|
||||
*
|
||||
* @param {Error} native - Error with message from C++.
|
||||
* @param {Error} context - Error with stack from JS.
|
||||
* @returns {Error} Error with message and stack.
|
||||
* @private
|
||||
*/
|
||||
const nativeError = function (native, context) {
|
||||
context.message = native.message;
|
||||
return context;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
defined,
|
||||
object,
|
||||
plainObject,
|
||||
fn,
|
||||
bool,
|
||||
buffer,
|
||||
typedArray,
|
||||
arrayBuffer,
|
||||
string,
|
||||
number,
|
||||
integer,
|
||||
inRange,
|
||||
inArray,
|
||||
invalidParameterError,
|
||||
nativeError
|
||||
};
|
||||
|
||||
216
lib/libvips.js
216
lib/libvips.js
@@ -1,99 +1,195 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const spawnSync = require('child_process').spawnSync;
|
||||
const semver = require('semver');
|
||||
const platform = require('./platform');
|
||||
const { spawnSync } = require('node:child_process');
|
||||
const { createHash } = require('node:crypto');
|
||||
const semverCoerce = require('semver/functions/coerce');
|
||||
const semverGreaterThanOrEqualTo = require('semver/functions/gte');
|
||||
const semverSatisfies = require('semver/functions/satisfies');
|
||||
const detectLibc = require('detect-libc');
|
||||
|
||||
const env = process.env;
|
||||
const minimumLibvipsVersionLabelled = env.npm_package_config_libvips || /* istanbul ignore next */
|
||||
require('../package.json').config.libvips;
|
||||
const minimumLibvipsVersion = semver.coerce(minimumLibvipsVersionLabelled).version;
|
||||
const { engines, optionalDependencies } = require('../package.json');
|
||||
|
||||
const minimumLibvipsVersionLabelled = process.env.npm_package_config_libvips || /* istanbul ignore next */
|
||||
engines.libvips;
|
||||
const minimumLibvipsVersion = semverCoerce(minimumLibvipsVersionLabelled).version;
|
||||
|
||||
const prebuiltPlatforms = [
|
||||
'darwin-arm64', 'darwin-x64',
|
||||
'linux-arm', 'linux-arm64', 'linux-s390x', 'linux-x64',
|
||||
'linuxmusl-arm64', 'linuxmusl-x64',
|
||||
'win32-ia32', 'win32-x64'
|
||||
];
|
||||
|
||||
const spawnSyncOptions = {
|
||||
encoding: 'utf8',
|
||||
shell: true
|
||||
};
|
||||
|
||||
const mkdirSync = function (dirPath) {
|
||||
const log = (item) => {
|
||||
if (item instanceof Error) {
|
||||
console.error(`sharp: Installation error: ${item.message}`);
|
||||
} else {
|
||||
console.log(`sharp: ${item}`);
|
||||
}
|
||||
};
|
||||
|
||||
/* istanbul ignore next */
|
||||
const runtimeLibc = () => detectLibc.isNonGlibcLinuxSync() ? detectLibc.familySync() : '';
|
||||
|
||||
const runtimePlatformArch = () => `${process.platform}${runtimeLibc()}-${process.arch}`;
|
||||
|
||||
/* istanbul ignore next */
|
||||
const buildPlatformArch = () => {
|
||||
if (isEmscripten()) {
|
||||
return 'wasm32';
|
||||
}
|
||||
/* eslint camelcase: ["error", { allow: ["^npm_config_"] }] */
|
||||
const { npm_config_arch, npm_config_platform, npm_config_libc } = process.env;
|
||||
const libc = typeof npm_config_libc === 'string' ? npm_config_libc : runtimeLibc();
|
||||
return `${npm_config_platform || process.platform}${libc}-${npm_config_arch || process.arch}`;
|
||||
};
|
||||
|
||||
const buildSharpLibvipsIncludeDir = () => {
|
||||
try {
|
||||
fs.mkdirSync(dirPath);
|
||||
} catch (err) {
|
||||
/* istanbul ignore if */
|
||||
if (err.code !== 'EEXIST') {
|
||||
throw err;
|
||||
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 };
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
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;
|
||||
/* istanbul ignore next */
|
||||
const isEmscripten = () => {
|
||||
const { CC } = process.env;
|
||||
return Boolean(CC && CC.endsWith('/emcc'));
|
||||
};
|
||||
|
||||
const globalLibvipsVersion = function () {
|
||||
const isRosetta = () => {
|
||||
/* istanbul ignore next */
|
||||
if (process.platform === 'darwin' && process.arch === 'x64') {
|
||||
const translated = spawnSync('sysctl sysctl.proc_translated', spawnSyncOptions).stdout;
|
||||
return (translated || '').trim() === 'sysctl.proc_translated: 1';
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const sha512 = (s) => createHash('sha512').update(s).digest('hex');
|
||||
|
||||
const yarnLocator = () => {
|
||||
try {
|
||||
const identHash = sha512(`imgsharp-libvips-${buildPlatformArch()}`);
|
||||
const npmVersion = semverCoerce(optionalDependencies[`@img/sharp-libvips-${buildPlatformArch()}`]).version;
|
||||
return sha512(`${identHash}npm:${npmVersion}`).slice(0, 10);
|
||||
} catch {}
|
||||
return '';
|
||||
};
|
||||
|
||||
/* istanbul ignore next */
|
||||
const spawnRebuild = () =>
|
||||
spawnSync(`node-gyp rebuild --directory=src ${isEmscripten() ? '--nodedir=emscripten' : ''}`, {
|
||||
...spawnSyncOptions,
|
||||
stdio: 'inherit'
|
||||
}).status;
|
||||
|
||||
const globalLibvipsVersion = () => {
|
||||
if (process.platform !== 'win32') {
|
||||
const globalLibvipsVersion = spawnSync(`PKG_CONFIG_PATH="${pkgConfigPath()}" pkg-config --modversion vips-cpp`, spawnSyncOptions).stdout || '';
|
||||
return globalLibvipsVersion.trim();
|
||||
const globalLibvipsVersion = spawnSync('pkg-config --modversion vips-cpp', {
|
||||
...spawnSyncOptions,
|
||||
env: {
|
||||
...process.env,
|
||||
PKG_CONFIG_PATH: pkgConfigPath()
|
||||
}
|
||||
}).stdout;
|
||||
/* istanbul ignore next */
|
||||
return (globalLibvipsVersion || '').trim();
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
const hasVendoredLibvips = function () {
|
||||
const currentPlatformId = platform();
|
||||
const vendorPath = path.join(__dirname, '..', 'vendor', minimumLibvipsVersion);
|
||||
let vendorPlatformId;
|
||||
try {
|
||||
vendorPlatformId = require(path.join(vendorPath, 'platform.json'));
|
||||
} catch (err) {}
|
||||
/* istanbul ignore else */
|
||||
if (vendorPlatformId) {
|
||||
/* istanbul ignore else */
|
||||
if (currentPlatformId === vendorPlatformId) {
|
||||
return true;
|
||||
} else {
|
||||
throw new Error(`'${vendorPlatformId}' binaries cannot be used on the '${currentPlatformId}' platform. Please remove the 'node_modules/sharp' directory and run 'npm install' on the '${currentPlatformId}' platform.`);
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const pkgConfigPath = function () {
|
||||
/* istanbul ignore next */
|
||||
const pkgConfigPath = () => {
|
||||
if (process.platform !== 'win32') {
|
||||
const brewPkgConfigPath = spawnSync('which brew >/dev/null 2>&1 && eval $(brew --env) && echo $PKG_CONFIG_LIBDIR', spawnSyncOptions).stdout || '';
|
||||
return [brewPkgConfigPath.trim(), env.PKG_CONFIG_PATH, '/usr/local/lib/pkgconfig', '/usr/lib/pkgconfig']
|
||||
.filter(function (p) { return !!p; })
|
||||
.join(':');
|
||||
const brewPkgConfigPath = spawnSync(
|
||||
'which brew >/dev/null 2>&1 && brew environment --plain | grep PKG_CONFIG_LIBDIR | cut -d" " -f2',
|
||||
spawnSyncOptions
|
||||
).stdout || '';
|
||||
return [
|
||||
brewPkgConfigPath.trim(),
|
||||
process.env.PKG_CONFIG_PATH,
|
||||
'/usr/local/lib/pkgconfig',
|
||||
'/usr/lib/pkgconfig',
|
||||
'/usr/local/libdata/pkgconfig',
|
||||
'/usr/libdata/pkgconfig'
|
||||
].filter(Boolean).join(':');
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
const useGlobalLibvips = function () {
|
||||
if (Boolean(env.SHARP_IGNORE_GLOBAL_LIBVIPS) === true) {
|
||||
const useGlobalLibvips = () => {
|
||||
if (Boolean(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS) === true) {
|
||||
log('Detected SHARP_IGNORE_GLOBAL_LIBVIPS, skipping search for globally-installed libvips');
|
||||
return false;
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
if (isRosetta()) {
|
||||
log('Detected Rosetta, skipping search for globally-installed libvips');
|
||||
return false;
|
||||
}
|
||||
|
||||
const globalVipsVersion = globalLibvipsVersion();
|
||||
return !!globalVipsVersion && /* istanbul ignore next */
|
||||
semver.gte(globalVipsVersion, minimumLibvipsVersion);
|
||||
semverGreaterThanOrEqualTo(globalVipsVersion, minimumLibvipsVersion);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
minimumLibvipsVersion,
|
||||
minimumLibvipsVersionLabelled,
|
||||
cachePath,
|
||||
prebuiltPlatforms,
|
||||
buildPlatformArch,
|
||||
buildSharpLibvipsIncludeDir,
|
||||
buildSharpLibvipsCPlusPlusDir,
|
||||
buildSharpLibvipsLibDir,
|
||||
isUnsupportedNodeRuntime,
|
||||
runtimePlatformArch,
|
||||
log,
|
||||
yarnLocator,
|
||||
spawnRebuild,
|
||||
globalLibvipsVersion,
|
||||
hasVendoredLibvips,
|
||||
pkgConfigPath,
|
||||
useGlobalLibvips,
|
||||
mkdirSync
|
||||
useGlobalLibvips
|
||||
};
|
||||
|
||||
545
lib/operation.js
545
lib/operation.js
@@ -1,3 +1,6 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const color = require('color');
|
||||
@@ -8,7 +11,7 @@ const is = require('./is');
|
||||
* 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.
|
||||
* 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.
|
||||
@@ -16,10 +19,15 @@ const is = require('./is');
|
||||
* If no angle is provided, it is determined from the EXIF data.
|
||||
* Mirroring is supported and may infer the use of a flip operation.
|
||||
*
|
||||
* The use of `rotate` implies the removal of the EXIF `Orientation` tag, if any.
|
||||
* The use of `rotate` without an angle will remove the EXIF `Orientation` tag, if any.
|
||||
*
|
||||
* Method order is important when both rotating and extracting regions,
|
||||
* for example `rotate(x).extract(y)` will produce a different result to `extract(y).rotate(x)`.
|
||||
* Only one rotation can occur per pipeline.
|
||||
* 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)`.
|
||||
*
|
||||
* @example
|
||||
* const pipeline = sharp()
|
||||
@@ -32,6 +40,16 @@ const is = require('./is');
|
||||
* });
|
||||
* readableStream.pipe(pipeline);
|
||||
*
|
||||
* @example
|
||||
* const rotateThenResize = await sharp(input)
|
||||
* .rotate(90)
|
||||
* .resize({ width: 16, height: 8, fit: 'fill' })
|
||||
* .toBuffer();
|
||||
* const resizeThenRotate = await sharp(input)
|
||||
* .resize({ width: 16, height: 8, fit: 'fill' })
|
||||
* .rotate(90)
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {number} [angle=auto] angle of rotation.
|
||||
* @param {Object} [options] - if present, is an Object with optional attributes.
|
||||
* @param {string|Object} [options.background="#000000"] parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
|
||||
@@ -39,6 +57,9 @@ const is = require('./is');
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
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)) {
|
||||
this.options.useExifOrientation = true;
|
||||
} else if (is.integer(angle) && !(angle % 90)) {
|
||||
@@ -61,8 +82,14 @@ function rotate (angle, options) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Flip the image about the vertical Y axis. This always occurs after rotation, if any.
|
||||
* The use of `flip` implies the removal of the EXIF `Orientation` tag, if any.
|
||||
* 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
|
||||
* const output = await sharp(input).flip().toBuffer();
|
||||
*
|
||||
* @param {Boolean} [flip=true]
|
||||
* @returns {Sharp}
|
||||
*/
|
||||
@@ -72,8 +99,12 @@ function flip (flip) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Flop the image about the horizontal X axis. This always occurs after rotation, if any.
|
||||
* The use of `flop` implies the removal of the EXIF `Orientation` tag, if any.
|
||||
* Mirror the image horizontally (left-right) about the y-axis.
|
||||
* This always occurs before rotation, if any.
|
||||
*
|
||||
* @example
|
||||
* const output = await sharp(input).flop().toBuffer();
|
||||
*
|
||||
* @param {Boolean} [flop=true]
|
||||
* @returns {Sharp}
|
||||
*/
|
||||
@@ -83,45 +114,211 @@ function flop (flop) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.
|
||||
*
|
||||
* @param {number} [sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
|
||||
* @param {number} [flat=1.0] - the level of sharpening to apply to "flat" areas.
|
||||
* @param {number} [jagged=2.0] - the level of sharpening to apply to "jagged" areas.
|
||||
* 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.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.
|
||||
*
|
||||
* @since 0.27.0
|
||||
*
|
||||
* @example
|
||||
* 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);
|
||||
*
|
||||
* @param {Array<Array<number>>|Array<number>} matrix - affine transformation matrix
|
||||
* @param {Object} [options] - if present, is an Object with optional attributes.
|
||||
* @param {String|Object} [options.background="#000000"] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
|
||||
* @param {Number} [options.idx=0] - input horizontal offset
|
||||
* @param {Number} [options.idy=0] - input vertical offset
|
||||
* @param {Number} [options.odx=0] - output horizontal offset
|
||||
* @param {Number} [options.ody=0] - output vertical offset
|
||||
* @param {String} [options.interpolator=sharp.interpolators.bicubic] - interpolator
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function sharpen (sigma, flat, jagged) {
|
||||
if (!is.defined(sigma)) {
|
||||
function affine (matrix, options) {
|
||||
const flatMatrix = [].concat(...matrix);
|
||||
if (flatMatrix.length === 4 && flatMatrix.every(is.number)) {
|
||||
this.options.affineMatrix = flatMatrix;
|
||||
} else {
|
||||
throw is.invalidParameterError('matrix', '1x4 or 2x2 array', matrix);
|
||||
}
|
||||
|
||||
if (is.defined(options)) {
|
||||
if (is.object(options)) {
|
||||
this._setBackgroundColourOption('affineBackground', options.background);
|
||||
if (is.defined(options.idx)) {
|
||||
if (is.number(options.idx)) {
|
||||
this.options.affineIdx = options.idx;
|
||||
} else {
|
||||
throw is.invalidParameterError('options.idx', 'number', options.idx);
|
||||
}
|
||||
}
|
||||
if (is.defined(options.idy)) {
|
||||
if (is.number(options.idy)) {
|
||||
this.options.affineIdy = options.idy;
|
||||
} else {
|
||||
throw is.invalidParameterError('options.idy', 'number', options.idy);
|
||||
}
|
||||
}
|
||||
if (is.defined(options.odx)) {
|
||||
if (is.number(options.odx)) {
|
||||
this.options.affineOdx = options.odx;
|
||||
} else {
|
||||
throw is.invalidParameterError('options.odx', 'number', options.odx);
|
||||
}
|
||||
}
|
||||
if (is.defined(options.ody)) {
|
||||
if (is.number(options.ody)) {
|
||||
this.options.affineOdy = options.ody;
|
||||
} else {
|
||||
throw is.invalidParameterError('options.ody', 'number', options.ody);
|
||||
}
|
||||
}
|
||||
if (is.defined(options.interpolator)) {
|
||||
if (is.inArray(options.interpolator, Object.values(this.constructor.interpolators))) {
|
||||
this.options.affineInterpolator = options.interpolator;
|
||||
} else {
|
||||
throw is.invalidParameterError('options.interpolator', 'valid interpolator name', options.interpolator);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw is.invalidParameterError('options', 'object', options);
|
||||
}
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {@link https://www.libvips.org/API/current/libvips-convolution.html#vips-sharpen|libvips sharpen} operation.
|
||||
*
|
||||
* @example
|
||||
* const data = await sharp(input).sharpen().toBuffer();
|
||||
*
|
||||
* @example
|
||||
* const data = await sharp(input).sharpen({ sigma: 2 }).toBuffer();
|
||||
*
|
||||
* @example
|
||||
* const data = await sharp(input)
|
||||
* .sharpen({
|
||||
* sigma: 2,
|
||||
* m1: 0,
|
||||
* m2: 3,
|
||||
* x1: 3,
|
||||
* y2: 15,
|
||||
* y3: 15,
|
||||
* })
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {Object|number} [options] - if present, is an Object with attributes
|
||||
* @param {number} [options.sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`, between 0.000001 and 10
|
||||
* @param {number} [options.m1=1.0] - the level of sharpening to apply to "flat" areas, between 0 and 1000000
|
||||
* @param {number} [options.m2=2.0] - the level of sharpening to apply to "jagged" areas, between 0 and 1000000
|
||||
* @param {number} [options.x1=2.0] - threshold between "flat" and "jagged", between 0 and 1000000
|
||||
* @param {number} [options.y2=10.0] - maximum amount of brightening, between 0 and 1000000
|
||||
* @param {number} [options.y3=20.0] - maximum amount of darkening, between 0 and 1000000
|
||||
* @param {number} [flat] - (deprecated) see `options.m1`.
|
||||
* @param {number} [jagged] - (deprecated) see `options.m2`.
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function sharpen (options, flat, jagged) {
|
||||
if (!is.defined(options)) {
|
||||
// No arguments: default to mild sharpen
|
||||
this.options.sharpenSigma = -1;
|
||||
} else if (is.bool(sigma)) {
|
||||
// Boolean argument: apply mild sharpen?
|
||||
this.options.sharpenSigma = sigma ? -1 : 0;
|
||||
} else if (is.number(sigma) && is.inRange(sigma, 0.01, 10000)) {
|
||||
// Numeric argument: specific sigma
|
||||
this.options.sharpenSigma = sigma;
|
||||
// Control over flat areas
|
||||
} else if (is.bool(options)) {
|
||||
// Deprecated boolean argument: apply mild sharpen?
|
||||
this.options.sharpenSigma = options ? -1 : 0;
|
||||
} else if (is.number(options) && is.inRange(options, 0.01, 10000)) {
|
||||
// Deprecated numeric argument: specific sigma
|
||||
this.options.sharpenSigma = options;
|
||||
// Deprecated control over flat areas
|
||||
if (is.defined(flat)) {
|
||||
if (is.number(flat) && is.inRange(flat, 0, 10000)) {
|
||||
this.options.sharpenFlat = flat;
|
||||
this.options.sharpenM1 = flat;
|
||||
} else {
|
||||
throw is.invalidParameterError('flat', 'number between 0 and 10000', flat);
|
||||
}
|
||||
}
|
||||
// Control over jagged areas
|
||||
// Deprecated control over jagged areas
|
||||
if (is.defined(jagged)) {
|
||||
if (is.number(jagged) && is.inRange(jagged, 0, 10000)) {
|
||||
this.options.sharpenJagged = jagged;
|
||||
this.options.sharpenM2 = jagged;
|
||||
} else {
|
||||
throw is.invalidParameterError('jagged', 'number between 0 and 10000', jagged);
|
||||
}
|
||||
}
|
||||
} else if (is.plainObject(options)) {
|
||||
if (is.number(options.sigma) && is.inRange(options.sigma, 0.000001, 10)) {
|
||||
this.options.sharpenSigma = options.sigma;
|
||||
} else {
|
||||
throw is.invalidParameterError('options.sigma', 'number between 0.000001 and 10', options.sigma);
|
||||
}
|
||||
if (is.defined(options.m1)) {
|
||||
if (is.number(options.m1) && is.inRange(options.m1, 0, 1000000)) {
|
||||
this.options.sharpenM1 = options.m1;
|
||||
} else {
|
||||
throw is.invalidParameterError('options.m1', 'number between 0 and 1000000', options.m1);
|
||||
}
|
||||
}
|
||||
if (is.defined(options.m2)) {
|
||||
if (is.number(options.m2) && is.inRange(options.m2, 0, 1000000)) {
|
||||
this.options.sharpenM2 = options.m2;
|
||||
} else {
|
||||
throw is.invalidParameterError('options.m2', 'number between 0 and 1000000', options.m2);
|
||||
}
|
||||
}
|
||||
if (is.defined(options.x1)) {
|
||||
if (is.number(options.x1) && is.inRange(options.x1, 0, 1000000)) {
|
||||
this.options.sharpenX1 = options.x1;
|
||||
} else {
|
||||
throw is.invalidParameterError('options.x1', 'number between 0 and 1000000', options.x1);
|
||||
}
|
||||
}
|
||||
if (is.defined(options.y2)) {
|
||||
if (is.number(options.y2) && is.inRange(options.y2, 0, 1000000)) {
|
||||
this.options.sharpenY2 = options.y2;
|
||||
} else {
|
||||
throw is.invalidParameterError('options.y2', 'number between 0 and 1000000', options.y2);
|
||||
}
|
||||
}
|
||||
if (is.defined(options.y3)) {
|
||||
if (is.number(options.y3) && is.inRange(options.y3, 0, 1000000)) {
|
||||
this.options.sharpenY3 = options.y3;
|
||||
} else {
|
||||
throw is.invalidParameterError('options.y3', 'number between 0 and 1000000', options.y3);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw is.invalidParameterError('sigma', 'number between 0.01 and 10000', sigma);
|
||||
throw is.invalidParameterError('sigma', 'number between 0.01 and 10000', options);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
@@ -129,6 +326,13 @@ function sharpen (sigma, flat, jagged) {
|
||||
/**
|
||||
* Apply median filter.
|
||||
* When used without parameters the default window is 3x3.
|
||||
*
|
||||
* @example
|
||||
* const output = await sharp(input).median().toBuffer();
|
||||
*
|
||||
* @example
|
||||
* const output = await sharp(input).median(5).toBuffer();
|
||||
*
|
||||
* @param {number} [size=3] square mask size: size x size
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
@@ -148,8 +352,21 @@ function median (size) {
|
||||
|
||||
/**
|
||||
* Blur the image.
|
||||
* When used without parameters, performs a fast, mild blur of the output 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.
|
||||
*
|
||||
* @example
|
||||
* const boxBlurred = await sharp(input)
|
||||
* .blur()
|
||||
* .toBuffer();
|
||||
*
|
||||
* @example
|
||||
* const gaussianBlurred = await sharp(input)
|
||||
* .blur(5)
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {number} [sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
@@ -171,7 +388,15 @@ function blur (sigma) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge alpha transparency channel, if any, with a background.
|
||||
* Merge alpha transparency channel, if any, with a background, then remove the alpha channel.
|
||||
*
|
||||
* See also {@link /api-channel#removealpha|removeAlpha}.
|
||||
*
|
||||
* @example
|
||||
* await sharp(rgbaInput)
|
||||
* .flatten({ background: '#F0A703' })
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @param {string|Object} [options.background={r: 0, g: 0, b: 0}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black.
|
||||
* @returns {Sharp}
|
||||
@@ -184,6 +409,32 @@ function flatten (options) {
|
||||
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`
|
||||
* then increasing the encoding (brighten) post-resize at a factor of `gamma`.
|
||||
@@ -220,31 +471,144 @@ function gamma (gamma, gammaOut) {
|
||||
|
||||
/**
|
||||
* Produce the "negative" of the image.
|
||||
* @param {Boolean} [negate=true]
|
||||
*
|
||||
* @example
|
||||
* const output = await sharp(input)
|
||||
* .negate()
|
||||
* .toBuffer();
|
||||
*
|
||||
* @example
|
||||
* const output = await sharp(input)
|
||||
* .negate({ alpha: false })
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @param {Boolean} [options.alpha=true] Whether or not to negate any alpha channel
|
||||
* @returns {Sharp}
|
||||
*/
|
||||
function negate (negate) {
|
||||
this.options.negate = is.bool(negate) ? negate : true;
|
||||
function negate (options) {
|
||||
this.options.negate = is.bool(options) ? options : true;
|
||||
if (is.plainObject(options) && 'alpha' in options) {
|
||||
if (!is.bool(options.alpha)) {
|
||||
throw is.invalidParameterError('alpha', 'should be boolean value', options.alpha);
|
||||
} else {
|
||||
this.options.negateAlpha = options.alpha;
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enhance output image contrast by stretching its luminance to cover the full dynamic range.
|
||||
* @param {Boolean} [normalise=true]
|
||||
* 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
|
||||
* const output = await sharp(input)
|
||||
* .normalise()
|
||||
* .toBuffer();
|
||||
*
|
||||
* @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}
|
||||
*/
|
||||
function normalise (normalise) {
|
||||
this.options.normalise = is.bool(normalise) ? normalise : true;
|
||||
function normalise (options) {
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Alternative spelling of normalise.
|
||||
* @param {Boolean} [normalize=true]
|
||||
*
|
||||
* @example
|
||||
* const output = await sharp(input)
|
||||
* .normalize()
|
||||
* .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}
|
||||
*/
|
||||
function normalize (normalize) {
|
||||
return this.normalise(normalize);
|
||||
function normalize (options) {
|
||||
return this.normalise(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform contrast limiting adaptive histogram equalization
|
||||
* {@link https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE|CLAHE}.
|
||||
*
|
||||
* This will, in general, enhance the clarity of the image by bringing out darker details.
|
||||
*
|
||||
* @since 0.28.3
|
||||
*
|
||||
* @example
|
||||
* const output = await sharp(input)
|
||||
* .clahe({
|
||||
* width: 3,
|
||||
* height: 3,
|
||||
* })
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {number} options.width - Integral width of the search window, in pixels.
|
||||
* @param {number} options.height - Integral height of the search window, in pixels.
|
||||
* @param {number} [options.maxSlope=3] - Integral level of brightening, between 0 and 100, where 0 disables contrast limiting.
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function clahe (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);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -265,7 +629,7 @@ function normalize (normalize) {
|
||||
*
|
||||
* @param {Object} kernel
|
||||
* @param {number} kernel.width - width of the kernel in pixels.
|
||||
* @param {number} kernel.height - width of the kernel in pixels.
|
||||
* @param {number} kernel.height - height of the kernel in pixels.
|
||||
* @param {Array<number>} kernel.kernel - Array of length `width*height` containing the kernel values.
|
||||
* @param {number} [kernel.scale=sum] - the scale of the kernel in pixels.
|
||||
* @param {number} [kernel.offset=0] - the offset of the kernel in pixels.
|
||||
@@ -299,7 +663,7 @@ function convolve (kernel) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Any pixel value greather than or equal to the threshold value will be set to 255, otherwise it will be set to 0.
|
||||
* Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0.
|
||||
* @param {number} [threshold=128] - a value in the range 0-255 representing the level at which the threshold will be applied.
|
||||
* @param {Object} [options]
|
||||
* @param {Boolean} [options.greyscale=true] - convert to single channel greyscale.
|
||||
@@ -352,32 +716,61 @@ function boolean (operand, operator, options) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the linear formula a * input + b to the image (levels adjustment)
|
||||
* @param {number} [a=1.0] multiplier
|
||||
* @param {number} [b=0.0] offset
|
||||
* 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.
|
||||
*
|
||||
* @example
|
||||
* await sharp(input)
|
||||
* .linear(0.5, 2)
|
||||
* .toBuffer();
|
||||
*
|
||||
* @example
|
||||
* await sharp(rgbInput)
|
||||
* .linear(
|
||||
* [0.25, 0.5, 0.75],
|
||||
* [150, 100, 50]
|
||||
* )
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {(number|number[])} [a=[]] multiplier
|
||||
* @param {(number|number[])} [b=[]] offset
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function linear (a, b) {
|
||||
if (!is.defined(a) && is.number(b)) {
|
||||
a = 1.0;
|
||||
} else if (is.number(a) && !is.defined(b)) {
|
||||
b = 0.0;
|
||||
}
|
||||
if (!is.defined(a)) {
|
||||
this.options.linearA = 1.0;
|
||||
this.options.linearA = [];
|
||||
} else if (is.number(a)) {
|
||||
this.options.linearA = [a];
|
||||
} else if (Array.isArray(a) && a.length && a.every(is.number)) {
|
||||
this.options.linearA = a;
|
||||
} else {
|
||||
throw is.invalidParameterError('a', 'numeric', a);
|
||||
throw is.invalidParameterError('a', 'number or array of numbers', a);
|
||||
}
|
||||
if (!is.defined(b)) {
|
||||
this.options.linearB = 0.0;
|
||||
this.options.linearB = [];
|
||||
} else if (is.number(b)) {
|
||||
this.options.linearB = [b];
|
||||
} else if (Array.isArray(b) && b.length && b.every(is.number)) {
|
||||
this.options.linearB = b;
|
||||
} else {
|
||||
throw is.invalidParameterError('b', 'numeric', b);
|
||||
throw is.invalidParameterError('b', 'number or array of numbers', b);
|
||||
}
|
||||
if (this.options.linearA.length !== this.options.linearB.length) {
|
||||
throw new Error('Expected a and b to be arrays of the same length');
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recomb the image with the specified matrix.
|
||||
* Recombine the image with the specified matrix.
|
||||
*
|
||||
* @since 0.21.1
|
||||
*
|
||||
@@ -390,7 +783,7 @@ function linear (a, b) {
|
||||
* ])
|
||||
* .raw()
|
||||
* .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
|
||||
* });
|
||||
*
|
||||
@@ -416,33 +809,51 @@ function recomb (inputMatrix) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms the image using brightness, saturation and hue rotation.
|
||||
* 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
|
||||
*
|
||||
* @example
|
||||
* sharp(input)
|
||||
* // increase brightness by a factor of 2
|
||||
* const output = await sharp(input)
|
||||
* .modulate({
|
||||
* brightness: 2 // increase lightness by a factor of 2
|
||||
* });
|
||||
* brightness: 2
|
||||
* })
|
||||
* .toBuffer();
|
||||
*
|
||||
* sharp(input)
|
||||
* @example
|
||||
* // hue-rotate by 180 degrees
|
||||
* const output = await sharp(input)
|
||||
* .modulate({
|
||||
* hue: 180 // hue-rotate by 180 degrees
|
||||
* });
|
||||
* hue: 180
|
||||
* })
|
||||
* .toBuffer();
|
||||
*
|
||||
* // decreate brightness and saturation while also hue-rotating by 90 degrees
|
||||
* sharp(input)
|
||||
* @example
|
||||
* // increase lightness by +50
|
||||
* const output = await sharp(input)
|
||||
* .modulate({
|
||||
* lightness: 50
|
||||
* })
|
||||
* .toBuffer();
|
||||
*
|
||||
* @example
|
||||
* // 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
|
||||
* });
|
||||
* hue: 90,
|
||||
* })
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @param {number} [options.brightness] Brightness multiplier
|
||||
* @param {number} [options.saturation] Saturation multiplier
|
||||
* @param {number} [options.hue] Degrees for hue rotation
|
||||
* @param {number} [options.lightness] Lightness addend
|
||||
* @returns {Sharp}
|
||||
*/
|
||||
function modulate (options) {
|
||||
@@ -470,6 +881,13 @@ function modulate (options) {
|
||||
throw is.invalidParameterError('hue', 'number', options.hue);
|
||||
}
|
||||
}
|
||||
if ('lightness' in options) {
|
||||
if (is.number(options.lightness)) {
|
||||
this.options.lightness = options.lightness;
|
||||
} else {
|
||||
throw is.invalidParameterError('lightness', 'number', options.lightness);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -482,14 +900,17 @@ module.exports = function (Sharp) {
|
||||
rotate,
|
||||
flip,
|
||||
flop,
|
||||
affine,
|
||||
sharpen,
|
||||
median,
|
||||
blur,
|
||||
flatten,
|
||||
unflatten,
|
||||
gamma,
|
||||
negate,
|
||||
normalise,
|
||||
normalize,
|
||||
clahe,
|
||||
convolve,
|
||||
threshold,
|
||||
boolean,
|
||||
|
||||
1006
lib/output.js
1006
lib/output.js
File diff suppressed because it is too large
Load Diff
@@ -1,25 +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;
|
||||
/* istanbul ignore next */
|
||||
const libc = (platform === 'linux' && detectLibc.isNonGlibcLinux) ? detectLibc.family : '';
|
||||
|
||||
const platformId = [`${platform}${libc}`];
|
||||
|
||||
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('-');
|
||||
};
|
||||
256
lib/resize.js
256
lib/resize.js
@@ -1,3 +1,6 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const is = require('./is');
|
||||
@@ -36,6 +39,18 @@ const position = {
|
||||
'left top': 8
|
||||
};
|
||||
|
||||
/**
|
||||
* How to extend the image.
|
||||
* @member
|
||||
* @private
|
||||
*/
|
||||
const extendWith = {
|
||||
background: 'background',
|
||||
copy: 'copy',
|
||||
repeat: 'repeat',
|
||||
mirror: 'mirror'
|
||||
};
|
||||
|
||||
/**
|
||||
* Strategies for automagic cover behaviour.
|
||||
* @member
|
||||
@@ -92,11 +107,18 @@ function isRotationExpected (options) {
|
||||
return (options.angle % 360) !== 0 || options.useExifOrientation === true || options.rotationAngle !== 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
function isResizeExpected (options) {
|
||||
return options.width !== -1 || options.height !== -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resize image to `width`, `height` or `width x height`.
|
||||
*
|
||||
* 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.
|
||||
* - `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.
|
||||
@@ -104,7 +126,9 @@ function isRotationExpected (options) {
|
||||
*
|
||||
* Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property.
|
||||
*
|
||||
* When using a `fit` of `cover` or `contain`, the default **position** is `centre`. Other options are:
|
||||
* <img alt="Examples of various values for the fit property when resizing" width="100%" style="aspect-ratio: 998/243" src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/api-resize-fit.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.
|
||||
@@ -123,6 +147,9 @@ function isRotationExpected (options) {
|
||||
* - `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).
|
||||
*
|
||||
* Only one resize can occur per pipeline.
|
||||
* Previous calls to `resize` in the same pipeline will be ignored.
|
||||
*
|
||||
* @example
|
||||
* sharp(input)
|
||||
* .resize({ width: 100 })
|
||||
@@ -183,6 +210,20 @@ function isRotationExpected (options) {
|
||||
* });
|
||||
*
|
||||
* @example
|
||||
* sharp(input)
|
||||
* .resize(200, 200, {
|
||||
* fit: sharp.fit.outside,
|
||||
* withoutReduction: true
|
||||
* })
|
||||
* .toFormat('jpeg')
|
||||
* .toBuffer()
|
||||
* .then(function(outputBuffer) {
|
||||
* // outputBuffer contains JPEG image data
|
||||
* // of at least 200 pixels wide and 200 pixels high while maintaining aspect ratio
|
||||
* // and no smaller than the input image
|
||||
* });
|
||||
*
|
||||
* @example
|
||||
* const scaleByHalf = await sharp(input)
|
||||
* .metadata()
|
||||
* .then(({ width }) => sharp(input)
|
||||
@@ -190,28 +231,35 @@ function isRotationExpected (options) {
|
||||
* .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} [height] - pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width.
|
||||
* @param {number} [width] - How many pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height.
|
||||
* @param {number} [height] - How many pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width.
|
||||
* @param {Object} [options]
|
||||
* @param {String} [options.width] - alternative means of specifying `width`. If both are present this take priority.
|
||||
* @param {String} [options.height] - alternative means of specifying `height`. If both are present this take 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.position='centre'] - position, gravity or strategy to use when `fit` is `cover` or `contain`.
|
||||
* @param {String|Object} [options.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour when using a `fit` of `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency.
|
||||
* @param {String} [options.kernel='lanczos3'] - the kernel to use for image reduction.
|
||||
* @param {Boolean} [options.withoutEnlargement=false] - do not enlarge if the width *or* height are already less than the specified dimensions, equivalent to GraphicsMagick's `>` geometry option.
|
||||
* @param {Boolean} [options.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 {number} [options.width] - An alternative means of specifying `width`. If both are present this takes priority.
|
||||
* @param {number} [options.height] - An alternative means of specifying `height`. If both are present this takes priority.
|
||||
* @param {String} [options.fit='cover'] - How the image should be resized/cropped to fit the target dimension(s), one of `cover`, `contain`, `fill`, `inside` or `outside`.
|
||||
* @param {String} [options.position='centre'] - A position, gravity or strategy to use when `fit` is `cover` or `contain`.
|
||||
* @param {String|Object} [options.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency.
|
||||
* @param {String} [options.kernel='lanczos3'] - The kernel to use for image reduction. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load.
|
||||
* @param {Boolean} [options.withoutEnlargement=false] - Do not scale up if the width *or* height are already less than the target dimensions, equivalent to GraphicsMagick's `>` geometry option. This may result in output dimensions smaller than the target dimensions.
|
||||
* @param {Boolean} [options.withoutReduction=false] - Do not scale down if the width *or* height are already greater than the target dimensions, equivalent to GraphicsMagick's `<` geometry option. This may still result in a crop to reach the target dimensions.
|
||||
* @param {Boolean} [options.fastShrinkOnLoad=true] - Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern or round-down of an auto-scaled dimension.
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function resize (width, height, options) {
|
||||
if (is.defined(width)) {
|
||||
if (is.object(width) && !is.defined(options)) {
|
||||
options = width;
|
||||
} else if (is.integer(width) && width > 0) {
|
||||
this.options.width = width;
|
||||
function resize (widthOrOptions, height, options) {
|
||||
if (isResizeExpected(this.options)) {
|
||||
this.options.debuglog('ignoring previous resize options');
|
||||
}
|
||||
if (this.options.widthPost !== -1) {
|
||||
this.options.debuglog('operation order will be: extract, resize, extract');
|
||||
}
|
||||
if (is.defined(widthOrOptions)) {
|
||||
if (is.object(widthOrOptions) && !is.defined(options)) {
|
||||
options = widthOrOptions;
|
||||
} else if (is.integer(widthOrOptions) && widthOrOptions > 0) {
|
||||
this.options.width = widthOrOptions;
|
||||
} else {
|
||||
throw is.invalidParameterError('width', 'positive integer', width);
|
||||
throw is.invalidParameterError('width', 'positive integer', widthOrOptions);
|
||||
}
|
||||
} else {
|
||||
this.options.width = -1;
|
||||
@@ -276,16 +324,24 @@ function resize (width, height, options) {
|
||||
if (is.defined(options.withoutEnlargement)) {
|
||||
this._setBooleanOption('withoutEnlargement', options.withoutEnlargement);
|
||||
}
|
||||
// Without reduction
|
||||
if (is.defined(options.withoutReduction)) {
|
||||
this._setBooleanOption('withoutReduction', options.withoutReduction);
|
||||
}
|
||||
// Shrink on load
|
||||
if (is.defined(options.fastShrinkOnLoad)) {
|
||||
this._setBooleanOption('fastShrinkOnLoad', options.fastShrinkOnLoad);
|
||||
}
|
||||
}
|
||||
if (isRotationExpected(this.options) && isResizeExpected(this.options)) {
|
||||
this.options.rotateBeforePreExtract = true;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* @example
|
||||
@@ -302,11 +358,30 @@ function resize (width, height, options) {
|
||||
* })
|
||||
* ...
|
||||
*
|
||||
* @example
|
||||
* // Add a row of 10 red pixels to the bottom
|
||||
* sharp(input)
|
||||
* .extend({
|
||||
* bottom: 10,
|
||||
* background: 'red'
|
||||
* })
|
||||
* ...
|
||||
*
|
||||
* @example
|
||||
* // Extrude image by 8 pixels to the right, mirroring existing right hand edge
|
||||
* sharp(input)
|
||||
* .extend({
|
||||
* right: 8,
|
||||
* background: 'mirror'
|
||||
* })
|
||||
* ...
|
||||
*
|
||||
* @param {(number|Object)} extend - single pixel count to add to all edges or an Object with per-edge counts
|
||||
* @param {number} [extend.top]
|
||||
* @param {number} [extend.left]
|
||||
* @param {number} [extend.bottom]
|
||||
* @param {number} [extend.right]
|
||||
* @param {number} [extend.top=0]
|
||||
* @param {number} [extend.left=0]
|
||||
* @param {number} [extend.bottom=0]
|
||||
* @param {number} [extend.right=0]
|
||||
* @param {String} [extend.extendWith='background'] - populate new pixels using this method, one of: background, copy, repeat, mirror.
|
||||
* @param {String|Object} [extend.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency.
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
@@ -317,18 +392,43 @@ function extend (extend) {
|
||||
this.options.extendBottom = extend;
|
||||
this.options.extendLeft = extend;
|
||||
this.options.extendRight = extend;
|
||||
} else if (
|
||||
is.object(extend) &&
|
||||
is.integer(extend.top) && extend.top >= 0 &&
|
||||
is.integer(extend.bottom) && extend.bottom >= 0 &&
|
||||
is.integer(extend.left) && extend.left >= 0 &&
|
||||
is.integer(extend.right) && extend.right >= 0
|
||||
) {
|
||||
this.options.extendTop = extend.top;
|
||||
this.options.extendBottom = extend.bottom;
|
||||
this.options.extendLeft = extend.left;
|
||||
this.options.extendRight = extend.right;
|
||||
} else if (is.object(extend)) {
|
||||
if (is.defined(extend.top)) {
|
||||
if (is.integer(extend.top) && extend.top >= 0) {
|
||||
this.options.extendTop = extend.top;
|
||||
} else {
|
||||
throw is.invalidParameterError('top', 'positive integer', extend.top);
|
||||
}
|
||||
}
|
||||
if (is.defined(extend.bottom)) {
|
||||
if (is.integer(extend.bottom) && extend.bottom >= 0) {
|
||||
this.options.extendBottom = extend.bottom;
|
||||
} else {
|
||||
throw is.invalidParameterError('bottom', 'positive integer', extend.bottom);
|
||||
}
|
||||
}
|
||||
if (is.defined(extend.left)) {
|
||||
if (is.integer(extend.left) && extend.left >= 0) {
|
||||
this.options.extendLeft = extend.left;
|
||||
} else {
|
||||
throw is.invalidParameterError('left', 'positive integer', extend.left);
|
||||
}
|
||||
}
|
||||
if (is.defined(extend.right)) {
|
||||
if (is.integer(extend.right) && extend.right >= 0) {
|
||||
this.options.extendRight = extend.right;
|
||||
} else {
|
||||
throw is.invalidParameterError('right', 'positive integer', extend.right);
|
||||
}
|
||||
}
|
||||
this._setBackgroundColourOption('extendBackground', extend.background);
|
||||
if (is.defined(extend.extendWith)) {
|
||||
if (is.string(extendWith[extend.extendWith])) {
|
||||
this.options.extendWith = extendWith[extend.extendWith];
|
||||
} else {
|
||||
throw is.invalidParameterError('extendWith', 'one of: background, copy, repeat, mirror', extend.extendWith);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw is.invalidParameterError('extend', 'integer or object', extend);
|
||||
}
|
||||
@@ -340,7 +440,7 @@ function extend (extend) {
|
||||
*
|
||||
* - Use `extract` before `resize` for pre-resize extraction.
|
||||
* - Use `extract` after `resize` for post-resize extraction.
|
||||
* - Use `extract` before and after for both.
|
||||
* - Use `extract` twice and `resize` once for extract-then-resize-then-extract in a fixed operation order.
|
||||
*
|
||||
* @example
|
||||
* sharp(input)
|
||||
@@ -366,7 +466,10 @@ function extend (extend) {
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function extract (options) {
|
||||
const suffix = this.options.width === -1 && this.options.height === -1 ? 'Pre' : 'Post';
|
||||
const suffix = isResizeExpected(this.options) || this.options.widthPre !== -1 ? 'Post' : 'Pre';
|
||||
if (this.options[`width${suffix}`] !== -1) {
|
||||
this.options.debuglog('ignoring previous extract options');
|
||||
}
|
||||
['left', 'top', 'width', 'height'].forEach(function (name) {
|
||||
const value = options[name];
|
||||
if (is.integer(value) && value >= 0) {
|
||||
@@ -376,31 +479,84 @@ function extract (options) {
|
||||
}
|
||||
}, this);
|
||||
// Ensure existing rotation occurs before pre-resize extraction
|
||||
if (suffix === 'Pre' && isRotationExpected(this.options)) {
|
||||
this.options.rotateBeforePreExtract = true;
|
||||
if (isRotationExpected(this.options) && !isResizeExpected(this.options)) {
|
||||
if (this.options.widthPre === -1 || this.options.widthPost === -1) {
|
||||
this.options.rotateBeforePreExtract = true;
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trim "boring" pixels from all edges that contain values similar to the top-left pixel.
|
||||
* Images consisting entirely of a single colour will calculate "boring" using the alpha channel, if any.
|
||||
* 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.
|
||||
*
|
||||
* @param {number} [threshold=10] the allowed difference from the top-left pixel, a number greater than zero.
|
||||
* @example
|
||||
* // Trim pixels with a colour similar to that of the top-left pixel.
|
||||
* await sharp(input)
|
||||
* .trim()
|
||||
* .toFile(output);
|
||||
*
|
||||
* @example
|
||||
* // Trim pixels with the exact same colour as that of the top-left pixel.
|
||||
* await sharp(input)
|
||||
* .trim({
|
||||
* threshold: 0
|
||||
* })
|
||||
* .toFile(output);
|
||||
*
|
||||
* @example
|
||||
* // Assume input is line art and trim only pixels with a similar colour to red.
|
||||
* const output = await sharp(input)
|
||||
* .trim({
|
||||
* background: "#FF0000",
|
||||
* lineArt: true
|
||||
* })
|
||||
* .toBuffer();
|
||||
*
|
||||
* @example
|
||||
* // Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
|
||||
* const output = await sharp(input)
|
||||
* .trim({
|
||||
* background: "yellow",
|
||||
* threshold: 42,
|
||||
* })
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @param {string|Object} [options.background='top-left pixel'] - Background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel.
|
||||
* @param {number} [options.threshold=10] - Allowed difference from the above colour, a positive number.
|
||||
* @param {boolean} [options.lineArt=false] - Does the input more closely resemble line art (e.g. vector) rather than being photographic?
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function trim (threshold) {
|
||||
if (!is.defined(threshold)) {
|
||||
this.options.trimThreshold = 10;
|
||||
} else if (is.number(threshold) && threshold > 0) {
|
||||
this.options.trimThreshold = threshold;
|
||||
} else {
|
||||
throw is.invalidParameterError('threshold', 'number greater than zero', threshold);
|
||||
function trim (options) {
|
||||
this.options.trimThreshold = 10;
|
||||
if (is.defined(options)) {
|
||||
if (is.object(options)) {
|
||||
if (is.defined(options.background)) {
|
||||
this._setBackgroundColourOption('trimBackground', options.background);
|
||||
}
|
||||
if (is.defined(options.threshold)) {
|
||||
if (is.number(options.threshold) && options.threshold >= 0) {
|
||||
this.options.trimThreshold = options.threshold;
|
||||
} else {
|
||||
throw is.invalidParameterError('threshold', 'positive number', options.threshold);
|
||||
}
|
||||
}
|
||||
if (is.defined(options.lineArt)) {
|
||||
this._setBooleanOption('trimLineArt', options.lineArt);
|
||||
}
|
||||
} else {
|
||||
throw is.invalidParameterError('trim', 'object', options);
|
||||
}
|
||||
}
|
||||
if (this.options.trimThreshold && isRotationExpected(this.options)) {
|
||||
if (isRotationExpected(this.options)) {
|
||||
this.options.rotateBeforePreExtract = true;
|
||||
}
|
||||
return this;
|
||||
|
||||
115
lib/sharp.js
Normal file
115
lib/sharp.js
Normal file
@@ -0,0 +1,115 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
// Inspects the runtime environment and exports the relevant sharp.node binary
|
||||
|
||||
const { familySync, versionSync } = require('detect-libc');
|
||||
|
||||
const { runtimePlatformArch, isUnsupportedNodeRuntime, prebuiltPlatforms, minimumLibvipsVersion } = require('./libvips');
|
||||
const runtimePlatform = runtimePlatformArch();
|
||||
|
||||
const paths = [
|
||||
`../src/build/Release/sharp-${runtimePlatform}.node`,
|
||||
'../src/build/Release/sharp-wasm32.node',
|
||||
`@img/sharp-${runtimePlatform}/sharp.node`,
|
||||
'@img/sharp-wasm32/sharp.node'
|
||||
];
|
||||
|
||||
let sharp;
|
||||
const errors = [];
|
||||
for (const path of paths) {
|
||||
try {
|
||||
sharp = require(path);
|
||||
break;
|
||||
} catch (err) {
|
||||
/* istanbul ignore next */
|
||||
errors.push(err);
|
||||
}
|
||||
}
|
||||
|
||||
/* istanbul ignore next */
|
||||
if (sharp) {
|
||||
module.exports = sharp;
|
||||
} else {
|
||||
const [isLinux, isMacOs, isWindows] = ['linux', 'darwin', 'win32'].map(os => runtimePlatform.startsWith(os));
|
||||
|
||||
const help = [`Could not load the "sharp" module using the ${runtimePlatform} runtime`];
|
||||
errors.forEach(err => {
|
||||
if (err.code !== 'MODULE_NOT_FOUND') {
|
||||
help.push(`${err.code}: ${err.message}`);
|
||||
}
|
||||
});
|
||||
const messages = errors.map(err => err.message).join(' ');
|
||||
help.push('Possible solutions:');
|
||||
// Common error messages
|
||||
if (isUnsupportedNodeRuntime()) {
|
||||
const { found, expected } = isUnsupportedNodeRuntime();
|
||||
help.push(
|
||||
'- Please upgrade Node.js:',
|
||||
` Found ${found}`,
|
||||
` Requires ${expected}`
|
||||
);
|
||||
} else if (prebuiltPlatforms.includes(runtimePlatform)) {
|
||||
const [os, cpu] = runtimePlatform.split('-');
|
||||
const libc = os.endsWith('musl') ? ' --libc=musl' : '';
|
||||
help.push(
|
||||
'- Ensure optional dependencies can be installed:',
|
||||
' npm install --include=optional sharp',
|
||||
' yarn add sharp --ignore-engines',
|
||||
'- 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 { engines } = require(`@img/sharp-libvips-${runtimePlatform}/package`);
|
||||
const libcFound = `${familySync()} ${versionSync()}`;
|
||||
const libcRequires = `${engines.musl ? 'musl' : 'glibc'} ${engines.musl || engines.glibc}`;
|
||||
help.push(
|
||||
'- Update your OS:',
|
||||
` Found ${libcFound}`,
|
||||
` Requires ${libcRequires}`
|
||||
);
|
||||
} catch (errEngines) {}
|
||||
}
|
||||
if (isLinux && /\/snap\/core[0-9]{2}/.test(messages)) {
|
||||
help.push(
|
||||
'- Remove the Node.js Snap, which does not support native modules',
|
||||
' snap remove node'
|
||||
);
|
||||
}
|
||||
if (isMacOs && /Incompatible library version/.test(messages)) {
|
||||
help.push(
|
||||
'- Update Homebrew:',
|
||||
' brew update && brew upgrade vips'
|
||||
);
|
||||
}
|
||||
if (errors.some(err => err.code === 'ERR_DLOPEN_DISABLED')) {
|
||||
help.push('- Run Node.js without using the --no-addons flag');
|
||||
}
|
||||
// Link to installation docs
|
||||
if (isWindows && /The specified procedure could not be found/.test(messages)) {
|
||||
help.push(
|
||||
'- Using the canvas package on Windows?',
|
||||
' See https://sharp.pixelplumbing.com/install#canvas-and-windows',
|
||||
'- Check for outdated versions of sharp in the dependency tree:',
|
||||
' npm ls sharp'
|
||||
);
|
||||
}
|
||||
help.push(
|
||||
'- Consult the installation documentation:',
|
||||
' See https://sharp.pixelplumbing.com/install'
|
||||
);
|
||||
throw new Error(help.join('\n'));
|
||||
}
|
||||
185
lib/utility.js
185
lib/utility.js
@@ -1,8 +1,17 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const events = require('events');
|
||||
const events = require('node:events');
|
||||
const detectLibc = require('detect-libc');
|
||||
|
||||
const is = require('./is');
|
||||
const sharp = require('../build/Release/sharp.node');
|
||||
const { runtimePlatformArch } = require('./libvips');
|
||||
const sharp = require('./sharp');
|
||||
|
||||
const runtimePlatform = runtimePlatformArch();
|
||||
const libvipsVersion = sharp.libvipsVersion();
|
||||
|
||||
/**
|
||||
* An Object containing nested boolean values representing the available input and output formats/methods.
|
||||
@@ -12,19 +21,59 @@ const sharp = require('../build/Release/sharp.node');
|
||||
* @returns {Object}
|
||||
*/
|
||||
const format = sharp.format();
|
||||
format.heif.output.alias = ['avif', 'heic'];
|
||||
format.jpeg.output.alias = ['jpe', 'jpg'];
|
||||
format.tiff.output.alias = ['tif'];
|
||||
format.jp2k.output.alias = ['j2c', 'j2k', 'jp2', 'jpx'];
|
||||
|
||||
/**
|
||||
* An Object containing the version numbers of libvips and its dependencies.
|
||||
* An Object containing the available interpolators and their proper values
|
||||
* @readonly
|
||||
* @enum {string}
|
||||
*/
|
||||
const interpolators = {
|
||||
/** [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. */
|
||||
nearest: 'nearest',
|
||||
/** [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. */
|
||||
bilinear: 'bilinear',
|
||||
/** [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). */
|
||||
bicubic: 'bicubic',
|
||||
/** [LBB interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100). Prevents some "[acutance](http://en.wikipedia.org/wiki/Acutance)" but typically reduces performance by a factor of 2. */
|
||||
locallyBoundedBicubic: 'lbb',
|
||||
/** [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. */
|
||||
nohalo: 'nohalo',
|
||||
/** [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents "staircasing" when enlarging. */
|
||||
vertexSplitQuadraticBasisSpline: 'vsqbs'
|
||||
};
|
||||
|
||||
/**
|
||||
* An Object containing the version numbers of sharp, libvips
|
||||
* and (when using prebuilt binaries) its dependencies.
|
||||
*
|
||||
* @member
|
||||
* @example
|
||||
* console.log(sharp.versions);
|
||||
*/
|
||||
let versions = {
|
||||
vips: sharp.libvipsVersion()
|
||||
vips: libvipsVersion.semver
|
||||
};
|
||||
try {
|
||||
versions = require(`../vendor/${versions.vips}/versions.json`);
|
||||
} catch (err) {}
|
||||
/* istanbul ignore next */
|
||||
if (!libvipsVersion.isGlobal) {
|
||||
if (!libvipsVersion.isWasm) {
|
||||
try {
|
||||
versions = require(`@img/sharp-${runtimePlatform}/versions`);
|
||||
} catch (_) {
|
||||
try {
|
||||
versions = require(`@img/sharp-libvips-${runtimePlatform}/versions`);
|
||||
} catch (_) {}
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
versions = require('@img/sharp-wasm32/versions');
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
versions.sharp = require('../package.json').version;
|
||||
|
||||
/**
|
||||
* Gets or, when options are provided, sets the limits of _libvips'_ operation cache.
|
||||
@@ -63,15 +112,32 @@ cache(true);
|
||||
|
||||
/**
|
||||
* Gets or, when a concurrency is provided, sets
|
||||
* the number of threads _libvips'_ should create to process each image.
|
||||
* The default value is the number of CPU cores.
|
||||
* A value of `0` will reset to this default.
|
||||
*
|
||||
* The maximum number of images that can be processed in parallel
|
||||
* is limited by libuv's `UV_THREADPOOL_SIZE` environment variable.
|
||||
* 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
|
||||
*
|
||||
* 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
|
||||
* const threads = sharp.concurrency(); // 4
|
||||
* sharp.concurrency(2); // 2
|
||||
@@ -83,6 +149,11 @@ cache(true);
|
||||
function concurrency (concurrency) {
|
||||
return sharp.concurrency(is.integer(concurrency) ? concurrency : null);
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
if (detectLibc.familySync() === detectLibc.GLIBC && !sharp._isUsingJemalloc()) {
|
||||
// Reduce default concurrency to 1 when using glibc memory allocator
|
||||
sharp.concurrency(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* An EventEmitter that emits a `change` event when a task is either:
|
||||
@@ -112,17 +183,17 @@ function counters () {
|
||||
|
||||
/**
|
||||
* 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
|
||||
* by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.
|
||||
*
|
||||
* @example
|
||||
* const simd = sharp.simd();
|
||||
* // simd is `true` if the runtime use of liborc is currently enabled
|
||||
* // simd is `true` if the runtime use of highway is currently enabled
|
||||
* @example
|
||||
* const simd = sharp.simd(false);
|
||||
* // prevent libvips from using liborc at runtime
|
||||
* // prevent libvips from using highway at runtime
|
||||
*
|
||||
* @param {boolean} [simd=true]
|
||||
* @returns {boolean}
|
||||
@@ -130,22 +201,86 @@ function counters () {
|
||||
function simd (simd) {
|
||||
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.
|
||||
* @private
|
||||
*/
|
||||
module.exports = function (Sharp) {
|
||||
[
|
||||
cache,
|
||||
concurrency,
|
||||
counters,
|
||||
simd
|
||||
].forEach(function (f) {
|
||||
Sharp[f.name] = f;
|
||||
});
|
||||
Sharp.cache = cache;
|
||||
Sharp.concurrency = concurrency;
|
||||
Sharp.counters = counters;
|
||||
Sharp.simd = simd;
|
||||
Sharp.format = format;
|
||||
Sharp.interpolators = interpolators;
|
||||
Sharp.versions = versions;
|
||||
Sharp.queue = queue;
|
||||
Sharp.block = block;
|
||||
Sharp.unblock = unblock;
|
||||
};
|
||||
|
||||
44
npm/darwin-arm64/package.json
Normal file
44
npm/darwin-arm64/package.json
Normal file
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"name": "@img/sharp-darwin-arm64",
|
||||
"version": "0.33.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with macOS 64-bit ARM",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/darwin-arm64"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-darwin-arm64": "1.0.2"
|
||||
},
|
||||
"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",
|
||||
"npm": ">=9.6.5",
|
||||
"yarn": ">=3.2.0",
|
||||
"pnpm": ">=7.1.0",
|
||||
"glibc": ">=2.26"
|
||||
},
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"cpu": [
|
||||
"arm64"
|
||||
]
|
||||
}
|
||||
44
npm/darwin-x64/package.json
Normal file
44
npm/darwin-x64/package.json
Normal file
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"name": "@img/sharp-darwin-x64",
|
||||
"version": "0.33.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with macOS x64",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/darwin-x64"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-darwin-x64": "1.0.2"
|
||||
},
|
||||
"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",
|
||||
"npm": ">=9.6.5",
|
||||
"yarn": ">=3.2.0",
|
||||
"pnpm": ">=7.1.0",
|
||||
"glibc": ">=2.26"
|
||||
},
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
]
|
||||
}
|
||||
73
npm/from-github-release.js
Normal file
73
npm/from-github-release.js
Normal file
@@ -0,0 +1,73 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
// Populate contents of all packages with the current GitHub release
|
||||
|
||||
const { readFile, writeFile, appendFile, copyFile, rm } = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const { Readable } = require('node:stream');
|
||||
const { pipeline } = require('node:stream/promises');
|
||||
const { createGunzip } = require('node:zlib');
|
||||
const { extract } = require('tar-fs');
|
||||
|
||||
const { workspaces } = require('./package.json');
|
||||
const { version } = require('../package.json');
|
||||
|
||||
const mapTarballEntry = (header) => {
|
||||
header.name = path.basename(header.name);
|
||||
return header;
|
||||
};
|
||||
|
||||
const licensing = `
|
||||
## Licensing
|
||||
|
||||
Copyright 2013 Lovell Fuller and others.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0)
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
`;
|
||||
|
||||
workspaces.map(async platform => {
|
||||
const prebuildPlatform = platform === 'wasm32' ? 'emscripten-wasm32' : platform;
|
||||
const url = `https://github.com/lovell/sharp/releases/download/v${version}/sharp-v${version}-napi-v9-${prebuildPlatform}.tar.gz`;
|
||||
const dir = path.join(__dirname, platform);
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
console.log(`Skipping ${platform}: ${response.statusText}`);
|
||||
return;
|
||||
}
|
||||
// Extract prebuild tarball
|
||||
const lib = path.join(dir, 'lib');
|
||||
await rm(lib, { force: true, recursive: true });
|
||||
await pipeline(
|
||||
Readable.fromWeb(response.body),
|
||||
createGunzip(),
|
||||
extract(lib, { map: mapTarballEntry })
|
||||
);
|
||||
// Generate README
|
||||
const { name, description } = require(`./${platform}/package.json`);
|
||||
await writeFile(path.join(dir, 'README.md'), `# \`${name}\`\n\n${description}.\n${licensing}`);
|
||||
// Copy Apache-2.0 LICENSE
|
||||
await copyFile(path.join(__dirname, '..', 'LICENSE'), path.join(dir, 'LICENSE'));
|
||||
// Copy files for packages without an explicit sharp-libvips dependency (Windows, wasm)
|
||||
if (platform.startsWith('win') || platform.startsWith('wasm')) {
|
||||
const libvipsPlatform = platform === 'wasm32' ? 'dev-wasm32' : platform;
|
||||
const sharpLibvipsDir = path.join(require(`@img/sharp-libvips-${libvipsPlatform}/lib`), '..');
|
||||
// Copy versions.json
|
||||
await copyFile(path.join(sharpLibvipsDir, 'versions.json'), path.join(dir, 'versions.json'));
|
||||
// Append third party licensing to README
|
||||
const readme = await readFile(path.join(sharpLibvipsDir, 'README.md'), { encoding: 'utf-8' });
|
||||
const thirdParty = readme.substring(readme.indexOf('\nThis software contains'));
|
||||
appendFile(path.join(dir, 'README.md'), thirdParty);
|
||||
}
|
||||
});
|
||||
26
npm/from-local-build.js
Normal file
26
npm/from-local-build.js
Normal file
@@ -0,0 +1,26 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
// Populate contents of a single npm/sharpen-sharp-<build-platform> package
|
||||
// with the local/CI build directory for local/CI prebuild testing
|
||||
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const { buildPlatformArch } = require('../lib/libvips');
|
||||
const platform = buildPlatformArch();
|
||||
const dest = path.join(__dirname, platform);
|
||||
|
||||
// Use same config as prebuild to copy binary files
|
||||
const release = path.join(__dirname, '..', 'src', 'build', 'Release');
|
||||
const prebuildrc = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '.prebuildrc'), 'utf8'));
|
||||
const include = new RegExp(prebuildrc['include-regex'], 'i');
|
||||
fs.cpSync(release, path.join(dest, 'lib'), {
|
||||
recursive: true,
|
||||
filter: (file) => {
|
||||
const name = path.basename(file);
|
||||
return name === 'Release' || include.test(name);
|
||||
}
|
||||
});
|
||||
47
npm/linux-arm/package.json
Normal file
47
npm/linux-arm/package.json
Normal file
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "@img/sharp-linux-arm",
|
||||
"version": "0.33.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Linux (glibc) ARM (32-bit)",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/linux-arm"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-linux-arm": "1.0.2"
|
||||
},
|
||||
"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",
|
||||
"npm": ">=9.6.5",
|
||||
"yarn": ">=3.2.0",
|
||||
"pnpm": ">=7.1.0",
|
||||
"glibc": ">=2.28"
|
||||
},
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"cpu": [
|
||||
"arm"
|
||||
]
|
||||
}
|
||||
47
npm/linux-arm64/package.json
Normal file
47
npm/linux-arm64/package.json
Normal file
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "@img/sharp-linux-arm64",
|
||||
"version": "0.33.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Linux (glibc) 64-bit ARM",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/linux-arm64"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-linux-arm64": "1.0.2"
|
||||
},
|
||||
"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",
|
||||
"npm": ">=9.6.5",
|
||||
"yarn": ">=3.2.0",
|
||||
"pnpm": ">=7.1.0",
|
||||
"glibc": ">=2.26"
|
||||
},
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"cpu": [
|
||||
"arm64"
|
||||
]
|
||||
}
|
||||
47
npm/linux-s390x/package.json
Normal file
47
npm/linux-s390x/package.json
Normal file
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "@img/sharp-linux-s390x",
|
||||
"version": "0.33.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Linux (glibc) s390x",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/linux-s390x"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-linux-s390x": "1.0.2"
|
||||
},
|
||||
"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",
|
||||
"npm": ">=9.6.5",
|
||||
"yarn": ">=3.2.0",
|
||||
"pnpm": ">=7.1.0",
|
||||
"glibc": ">=2.28"
|
||||
},
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"cpu": [
|
||||
"s390x"
|
||||
]
|
||||
}
|
||||
47
npm/linux-x64/package.json
Normal file
47
npm/linux-x64/package.json
Normal file
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "@img/sharp-linux-x64",
|
||||
"version": "0.33.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Linux (glibc) x64",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/linux-x64"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-linux-x64": "1.0.2"
|
||||
},
|
||||
"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",
|
||||
"npm": ">=9.6.5",
|
||||
"yarn": ">=3.2.0",
|
||||
"pnpm": ">=7.1.0",
|
||||
"glibc": ">=2.26"
|
||||
},
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
]
|
||||
}
|
||||
47
npm/linuxmusl-arm64/package.json
Normal file
47
npm/linuxmusl-arm64/package.json
Normal file
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "@img/sharp-linuxmusl-arm64",
|
||||
"version": "0.33.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Linux (musl) 64-bit ARM",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/linuxmusl-arm64"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-linuxmusl-arm64": "1.0.2"
|
||||
},
|
||||
"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",
|
||||
"npm": ">=9.6.5",
|
||||
"yarn": ">=3.2.0",
|
||||
"pnpm": ">=7.1.0",
|
||||
"musl": ">=1.2.2"
|
||||
},
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"cpu": [
|
||||
"arm64"
|
||||
]
|
||||
}
|
||||
47
npm/linuxmusl-x64/package.json
Normal file
47
npm/linuxmusl-x64/package.json
Normal file
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "@img/sharp-linuxmusl-x64",
|
||||
"version": "0.33.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Linux (musl) x64",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/linuxmusl-x64"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-linuxmusl-x64": "1.0.2"
|
||||
},
|
||||
"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",
|
||||
"npm": ">=9.6.5",
|
||||
"yarn": ">=3.2.0",
|
||||
"pnpm": ">=7.1.0",
|
||||
"musl": ">=1.2.2"
|
||||
},
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
]
|
||||
}
|
||||
18
npm/package.json
Normal file
18
npm/package.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "@img/sharp",
|
||||
"version": "0.33.3-rc.0",
|
||||
"private": "true",
|
||||
"workspaces": [
|
||||
"darwin-arm64",
|
||||
"darwin-x64",
|
||||
"linux-arm",
|
||||
"linux-arm64",
|
||||
"linux-s390x",
|
||||
"linux-x64",
|
||||
"linuxmusl-arm64",
|
||||
"linuxmusl-x64",
|
||||
"wasm32",
|
||||
"win32-ia32",
|
||||
"win32-x64"
|
||||
]
|
||||
}
|
||||
42
npm/wasm32/package.json
Normal file
42
npm/wasm32/package.json
Normal file
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "@img/sharp-wasm32",
|
||||
"version": "0.33.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with wasm32",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/wasm32"
|
||||
},
|
||||
"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"files": [
|
||||
"lib",
|
||||
"versions.json"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
"./sharp.node": "./lib/sharp-wasm32.node.js",
|
||||
"./package": "./package.json",
|
||||
"./versions": "./versions.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0",
|
||||
"npm": ">=9.6.5",
|
||||
"yarn": ">=3.2.0",
|
||||
"pnpm": ">=7.1.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@emnapi/runtime": "^1.1.0"
|
||||
},
|
||||
"cpu": [
|
||||
"wasm32"
|
||||
]
|
||||
}
|
||||
42
npm/win32-ia32/package.json
Normal file
42
npm/win32-ia32/package.json
Normal file
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "@img/sharp-win32-ia32",
|
||||
"version": "0.33.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Windows x86 (32-bit)",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/win32-ia32"
|
||||
},
|
||||
"license": "Apache-2.0 AND LGPL-3.0-or-later",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"files": [
|
||||
"lib",
|
||||
"versions.json"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
"./sharp.node": "./lib/sharp-win32-ia32.node",
|
||||
"./package": "./package.json",
|
||||
"./versions": "./versions.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0",
|
||||
"npm": ">=9.6.5",
|
||||
"yarn": ">=3.2.0",
|
||||
"pnpm": ">=7.1.0"
|
||||
},
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"cpu": [
|
||||
"ia32"
|
||||
]
|
||||
}
|
||||
42
npm/win32-x64/package.json
Normal file
42
npm/win32-x64/package.json
Normal file
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "@img/sharp-win32-x64",
|
||||
"version": "0.33.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Windows x64",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/win32-x64"
|
||||
},
|
||||
"license": "Apache-2.0 AND LGPL-3.0-or-later",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"files": [
|
||||
"lib",
|
||||
"versions.json"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
"./sharp.node": "./lib/sharp-win32-x64.node",
|
||||
"./package": "./package.json",
|
||||
"./versions": "./versions.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0",
|
||||
"npm": ">=9.6.5",
|
||||
"yarn": ">=3.2.0",
|
||||
"pnpm": ">=7.1.0"
|
||||
},
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
]
|
||||
}
|
||||
139
package.json
139
package.json
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"name": "sharp",
|
||||
"description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP and TIFF images",
|
||||
"version": "0.26.0-beta1",
|
||||
"description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images",
|
||||
"version": "0.33.3-rc.0",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://github.com/lovell/sharp",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"contributors": [
|
||||
"Pierre Inglebert <pierre.inglebert@gmail.com>",
|
||||
"Jonathan Ong <jonathanrichardong@gmail.com>",
|
||||
@@ -69,39 +69,63 @@
|
||||
"Edward Silverton <e.silverton@gmail.com>",
|
||||
"Roman Malieiev <aromaleev@gmail.com>",
|
||||
"Tomas Szabo <tomas.szabo@deftomat.com>",
|
||||
"Robert O'Rourke <robert@o-rourke.org>"
|
||||
"Robert O'Rourke <robert@o-rourke.org>",
|
||||
"Guillermo Alfonso Varela Chouciño <guillevch@gmail.com>",
|
||||
"Christian Flintrup <chr@gigahost.dk>",
|
||||
"Manan Jadhav <manan@motionden.com>",
|
||||
"Leon Radley <leon@radley.se>",
|
||||
"alza54 <alza54@thiocod.in>",
|
||||
"Jacob Smith <jacob@frende.me>",
|
||||
"Michael Nutt <michael@nutt.im>",
|
||||
"Brad Parham <baparham@gmail.com>",
|
||||
"Taneli Vatanen <taneli.vatanen@gmail.com>",
|
||||
"Joris Dugué <zaruike10@gmail.com>",
|
||||
"Chris Banks <christopher.bradley.banks@gmail.com>",
|
||||
"Ompal Singh <ompal.hitm09@gmail.com>",
|
||||
"Brodan <christopher.hranj@gmail.com",
|
||||
"Ankur Parihar <ankur.github@gmail.com>",
|
||||
"Brahim Ait elhaj <brahima@gmail.com>",
|
||||
"Mart Jansink <m.jansink@gmail.com>",
|
||||
"Lachlan Newman <lachnewman007@gmail.com>",
|
||||
"Dennis Beatty <dennis@dcbeatty.com>",
|
||||
"Ingvar Stepanyan <me@rreverser.com>"
|
||||
],
|
||||
"scripts": {
|
||||
"install": "(node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)",
|
||||
"clean": "rm -rf node_modules/ build/ vendor/ .nyc_output/ coverage/ test/fixtures/output.*",
|
||||
"test": "semistandard && cpplint && npm run test-unit && npm run test-licensing && node install/prebuild-ci",
|
||||
"test-unit": "nyc --reporter=lcov --branches=99 mocha --slow=5000 --timeout=60000 ./test/unit/*.js",
|
||||
"test-licensing": "license-checker --production --summary --onlyAllow=\"Apache-2.0;BSD;ISC;MIT\"",
|
||||
"test-coverage": "./test/coverage/report.sh",
|
||||
"install": "node install/check",
|
||||
"clean": "rm -rf src/build/ .nyc_output/ coverage/ test/fixtures/output.*",
|
||||
"test": "npm run test-lint && npm run test-unit && npm run test-licensing && npm run test-types",
|
||||
"test-lint": "semistandard && cpplint",
|
||||
"test-unit": "nyc --reporter=lcov --reporter=text --check-coverage --branches=100 mocha",
|
||||
"test-licensing": "license-checker --production --summary --onlyAllow=\"Apache-2.0;BSD;ISC;LGPL-3.0-or-later;MIT\"",
|
||||
"test-leak": "./test/leak/leak.sh",
|
||||
"docs-build": "documentation lint lib && for m in constructor input resize composite operation colour channel output utility; do documentation build --shallow --format=md --markdown-toc=false lib/$m.js >docs/api-$m.md; done && node docs/search-index/build",
|
||||
"test-types": "tsd",
|
||||
"package-from-local-build": "node npm/from-local-build",
|
||||
"package-from-github-release": "node npm/from-github-release",
|
||||
"docs-build": "node docs/build && node docs/search-index/build",
|
||||
"docs-serve": "cd docs && npx serve",
|
||||
"docs-publish": "cd docs && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/index.d.ts",
|
||||
"files": [
|
||||
"binding.gyp",
|
||||
"install/**",
|
||||
"!install/prebuild-ci.js",
|
||||
"lib/**",
|
||||
"src/**"
|
||||
"install",
|
||||
"lib",
|
||||
"src/*.{cc,h,gyp}"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/lovell/sharp"
|
||||
"url": "git://github.com/lovell/sharp.git"
|
||||
},
|
||||
"keywords": [
|
||||
"jpeg",
|
||||
"png",
|
||||
"webp",
|
||||
"avif",
|
||||
"tiff",
|
||||
"gif",
|
||||
"svg",
|
||||
"jp2",
|
||||
"dzi",
|
||||
"image",
|
||||
"resize",
|
||||
@@ -112,46 +136,65 @@
|
||||
"vips"
|
||||
],
|
||||
"dependencies": {
|
||||
"color": "^3.1.2",
|
||||
"detect-libc": "^1.0.3",
|
||||
"node-addon-api": "^3.0.0",
|
||||
"npmlog": "^4.1.2",
|
||||
"prebuild-install": "^5.3.5",
|
||||
"semver": "^7.3.2",
|
||||
"simple-get": "^4.0.0",
|
||||
"tar-fs": "^2.1.0",
|
||||
"tunnel-agent": "^0.6.0"
|
||||
"color": "^4.2.3",
|
||||
"detect-libc": "^2.0.3",
|
||||
"semver": "^7.6.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-darwin-arm64": "0.33.3-rc.0",
|
||||
"@img/sharp-darwin-x64": "0.33.3-rc.0",
|
||||
"@img/sharp-libvips-darwin-arm64": "1.0.2",
|
||||
"@img/sharp-libvips-darwin-x64": "1.0.2",
|
||||
"@img/sharp-libvips-linux-arm": "1.0.2",
|
||||
"@img/sharp-libvips-linux-arm64": "1.0.2",
|
||||
"@img/sharp-libvips-linux-s390x": "1.0.2",
|
||||
"@img/sharp-libvips-linux-x64": "1.0.2",
|
||||
"@img/sharp-libvips-linuxmusl-arm64": "1.0.2",
|
||||
"@img/sharp-libvips-linuxmusl-x64": "1.0.2",
|
||||
"@img/sharp-linux-arm": "0.33.3-rc.0",
|
||||
"@img/sharp-linux-arm64": "0.33.3-rc.0",
|
||||
"@img/sharp-linux-s390x": "0.33.3-rc.0",
|
||||
"@img/sharp-linux-x64": "0.33.3-rc.0",
|
||||
"@img/sharp-linuxmusl-arm64": "0.33.3-rc.0",
|
||||
"@img/sharp-linuxmusl-x64": "0.33.3-rc.0",
|
||||
"@img/sharp-wasm32": "0.33.3-rc.0",
|
||||
"@img/sharp-win32-ia32": "0.33.3-rc.0",
|
||||
"@img/sharp-win32-x64": "0.33.3-rc.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"async": "^3.2.0",
|
||||
"cc": "^2.0.1",
|
||||
"decompress-zip": "^0.3.2",
|
||||
"documentation": "^13.0.2",
|
||||
"exif-reader": "^1.0.3",
|
||||
"icc": "^2.0.0",
|
||||
"@emnapi/runtime": "^1.1.0",
|
||||
"@img/sharp-libvips-dev": "1.0.2",
|
||||
"@img/sharp-libvips-dev-wasm32": "1.0.3",
|
||||
"@img/sharp-libvips-win32-ia32": "1.0.2",
|
||||
"@img/sharp-libvips-win32-x64": "1.0.2",
|
||||
"@types/node": "*",
|
||||
"async": "^3.2.5",
|
||||
"cc": "^3.0.1",
|
||||
"emnapi": "^1.1.0",
|
||||
"exif-reader": "^2.0.1",
|
||||
"extract-zip": "^2.0.1",
|
||||
"icc": "^3.0.0",
|
||||
"jsdoc-to-markdown": "^8.0.1",
|
||||
"license-checker": "^25.0.1",
|
||||
"mocha": "^8.1.1",
|
||||
"mock-fs": "^4.13.0",
|
||||
"mocha": "^10.3.0",
|
||||
"node-addon-api": "^8.0.0",
|
||||
"nyc": "^15.1.0",
|
||||
"prebuild": "^10.0.1",
|
||||
"rimraf": "^3.0.2",
|
||||
"semistandard": "^14.2.3"
|
||||
"prebuild": "^13.0.0",
|
||||
"semistandard": "^17.0.0",
|
||||
"tar-fs": "^3.0.5",
|
||||
"tsd": "^0.30.7"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"config": {
|
||||
"libvips": "8.10.0",
|
||||
"runtime": "napi",
|
||||
"target": 3
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.16.0"
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0",
|
||||
"libvips": ">=8.15.2"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"binary": {
|
||||
"napi_versions": [
|
||||
3
|
||||
9
|
||||
]
|
||||
},
|
||||
"semistandard": {
|
||||
@@ -164,5 +207,13 @@
|
||||
"filter": [
|
||||
"build/include"
|
||||
]
|
||||
},
|
||||
"nyc": {
|
||||
"include": [
|
||||
"lib"
|
||||
]
|
||||
},
|
||||
"tsd": {
|
||||
"directory": "test/types/"
|
||||
}
|
||||
}
|
||||
|
||||
280
src/binding.gyp
Normal file
280
src/binding.gyp
Normal file
@@ -0,0 +1,280 @@
|
||||
# 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',
|
||||
'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': [
|
||||
'<(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': {
|
||||
'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=9',
|
||||
'NODE_ADDON_API_DISABLE_DEPRECATED',
|
||||
'NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS'
|
||||
],
|
||||
'dependencies': [
|
||||
'<!(node -p "require(\'node-addon-api\').gyp")',
|
||||
'libvips-cpp'
|
||||
],
|
||||
'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.42.dylib'
|
||||
]
|
||||
},
|
||||
'xcode_settings': {
|
||||
'OTHER_LDFLAGS': [
|
||||
# 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'
|
||||
],
|
||||
'link_settings': {
|
||||
'libraries': [
|
||||
'-l:libvips-cpp.so.42'
|
||||
],
|
||||
'ldflags': [
|
||||
'-Wl,-s',
|
||||
'-Wl,--disable-new-dtags',
|
||||
'-Wl,-z,nodelete',
|
||||
'-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=["_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++0x',
|
||||
'-fexceptions',
|
||||
'-Wall',
|
||||
'-Os'
|
||||
],
|
||||
'xcode_settings': {
|
||||
'CLANG_CXX_LANGUAGE_STANDARD': 'c++11',
|
||||
'MACOSX_DEPLOYMENT_TARGET': '10.13',
|
||||
'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': {
|
||||
'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'
|
||||
]
|
||||
}]
|
||||
}]
|
||||
]
|
||||
}]
|
||||
}
|
||||
578
src/common.cc
578
src/common.cc
@@ -1,16 +1,5 @@
|
||||
// Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Lovell Fuller and contributors.
|
||||
//
|
||||
// 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.
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
@@ -36,6 +25,9 @@ namespace sharp {
|
||||
std::string AttrAsStr(Napi::Object obj, std::string attr) {
|
||||
return obj.Get(attr).As<Napi::String>();
|
||||
}
|
||||
std::string AttrAsStr(Napi::Object obj, unsigned int const attr) {
|
||||
return obj.Get(attr).As<Napi::String>();
|
||||
}
|
||||
uint32_t AttrAsUint32(Napi::Object obj, std::string attr) {
|
||||
return obj.Get(attr).As<Napi::Number>().Uint32Value();
|
||||
}
|
||||
@@ -45,6 +37,9 @@ namespace sharp {
|
||||
int32_t AttrAsInt32(Napi::Object obj, unsigned int const attr) {
|
||||
return obj.Get(attr).As<Napi::Number>().Int32Value();
|
||||
}
|
||||
int64_t AttrAsInt64(Napi::Object obj, std::string attr) {
|
||||
return obj.Get(attr).As<Napi::Number>().Int64Value();
|
||||
}
|
||||
double AttrAsDouble(Napi::Object obj, std::string attr) {
|
||||
return obj.Get(attr).As<Napi::Number>().DoubleValue();
|
||||
}
|
||||
@@ -54,13 +49,13 @@ namespace sharp {
|
||||
bool AttrAsBool(Napi::Object obj, std::string attr) {
|
||||
return obj.Get(attr).As<Napi::Boolean>().Value();
|
||||
}
|
||||
std::vector<double> AttrAsRgba(Napi::Object obj, std::string attr) {
|
||||
Napi::Array background = obj.Get(attr).As<Napi::Array>();
|
||||
std::vector<double> rgba(background.Length());
|
||||
for (unsigned int i = 0; i < background.Length(); i++) {
|
||||
rgba[i] = AttrAsDouble(background, i);
|
||||
std::vector<double> AttrAsVectorOfDouble(Napi::Object obj, std::string attr) {
|
||||
Napi::Array napiArray = obj.Get(attr).As<Napi::Array>();
|
||||
std::vector<double> vectorOfDouble(napiArray.Length());
|
||||
for (unsigned int i = 0; i < napiArray.Length(); i++) {
|
||||
vectorOfDouble[i] = AttrAsDouble(napiArray, i);
|
||||
}
|
||||
return rgba;
|
||||
return vectorOfDouble;
|
||||
}
|
||||
std::vector<int32_t> AttrAsInt32Vector(Napi::Object obj, std::string attr) {
|
||||
Napi::Array array = obj.Get(attr).As<Napi::Array>();
|
||||
@@ -82,16 +77,22 @@ namespace sharp {
|
||||
descriptor->buffer = buffer.Data();
|
||||
descriptor->isBuffer = TRUE;
|
||||
}
|
||||
descriptor->failOnError = AttrAsBool(input, "failOnError");
|
||||
descriptor->failOn = AttrAsEnum<VipsFailOn>(input, "failOn", VIPS_TYPE_FAIL_ON);
|
||||
// Density for vector-based input
|
||||
if (HasAttr(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
|
||||
if (HasAttr(input, "rawChannels")) {
|
||||
descriptor->rawDepth = AttrAsEnum<VipsBandFormat>(input, "rawDepth", VIPS_TYPE_BAND_FORMAT);
|
||||
descriptor->rawChannels = AttrAsUint32(input, "rawChannels");
|
||||
descriptor->rawWidth = AttrAsUint32(input, "rawWidth");
|
||||
descriptor->rawHeight = AttrAsUint32(input, "rawHeight");
|
||||
descriptor->rawPremultiplied = AttrAsBool(input, "rawPremultiplied");
|
||||
}
|
||||
// Multi-page input (GIF, TIFF, PDF)
|
||||
if (HasAttr(input, "pages")) {
|
||||
@@ -104,25 +105,71 @@ namespace sharp {
|
||||
if (HasAttr(input, "level")) {
|
||||
descriptor->level = AttrAsUint32(input, "level");
|
||||
}
|
||||
// subIFD (OME-TIFF)
|
||||
if (HasAttr(input, "subifd")) {
|
||||
descriptor->subifd = AttrAsInt32(input, "subifd");
|
||||
}
|
||||
// Create new image
|
||||
if (HasAttr(input, "createChannels")) {
|
||||
descriptor->createChannels = AttrAsUint32(input, "createChannels");
|
||||
descriptor->createWidth = AttrAsUint32(input, "createWidth");
|
||||
descriptor->createHeight = AttrAsUint32(input, "createHeight");
|
||||
descriptor->createBackground = AttrAsRgba(input, "createBackground");
|
||||
if (HasAttr(input, "createNoiseType")) {
|
||||
descriptor->createNoiseType = AttrAsStr(input, "createNoiseType");
|
||||
descriptor->createNoiseMean = AttrAsDouble(input, "createNoiseMean");
|
||||
descriptor->createNoiseSigma = AttrAsDouble(input, "createNoiseSigma");
|
||||
} else {
|
||||
descriptor->createBackground = AttrAsVectorOfDouble(input, "createBackground");
|
||||
}
|
||||
}
|
||||
// Create new image with text
|
||||
if (HasAttr(input, "textValue")) {
|
||||
descriptor->textValue = AttrAsStr(input, "textValue");
|
||||
if (HasAttr(input, "textFont")) {
|
||||
descriptor->textFont = AttrAsStr(input, "textFont");
|
||||
}
|
||||
if (HasAttr(input, "textFontfile")) {
|
||||
descriptor->textFontfile = AttrAsStr(input, "textFontfile");
|
||||
}
|
||||
if (HasAttr(input, "textWidth")) {
|
||||
descriptor->textWidth = AttrAsUint32(input, "textWidth");
|
||||
}
|
||||
if (HasAttr(input, "textHeight")) {
|
||||
descriptor->textHeight = AttrAsUint32(input, "textHeight");
|
||||
}
|
||||
if (HasAttr(input, "textAlign")) {
|
||||
descriptor->textAlign = AttrAsEnum<VipsAlign>(input, "textAlign", VIPS_TYPE_ALIGN);
|
||||
}
|
||||
if (HasAttr(input, "textJustify")) {
|
||||
descriptor->textJustify = AttrAsBool(input, "textJustify");
|
||||
}
|
||||
if (HasAttr(input, "textDpi")) {
|
||||
descriptor->textDpi = AttrAsUint32(input, "textDpi");
|
||||
}
|
||||
if (HasAttr(input, "textRgba")) {
|
||||
descriptor->textRgba = AttrAsBool(input, "textRgba");
|
||||
}
|
||||
if (HasAttr(input, "textSpacing")) {
|
||||
descriptor->textSpacing = AttrAsUint32(input, "textSpacing");
|
||||
}
|
||||
if (HasAttr(input, "textWrap")) {
|
||||
descriptor->textWrap = AttrAsEnum<VipsTextWrap>(input, "textWrap", VIPS_TYPE_TEXT_WRAP);
|
||||
}
|
||||
}
|
||||
// Limit input images to a given number of pixels, where pixels = width * height
|
||||
descriptor->limitInputPixels = AttrAsUint32(input, "limitInputPixels");
|
||||
descriptor->limitInputPixels = static_cast<uint64_t>(AttrAsInt64(input, "limitInputPixels"));
|
||||
// Allow switch from random to sequential access
|
||||
descriptor->access = AttrAsBool(input, "sequentialRead") ? VIPS_ACCESS_SEQUENTIAL : VIPS_ACCESS_RANDOM;
|
||||
// Remove safety features and allow unlimited input
|
||||
descriptor->unlimited = AttrAsBool(input, "unlimited");
|
||||
return descriptor;
|
||||
}
|
||||
|
||||
// How many tasks are in the queue?
|
||||
volatile int counterQueue = 0;
|
||||
std::atomic<int> counterQueue{0};
|
||||
|
||||
// How many tasks are being processed?
|
||||
volatile int counterProcess = 0;
|
||||
std::atomic<int> counterProcess{0};
|
||||
|
||||
// Filename extension checkers
|
||||
static bool EndsWith(std::string const &str, std::string const &end) {
|
||||
@@ -140,6 +187,10 @@ namespace sharp {
|
||||
bool IsGif(std::string const &str) {
|
||||
return EndsWith(str, ".gif") || EndsWith(str, ".GIF");
|
||||
}
|
||||
bool IsJp2(std::string const &str) {
|
||||
return EndsWith(str, ".jp2") || EndsWith(str, ".jpx") || EndsWith(str, ".j2k") || EndsWith(str, ".j2c")
|
||||
|| EndsWith(str, ".JP2") || EndsWith(str, ".JPX") || EndsWith(str, ".J2K") || EndsWith(str, ".J2C");
|
||||
}
|
||||
bool IsTiff(std::string const &str) {
|
||||
return EndsWith(str, ".tif") || EndsWith(str, ".tiff") || EndsWith(str, ".TIF") || EndsWith(str, ".TIFF");
|
||||
}
|
||||
@@ -152,6 +203,9 @@ namespace sharp {
|
||||
bool IsAvif(std::string const &str) {
|
||||
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) {
|
||||
return EndsWith(str, ".dzi") || EndsWith(str, ".DZI");
|
||||
}
|
||||
@@ -162,6 +216,13 @@ namespace sharp {
|
||||
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.
|
||||
*/
|
||||
@@ -173,6 +234,7 @@ namespace sharp {
|
||||
case ImageType::WEBP: id = "webp"; break;
|
||||
case ImageType::TIFF: id = "tiff"; break;
|
||||
case ImageType::GIF: id = "gif"; break;
|
||||
case ImageType::JP2: id = "jp2"; break;
|
||||
case ImageType::SVG: id = "svg"; break;
|
||||
case ImageType::HEIF: id = "heif"; break;
|
||||
case ImageType::PDF: id = "pdf"; break;
|
||||
@@ -180,6 +242,8 @@ namespace sharp {
|
||||
case ImageType::OPENSLIDE: id = "openslide"; break;
|
||||
case ImageType::PPM: id = "ppm"; break;
|
||||
case ImageType::FITS: id = "fits"; break;
|
||||
case ImageType::EXR: id = "exr"; break;
|
||||
case ImageType::JXL: id = "jxl"; break;
|
||||
case ImageType::VIPS: id = "vips"; break;
|
||||
case ImageType::RAW: id = "raw"; break;
|
||||
case ImageType::UNKNOWN: id = "unknown"; break;
|
||||
@@ -188,30 +252,47 @@ namespace sharp {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Regenerate this table with something like:
|
||||
*
|
||||
* $ vips -l foreign | grep -i load | awk '{ print $2, $1; }'
|
||||
*
|
||||
* Plus a bit of editing.
|
||||
*/
|
||||
std::map<std::string, ImageType> loaderToType = {
|
||||
{ "jpegload", ImageType::JPEG },
|
||||
{ "jpegload_buffer", ImageType::JPEG },
|
||||
{ "pngload", ImageType::PNG },
|
||||
{ "pngload_buffer", ImageType::PNG },
|
||||
{ "webpload", ImageType::WEBP },
|
||||
{ "webpload_buffer", ImageType::WEBP },
|
||||
{ "tiffload", ImageType::TIFF },
|
||||
{ "tiffload_buffer", ImageType::TIFF },
|
||||
{ "gifload", ImageType::GIF },
|
||||
{ "gifload_buffer", ImageType::GIF },
|
||||
{ "svgload", ImageType::SVG },
|
||||
{ "svgload_buffer", ImageType::SVG },
|
||||
{ "heifload", ImageType::HEIF },
|
||||
{ "heifload_buffer", ImageType::HEIF },
|
||||
{ "pdfload", ImageType::PDF },
|
||||
{ "pdfload_buffer", ImageType::PDF },
|
||||
{ "magickload", ImageType::MAGICK },
|
||||
{ "magickload_buffer", ImageType::MAGICK },
|
||||
{ "openslideload", ImageType::OPENSLIDE },
|
||||
{ "ppmload", ImageType::PPM },
|
||||
{ "fitsload", ImageType::FITS },
|
||||
{ "vipsload", ImageType::VIPS },
|
||||
{ "rawload", ImageType::RAW }
|
||||
{ "VipsForeignLoadJpegFile", ImageType::JPEG },
|
||||
{ "VipsForeignLoadJpegBuffer", ImageType::JPEG },
|
||||
{ "VipsForeignLoadPngFile", ImageType::PNG },
|
||||
{ "VipsForeignLoadPngBuffer", ImageType::PNG },
|
||||
{ "VipsForeignLoadWebpFile", ImageType::WEBP },
|
||||
{ "VipsForeignLoadWebpBuffer", ImageType::WEBP },
|
||||
{ "VipsForeignLoadTiffFile", ImageType::TIFF },
|
||||
{ "VipsForeignLoadTiffBuffer", ImageType::TIFF },
|
||||
{ "VipsForeignLoadGifFile", ImageType::GIF },
|
||||
{ "VipsForeignLoadGifBuffer", ImageType::GIF },
|
||||
{ "VipsForeignLoadNsgifFile", ImageType::GIF },
|
||||
{ "VipsForeignLoadNsgifBuffer", ImageType::GIF },
|
||||
{ "VipsForeignLoadJp2kBuffer", ImageType::JP2 },
|
||||
{ "VipsForeignLoadJp2kFile", ImageType::JP2 },
|
||||
{ "VipsForeignLoadSvgFile", ImageType::SVG },
|
||||
{ "VipsForeignLoadSvgBuffer", ImageType::SVG },
|
||||
{ "VipsForeignLoadHeifFile", ImageType::HEIF },
|
||||
{ "VipsForeignLoadHeifBuffer", ImageType::HEIF },
|
||||
{ "VipsForeignLoadPdfFile", ImageType::PDF },
|
||||
{ "VipsForeignLoadPdfBuffer", ImageType::PDF },
|
||||
{ "VipsForeignLoadMagickFile", ImageType::MAGICK },
|
||||
{ "VipsForeignLoadMagickBuffer", ImageType::MAGICK },
|
||||
{ "VipsForeignLoadMagick7File", ImageType::MAGICK },
|
||||
{ "VipsForeignLoadMagick7Buffer", ImageType::MAGICK },
|
||||
{ "VipsForeignLoadOpenslideFile", ImageType::OPENSLIDE },
|
||||
{ "VipsForeignLoadPpmFile", ImageType::PPM },
|
||||
{ "VipsForeignLoadFitsFile", ImageType::FITS },
|
||||
{ "VipsForeignLoadOpenexr", ImageType::EXR },
|
||||
{ "VipsForeignLoadJxlFile", ImageType::JXL },
|
||||
{ "VipsForeignLoadJxlBuffer", ImageType::JXL },
|
||||
{ "VipsForeignLoadVips", ImageType::VIPS },
|
||||
{ "VipsForeignLoadVipsFile", ImageType::VIPS },
|
||||
{ "VipsForeignLoadRaw", ImageType::RAW }
|
||||
};
|
||||
|
||||
/*
|
||||
@@ -221,7 +302,7 @@ namespace sharp {
|
||||
ImageType imageType = ImageType::UNKNOWN;
|
||||
char const *load = vips_foreign_find_load_buffer(buffer, length);
|
||||
if (load != nullptr) {
|
||||
auto it = loaderToType.find(vips_nickname_find(g_type_from_name(load)));
|
||||
auto it = loaderToType.find(load);
|
||||
if (it != loaderToType.end()) {
|
||||
imageType = it->second;
|
||||
}
|
||||
@@ -236,7 +317,7 @@ namespace sharp {
|
||||
ImageType imageType = ImageType::UNKNOWN;
|
||||
char const *load = vips_foreign_find_load(file);
|
||||
if (load != nullptr) {
|
||||
auto it = loaderToType.find(vips_nickname_find(g_type_from_name(load)));
|
||||
auto it = loaderToType.find(load);
|
||||
if (it != loaderToType.end()) {
|
||||
imageType = it->second;
|
||||
}
|
||||
@@ -256,11 +337,23 @@ namespace sharp {
|
||||
imageType == ImageType::WEBP ||
|
||||
imageType == ImageType::MAGICK ||
|
||||
imageType == ImageType::GIF ||
|
||||
imageType == ImageType::JP2 ||
|
||||
imageType == ImageType::TIFF ||
|
||||
imageType == ImageType::HEIF ||
|
||||
imageType == ImageType::PDF;
|
||||
}
|
||||
|
||||
/*
|
||||
Does this image type support removal of safety limits?
|
||||
*/
|
||||
bool ImageTypeSupportsUnlimited(ImageType imageType) {
|
||||
return
|
||||
imageType == ImageType::JPEG ||
|
||||
imageType == ImageType::PNG ||
|
||||
imageType == ImageType::SVG ||
|
||||
imageType == ImageType::HEIF;
|
||||
}
|
||||
|
||||
/*
|
||||
Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data)
|
||||
*/
|
||||
@@ -270,12 +363,16 @@ namespace sharp {
|
||||
if (descriptor->isBuffer) {
|
||||
if (descriptor->rawChannels > 0) {
|
||||
// Raw, uncompressed pixel data
|
||||
bool const is8bit = vips_band_format_is8bit(descriptor->rawDepth);
|
||||
image = VImage::new_from_memory(descriptor->buffer, descriptor->bufferLength,
|
||||
descriptor->rawWidth, descriptor->rawHeight, descriptor->rawChannels, VIPS_FORMAT_UCHAR);
|
||||
descriptor->rawWidth, descriptor->rawHeight, descriptor->rawChannels, descriptor->rawDepth);
|
||||
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 {
|
||||
image.get_image()->Type = VIPS_INTERPRETATION_sRGB;
|
||||
image.get_image()->Type = is8bit ? VIPS_INTERPRETATION_sRGB : VIPS_INTERPRETATION_RGB16;
|
||||
}
|
||||
if (descriptor->rawPremultiplied) {
|
||||
image = image.unpremultiply();
|
||||
}
|
||||
imageType = ImageType::RAW;
|
||||
} else {
|
||||
@@ -285,8 +382,8 @@ namespace sharp {
|
||||
try {
|
||||
vips::VOption *option = VImage::option()
|
||||
->set("access", descriptor->access)
|
||||
->set("fail", descriptor->failOnError);
|
||||
if (imageType == ImageType::SVG) {
|
||||
->set("fail_on", descriptor->failOn);
|
||||
if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {
|
||||
option->set("unlimited", TRUE);
|
||||
}
|
||||
if (imageType == ImageType::SVG || imageType == ImageType::PDF) {
|
||||
@@ -302,6 +399,9 @@ namespace sharp {
|
||||
if (imageType == ImageType::OPENSLIDE) {
|
||||
option->set("level", descriptor->level);
|
||||
}
|
||||
if (imageType == ImageType::TIFF) {
|
||||
option->set("subifd", descriptor->subifd);
|
||||
}
|
||||
image = VImage::new_from_buffer(descriptor->buffer, descriptor->bufferLength, nullptr, option);
|
||||
if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) {
|
||||
image = SetDensity(image, descriptor->density);
|
||||
@@ -314,31 +414,80 @@ namespace sharp {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (descriptor->createChannels > 0) {
|
||||
int const channels = descriptor->createChannels;
|
||||
if (channels > 0) {
|
||||
// Create new image
|
||||
std::vector<double> background = {
|
||||
descriptor->createBackground[0],
|
||||
descriptor->createBackground[1],
|
||||
descriptor->createBackground[2]
|
||||
};
|
||||
if (descriptor->createChannels == 4) {
|
||||
background.push_back(descriptor->createBackground[3]);
|
||||
if (descriptor->createNoiseType == "gaussian") {
|
||||
std::vector<VImage> bands = {};
|
||||
bands.reserve(channels);
|
||||
for (int _band = 0; _band < channels; _band++) {
|
||||
bands.push_back(VImage::gaussnoise(descriptor->createWidth, descriptor->createHeight, VImage::option()
|
||||
->set("mean", descriptor->createNoiseMean)
|
||||
->set("sigma", descriptor->createNoiseSigma)));
|
||||
}
|
||||
image = VImage::bandjoin(bands).copy(VImage::option()->set("interpretation",
|
||||
channels < 3 ? VIPS_INTERPRETATION_B_W: VIPS_INTERPRETATION_sRGB));
|
||||
} else {
|
||||
std::vector<double> background = {
|
||||
descriptor->createBackground[0],
|
||||
descriptor->createBackground[1],
|
||||
descriptor->createBackground[2]
|
||||
};
|
||||
if (channels == 4) {
|
||||
background.push_back(descriptor->createBackground[3]);
|
||||
}
|
||||
image = VImage::new_matrix(descriptor->createWidth, descriptor->createHeight)
|
||||
.copy(VImage::option()->set("interpretation",
|
||||
channels < 3 ? VIPS_INTERPRETATION_B_W : VIPS_INTERPRETATION_sRGB))
|
||||
.new_from_image(background);
|
||||
}
|
||||
image = image.cast(VIPS_FORMAT_UCHAR);
|
||||
imageType = ImageType::RAW;
|
||||
} else if (descriptor->textValue.length() > 0) {
|
||||
// Create a new image with text
|
||||
vips::VOption *textOptions = VImage::option()
|
||||
->set("align", descriptor->textAlign)
|
||||
->set("justify", descriptor->textJustify)
|
||||
->set("rgba", descriptor->textRgba)
|
||||
->set("spacing", descriptor->textSpacing)
|
||||
->set("wrap", descriptor->textWrap)
|
||||
->set("autofit_dpi", &descriptor->textAutofitDpi);
|
||||
if (descriptor->textWidth > 0) {
|
||||
textOptions->set("width", descriptor->textWidth);
|
||||
}
|
||||
// Ignore dpi if height is set
|
||||
if (descriptor->textWidth > 0 && descriptor->textHeight > 0) {
|
||||
textOptions->set("height", descriptor->textHeight);
|
||||
} else if (descriptor->textDpi > 0) {
|
||||
textOptions->set("dpi", descriptor->textDpi);
|
||||
}
|
||||
if (descriptor->textFont.length() > 0) {
|
||||
textOptions->set("font", const_cast<char*>(descriptor->textFont.data()));
|
||||
}
|
||||
if (descriptor->textFontfile.length() > 0) {
|
||||
textOptions->set("fontfile", const_cast<char*>(descriptor->textFontfile.data()));
|
||||
}
|
||||
image = VImage::text(const_cast<char *>(descriptor->textValue.data()), textOptions);
|
||||
if (!descriptor->textRgba) {
|
||||
image = image.copy(VImage::option()->set("interpretation", VIPS_INTERPRETATION_B_W));
|
||||
}
|
||||
image = VImage::new_matrix(descriptor->createWidth, descriptor->createHeight).new_from_image(background);
|
||||
image.get_image()->Type = VIPS_INTERPRETATION_sRGB;
|
||||
imageType = ImageType::RAW;
|
||||
} else {
|
||||
// From filesystem
|
||||
imageType = DetermineImageType(descriptor->file.data());
|
||||
if (imageType == ImageType::MISSING) {
|
||||
throw vips::VError("Input file is missing");
|
||||
if (descriptor->file.find("<svg") != std::string::npos) {
|
||||
throw vips::VError("Input file is missing, did you mean "
|
||||
"sharp(Buffer.from('" + descriptor->file.substr(0, 8) + "...')?");
|
||||
}
|
||||
throw vips::VError("Input file is missing: " + descriptor->file);
|
||||
}
|
||||
if (imageType != ImageType::UNKNOWN) {
|
||||
try {
|
||||
vips::VOption *option = VImage::option()
|
||||
->set("access", descriptor->access)
|
||||
->set("fail", descriptor->failOnError);
|
||||
if (imageType == ImageType::SVG) {
|
||||
->set("fail_on", descriptor->failOn);
|
||||
if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {
|
||||
option->set("unlimited", TRUE);
|
||||
}
|
||||
if (imageType == ImageType::SVG || imageType == ImageType::PDF) {
|
||||
@@ -354,6 +503,9 @@ namespace sharp {
|
||||
if (imageType == ImageType::OPENSLIDE) {
|
||||
option->set("level", descriptor->level);
|
||||
}
|
||||
if (imageType == ImageType::TIFF) {
|
||||
option->set("subifd", descriptor->subifd);
|
||||
}
|
||||
image = VImage::new_from_file(descriptor->file.data(), option);
|
||||
if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) {
|
||||
image = SetDensity(image, descriptor->density);
|
||||
@@ -366,9 +518,10 @@ namespace sharp {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Limit input images to a given number of pixels, where pixels = width * height
|
||||
if (descriptor->limitInputPixels > 0 &&
|
||||
static_cast<uint64_t>(image.width() * image.height()) > static_cast<uint64_t>(descriptor->limitInputPixels)) {
|
||||
static_cast<uint64_t>(image.width()) * image.height() > descriptor->limitInputPixels) {
|
||||
throw vips::VError("Input image exceeds pixel limit");
|
||||
}
|
||||
return std::make_tuple(image, imageType);
|
||||
@@ -378,7 +531,33 @@ namespace sharp {
|
||||
Does this image have an embedded profile?
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/*
|
||||
Get copy of embedded profile.
|
||||
*/
|
||||
std::pair<char*, size_t> GetProfile(VImage image) {
|
||||
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;
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -386,12 +565,28 @@ namespace sharp {
|
||||
Uses colour space interpretation with number of channels to guess this.
|
||||
*/
|
||||
bool HasAlpha(VImage image) {
|
||||
int const bands = image.bands();
|
||||
VipsInterpretation const interpretation = image.interpretation();
|
||||
return (
|
||||
(bands == 2 && interpretation == VIPS_INTERPRETATION_B_W) ||
|
||||
(bands == 4 && interpretation != VIPS_INTERPRETATION_CMYK) ||
|
||||
(bands == 5 && interpretation == VIPS_INTERPRETATION_CMYK));
|
||||
return image.has_alpha();
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -420,41 +615,56 @@ namespace sharp {
|
||||
VImage RemoveExifOrientation(VImage image) {
|
||||
VImage copy = image.copy();
|
||||
copy.remove(VIPS_META_ORIENTATION);
|
||||
copy.remove("exif-ifd0-Orientation");
|
||||
return copy;
|
||||
}
|
||||
|
||||
/*
|
||||
Set animation properties if necessary.
|
||||
Non-provided properties will be loaded from image.
|
||||
*/
|
||||
VImage SetAnimationProperties(VImage image, int pageHeight, std::vector<int> delay, int loop) {
|
||||
bool hasDelay = delay.size() != 1 || delay.front() != -1;
|
||||
VImage SetAnimationProperties(VImage image, int nPages, int pageHeight, std::vector<int> delay, int loop) {
|
||||
bool hasDelay = !delay.empty();
|
||||
|
||||
if (pageHeight == 0 && image.get_typeof(VIPS_META_PAGE_HEIGHT) == G_TYPE_INT) {
|
||||
pageHeight = image.get_int(VIPS_META_PAGE_HEIGHT);
|
||||
// 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]);
|
||||
}
|
||||
|
||||
if (!hasDelay && image.get_typeof("delay") == VIPS_TYPE_ARRAY_INT) {
|
||||
delay = image.get_array_int("delay");
|
||||
hasDelay = true;
|
||||
}
|
||||
|
||||
if (loop == -1 && image.get_typeof("loop") == G_TYPE_INT) {
|
||||
loop = image.get_int("loop");
|
||||
}
|
||||
|
||||
if (pageHeight == 0) return image;
|
||||
|
||||
// It is necessary to create the copy as otherwise, pageHeight will be ignored!
|
||||
// Attaching metadata, need to copy the image.
|
||||
VImage copy = image.copy();
|
||||
|
||||
copy.set(VIPS_META_PAGE_HEIGHT, pageHeight);
|
||||
// Only set page-height if we have more than one page, or this could
|
||||
// accidentally turn into an animated image later.
|
||||
if (nPages > 1) copy.set(VIPS_META_PAGE_HEIGHT, pageHeight);
|
||||
if (hasDelay) copy.set("delay", delay);
|
||||
if (loop != -1) copy.set("loop", loop);
|
||||
|
||||
return copy;
|
||||
}
|
||||
|
||||
/*
|
||||
Remove animation properties from image.
|
||||
*/
|
||||
VImage RemoveAnimationProperties(VImage image) {
|
||||
VImage copy = image.copy();
|
||||
copy.remove(VIPS_META_PAGE_HEIGHT);
|
||||
copy.remove("delay");
|
||||
copy.remove("loop");
|
||||
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?
|
||||
*/
|
||||
@@ -475,18 +685,25 @@ namespace sharp {
|
||||
VImage SetDensity(VImage image, const double density) {
|
||||
const double pixelsPerMm = density / 25.4;
|
||||
VImage copy = image.copy();
|
||||
copy.set("Xres", pixelsPerMm);
|
||||
copy.set("Yres", pixelsPerMm);
|
||||
copy.set(VIPS_META_RESOLUTION_UNIT, "in");
|
||||
copy.get_image()->Xres = pixelsPerMm;
|
||||
copy.get_image()->Yres = pixelsPerMm;
|
||||
return copy;
|
||||
}
|
||||
|
||||
/*
|
||||
Multi-page images can have a page height. Fetch it, and sanity check it.
|
||||
If page-height is not set, it defaults to the image height
|
||||
*/
|
||||
int GetPageHeight(VImage image) {
|
||||
return vips_image_get_page_height(image.get_image());
|
||||
}
|
||||
|
||||
/*
|
||||
Check the proposed format supports the current dimensions.
|
||||
*/
|
||||
void AssertImageTypeDimensions(VImage image, ImageType const imageType) {
|
||||
const int height = image.get_typeof("pageHeight") == G_TYPE_INT
|
||||
? image.get_int("pageHeight")
|
||||
const int height = image.get_typeof(VIPS_META_PAGE_HEIGHT) == G_TYPE_INT
|
||||
? image.get_int(VIPS_META_PAGE_HEIGHT)
|
||||
: image.height();
|
||||
if (imageType == ImageType::JPEG) {
|
||||
if (image.width() > 65535 || height > 65535) {
|
||||
@@ -500,6 +717,10 @@ namespace sharp {
|
||||
if (image.width() > 65535 || height > 65535) {
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -537,6 +758,32 @@ namespace sharp {
|
||||
return warning;
|
||||
}
|
||||
|
||||
/*
|
||||
Attach an event listener for progress updates, used to detect timeout
|
||||
*/
|
||||
void SetTimeout(VImage image, int const seconds) {
|
||||
if (seconds > 0) {
|
||||
VipsImage *im = image.get_image();
|
||||
if (im->progress_signal == NULL) {
|
||||
int *timeout = VIPS_NEW(im, int);
|
||||
*timeout = seconds;
|
||||
g_signal_connect(im, "eval", G_CALLBACK(VipsProgressCallBack), timeout);
|
||||
vips_image_set_progress(im, TRUE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Event listener for progress updates, used to detect timeout
|
||||
*/
|
||||
void VipsProgressCallBack(VipsImage *im, VipsProgress *progress, int *timeout) {
|
||||
if (*timeout > 0 && progress->run >= *timeout) {
|
||||
vips_image_set_kill(im, TRUE);
|
||||
vips_error("timeout", "%d%% complete", progress->percent);
|
||||
*timeout = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Calculate the (left, top) coordinates of the output image
|
||||
within the input image, applying the given gravity during an embed.
|
||||
@@ -656,26 +903,18 @@ namespace sharp {
|
||||
int top = 0;
|
||||
|
||||
// assign only if valid
|
||||
if (x >= 0 && x < (inWidth - outWidth)) {
|
||||
if (x < (inWidth - outWidth)) {
|
||||
left = x;
|
||||
} else if (x >= (inWidth - outWidth)) {
|
||||
left = inWidth - outWidth;
|
||||
}
|
||||
|
||||
if (y >= 0 && y < (inHeight - outHeight)) {
|
||||
if (y < (inHeight - outHeight)) {
|
||||
top = y;
|
||||
} else if (y >= (inHeight - outHeight)) {
|
||||
top = inHeight - outHeight;
|
||||
}
|
||||
|
||||
// the resulting left and top could have been outside the image after calculation from bottom/right edges
|
||||
if (left < 0) {
|
||||
left = 0;
|
||||
}
|
||||
if (top < 0) {
|
||||
top = 0;
|
||||
}
|
||||
|
||||
return std::make_tuple(left, top);
|
||||
}
|
||||
|
||||
@@ -694,42 +933,30 @@ namespace sharp {
|
||||
return Is16Bit(interpretation) ? 65535.0 : 255.0;
|
||||
}
|
||||
|
||||
/*
|
||||
Get boolean operation type from string
|
||||
*/
|
||||
VipsOperationBoolean GetBooleanOperation(std::string const opStr) {
|
||||
return static_cast<VipsOperationBoolean>(
|
||||
vips_enum_from_nick(nullptr, VIPS_TYPE_OPERATION_BOOLEAN, opStr.data()));
|
||||
}
|
||||
|
||||
/*
|
||||
Get interpretation type from string
|
||||
*/
|
||||
VipsInterpretation GetInterpretation(std::string const typeStr) {
|
||||
return static_cast<VipsInterpretation>(
|
||||
vips_enum_from_nick(nullptr, VIPS_TYPE_INTERPRETATION, typeStr.data()));
|
||||
}
|
||||
|
||||
/*
|
||||
Convert RGBA value to another colourspace
|
||||
*/
|
||||
std::vector<double> GetRgbaAsColourspace(std::vector<double> const rgba, VipsInterpretation const interpretation) {
|
||||
std::vector<double> GetRgbaAsColourspace(std::vector<double> const rgba,
|
||||
VipsInterpretation const interpretation, bool premultiply) {
|
||||
int const bands = static_cast<int>(rgba.size());
|
||||
if (bands < 3 || interpretation == VIPS_INTERPRETATION_sRGB || interpretation == VIPS_INTERPRETATION_RGB) {
|
||||
if (bands < 3) {
|
||||
return rgba;
|
||||
} else {
|
||||
VImage pixel = VImage::new_matrix(1, 1);
|
||||
pixel.set("bands", bands);
|
||||
pixel = pixel.new_from_image(rgba);
|
||||
pixel = pixel.colourspace(interpretation, VImage::option()->set("source_space", VIPS_INTERPRETATION_sRGB));
|
||||
return pixel(0, 0);
|
||||
}
|
||||
VImage pixel = VImage::new_matrix(1, 1);
|
||||
pixel.set("bands", bands);
|
||||
pixel = pixel
|
||||
.new_from_image(rgba)
|
||||
.colourspace(interpretation, VImage::option()->set("source_space", VIPS_INTERPRETATION_sRGB));
|
||||
if (premultiply) {
|
||||
pixel = pixel.premultiply();
|
||||
}
|
||||
return pixel(0, 0);
|
||||
}
|
||||
|
||||
/*
|
||||
Apply the alpha channel to a given colour
|
||||
*/
|
||||
std::tuple<VImage, std::vector<double>> ApplyAlpha(VImage image, std::vector<double> colour) {
|
||||
std::tuple<VImage, std::vector<double>> ApplyAlpha(VImage image, std::vector<double> colour, bool premultiply) {
|
||||
// Scale up 8-bit values to match 16-bit input image
|
||||
double const multiplier = sharp::Is16Bit(image.interpretation()) ? 256.0 : 1.0;
|
||||
// Create alphaColour colour
|
||||
@@ -753,11 +980,11 @@ namespace sharp {
|
||||
alphaColour.push_back(colour[3] * multiplier);
|
||||
}
|
||||
// Ensure alphaColour colour uses correct colourspace
|
||||
alphaColour = sharp::GetRgbaAsColourspace(alphaColour, image.interpretation());
|
||||
alphaColour = sharp::GetRgbaAsColourspace(alphaColour, image.interpretation(), premultiply);
|
||||
// Add non-transparent alpha channel, if required
|
||||
if (colour[3] < 255.0 && !HasAlpha(image)) {
|
||||
image = image.bandjoin(
|
||||
VImage::new_matrix(image.width(), image.height()).new_from_image(255 * multiplier));
|
||||
VImage::new_matrix(image.width(), image.height()).new_from_image(255 * multiplier).cast(image.format()));
|
||||
}
|
||||
return std::make_tuple(image, alphaColour);
|
||||
}
|
||||
@@ -775,12 +1002,89 @@ namespace sharp {
|
||||
/*
|
||||
Ensures alpha channel, if missing.
|
||||
*/
|
||||
VImage EnsureAlpha(VImage image) {
|
||||
VImage EnsureAlpha(VImage image, double const value) {
|
||||
if (!HasAlpha(image)) {
|
||||
std::vector<double> alpha;
|
||||
alpha.push_back(sharp::MaximumImageAlpha(image.interpretation()));
|
||||
alpha.push_back(value * sharp::MaximumImageAlpha(image.interpretation()));
|
||||
image = image.bandjoin_const(alpha);
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
std::pair<double, double> ResolveShrink(int width, int height, int targetWidth, int targetHeight,
|
||||
Canvas canvas, bool withoutEnlargement, bool withoutReduction) {
|
||||
double hshrink = 1.0;
|
||||
double vshrink = 1.0;
|
||||
|
||||
if (targetWidth > 0 && targetHeight > 0) {
|
||||
// Fixed width and height
|
||||
hshrink = static_cast<double>(width) / targetWidth;
|
||||
vshrink = static_cast<double>(height) / targetHeight;
|
||||
|
||||
switch (canvas) {
|
||||
case Canvas::CROP:
|
||||
case Canvas::MIN:
|
||||
if (hshrink < vshrink) {
|
||||
vshrink = hshrink;
|
||||
} else {
|
||||
hshrink = vshrink;
|
||||
}
|
||||
break;
|
||||
case Canvas::EMBED:
|
||||
case Canvas::MAX:
|
||||
if (hshrink > vshrink) {
|
||||
vshrink = hshrink;
|
||||
} else {
|
||||
hshrink = vshrink;
|
||||
}
|
||||
break;
|
||||
case Canvas::IGNORE_ASPECT:
|
||||
break;
|
||||
}
|
||||
} else if (targetWidth > 0) {
|
||||
// Fixed width
|
||||
hshrink = static_cast<double>(width) / targetWidth;
|
||||
|
||||
if (canvas != Canvas::IGNORE_ASPECT) {
|
||||
// Auto height
|
||||
vshrink = hshrink;
|
||||
}
|
||||
} else if (targetHeight > 0) {
|
||||
// Fixed height
|
||||
vshrink = static_cast<double>(height) / targetHeight;
|
||||
|
||||
if (canvas != Canvas::IGNORE_ASPECT) {
|
||||
// Auto width
|
||||
hshrink = vshrink;
|
||||
}
|
||||
}
|
||||
|
||||
// We should not reduce or enlarge the output image, if
|
||||
// withoutReduction or withoutEnlargement is specified.
|
||||
if (withoutReduction) {
|
||||
// Equivalent of VIPS_SIZE_UP
|
||||
hshrink = std::min(1.0, hshrink);
|
||||
vshrink = std::min(1.0, vshrink);
|
||||
} else if (withoutEnlargement) {
|
||||
// Equivalent of VIPS_SIZE_DOWN
|
||||
hshrink = std::max(1.0, hshrink);
|
||||
vshrink = std::max(1.0, vshrink);
|
||||
}
|
||||
|
||||
// We don't want to shrink so much that we send an axis to 0
|
||||
hshrink = std::min(hshrink, static_cast<double>(width));
|
||||
vshrink = std::min(vshrink, static_cast<double>(height));
|
||||
|
||||
return std::make_pair(hshrink, vshrink);
|
||||
}
|
||||
|
||||
/*
|
||||
Ensure decoding remains sequential.
|
||||
*/
|
||||
VImage StaySequential(VImage image, VipsAccess access, bool condition) {
|
||||
if (access == VIPS_ACCESS_SEQUENTIAL && condition) {
|
||||
return image.copy_memory();
|
||||
}
|
||||
return image;
|
||||
}
|
||||
} // namespace sharp
|
||||
|
||||
172
src/common.h
172
src/common.h
@@ -1,16 +1,5 @@
|
||||
// Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Lovell Fuller and contributors.
|
||||
//
|
||||
// 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.
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
#ifndef SRC_COMMON_H_
|
||||
#define SRC_COMMON_H_
|
||||
@@ -18,14 +7,17 @@
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <vector>
|
||||
#include <atomic>
|
||||
|
||||
#include <napi.h>
|
||||
#include <vips/vips8>
|
||||
|
||||
// Verify platform and compiler compatibility
|
||||
|
||||
#if (VIPS_MAJOR_VERSION < 8 || (VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION < 9))
|
||||
#error "libvips version 8.9.2+ is required - please see https://sharp.pixelplumbing.com/install"
|
||||
#if (VIPS_MAJOR_VERSION < 8) || \
|
||||
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION < 15) || \
|
||||
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION == 15 && VIPS_MICRO_VERSION < 2)
|
||||
#error "libvips version 8.15.2+ is required - please see https://sharp.pixelplumbing.com/install"
|
||||
#endif
|
||||
|
||||
#if ((!defined(__clang__)) && defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 6)))
|
||||
@@ -46,54 +38,95 @@ namespace sharp {
|
||||
std::string name;
|
||||
std::string file;
|
||||
char *buffer;
|
||||
bool failOnError;
|
||||
int limitInputPixels;
|
||||
VipsFailOn failOn;
|
||||
uint64_t limitInputPixels;
|
||||
bool unlimited;
|
||||
VipsAccess access;
|
||||
size_t bufferLength;
|
||||
bool isBuffer;
|
||||
double density;
|
||||
bool ignoreIcc;
|
||||
VipsBandFormat rawDepth;
|
||||
int rawChannels;
|
||||
int rawWidth;
|
||||
int rawHeight;
|
||||
bool rawPremultiplied;
|
||||
int pages;
|
||||
int page;
|
||||
int level;
|
||||
int subifd;
|
||||
int createChannels;
|
||||
int createWidth;
|
||||
int createHeight;
|
||||
std::vector<double> createBackground;
|
||||
std::string createNoiseType;
|
||||
double createNoiseMean;
|
||||
double createNoiseSigma;
|
||||
std::string textValue;
|
||||
std::string textFont;
|
||||
std::string textFontfile;
|
||||
int textWidth;
|
||||
int textHeight;
|
||||
VipsAlign textAlign;
|
||||
bool textJustify;
|
||||
int textDpi;
|
||||
bool textRgba;
|
||||
int textSpacing;
|
||||
VipsTextWrap textWrap;
|
||||
int textAutofitDpi;
|
||||
|
||||
InputDescriptor():
|
||||
buffer(nullptr),
|
||||
failOnError(TRUE),
|
||||
failOn(VIPS_FAIL_ON_WARNING),
|
||||
limitInputPixels(0x3FFF * 0x3FFF),
|
||||
unlimited(FALSE),
|
||||
access(VIPS_ACCESS_RANDOM),
|
||||
bufferLength(0),
|
||||
isBuffer(FALSE),
|
||||
density(72.0),
|
||||
ignoreIcc(FALSE),
|
||||
rawDepth(VIPS_FORMAT_UCHAR),
|
||||
rawChannels(0),
|
||||
rawWidth(0),
|
||||
rawHeight(0),
|
||||
rawPremultiplied(false),
|
||||
pages(1),
|
||||
page(0),
|
||||
level(0),
|
||||
subifd(-1),
|
||||
createChannels(0),
|
||||
createWidth(0),
|
||||
createHeight(0),
|
||||
createBackground{ 0.0, 0.0, 0.0, 255.0 } {}
|
||||
createBackground{ 0.0, 0.0, 0.0, 255.0 },
|
||||
createNoiseMean(0.0),
|
||||
createNoiseSigma(0.0),
|
||||
textWidth(0),
|
||||
textHeight(0),
|
||||
textAlign(VIPS_ALIGN_LOW),
|
||||
textJustify(FALSE),
|
||||
textDpi(72),
|
||||
textRgba(FALSE),
|
||||
textSpacing(0),
|
||||
textWrap(VIPS_TEXT_WRAP_WORD),
|
||||
textAutofitDpi(0) {}
|
||||
};
|
||||
|
||||
// Convenience methods to access the attributes of a Napi::Object
|
||||
bool HasAttr(Napi::Object obj, std::string attr);
|
||||
std::string AttrAsStr(Napi::Object obj, std::string attr);
|
||||
std::string AttrAsStr(Napi::Object obj, unsigned int const attr);
|
||||
uint32_t AttrAsUint32(Napi::Object obj, std::string attr);
|
||||
int32_t AttrAsInt32(Napi::Object obj, std::string attr);
|
||||
int32_t AttrAsInt32(Napi::Object obj, unsigned int const attr);
|
||||
double AttrAsDouble(Napi::Object obj, std::string attr);
|
||||
double AttrAsDouble(Napi::Object obj, unsigned int const attr);
|
||||
bool AttrAsBool(Napi::Object obj, std::string attr);
|
||||
std::vector<double> AttrAsRgba(Napi::Object obj, std::string attr);
|
||||
std::vector<double> AttrAsVectorOfDouble(Napi::Object obj, std::string attr);
|
||||
std::vector<int32_t> AttrAsInt32Vector(Napi::Object obj, std::string attr);
|
||||
template <class T> T AttrAsEnum(Napi::Object obj, std::string attr, GType type) {
|
||||
return static_cast<T>(
|
||||
vips_enum_from_nick(nullptr, type, AttrAsStr(obj, attr).data()));
|
||||
}
|
||||
|
||||
// Create an InputDescriptor instance from a Napi::Object describing an input image
|
||||
InputDescriptor* CreateInputDescriptor(Napi::Object input);
|
||||
@@ -102,6 +135,7 @@ namespace sharp {
|
||||
JPEG,
|
||||
PNG,
|
||||
WEBP,
|
||||
JP2,
|
||||
TIFF,
|
||||
GIF,
|
||||
SVG,
|
||||
@@ -111,31 +145,48 @@ namespace sharp {
|
||||
OPENSLIDE,
|
||||
PPM,
|
||||
FITS,
|
||||
EXR,
|
||||
JXL,
|
||||
VIPS,
|
||||
RAW,
|
||||
UNKNOWN,
|
||||
MISSING
|
||||
};
|
||||
|
||||
enum class Canvas {
|
||||
CROP,
|
||||
EMBED,
|
||||
MAX,
|
||||
MIN,
|
||||
IGNORE_ASPECT
|
||||
};
|
||||
|
||||
// How many tasks are in the queue?
|
||||
extern volatile int counterQueue;
|
||||
extern std::atomic<int> counterQueue;
|
||||
|
||||
// How many tasks are being processed?
|
||||
extern volatile int counterProcess;
|
||||
extern std::atomic<int> counterProcess;
|
||||
|
||||
// Filename extension checkers
|
||||
bool IsJpeg(std::string const &str);
|
||||
bool IsPng(std::string const &str);
|
||||
bool IsWebp(std::string const &str);
|
||||
bool IsJp2(std::string const &str);
|
||||
bool IsGif(std::string const &str);
|
||||
bool IsTiff(std::string const &str);
|
||||
bool IsHeic(std::string const &str);
|
||||
bool IsHeif(std::string const &str);
|
||||
bool IsAvif(std::string const &str);
|
||||
bool IsJxl(std::string const &str);
|
||||
bool IsDz(std::string const &str);
|
||||
bool IsDzZip(std::string const &str);
|
||||
bool IsV(std::string const &str);
|
||||
|
||||
/*
|
||||
Trim space from end of string.
|
||||
*/
|
||||
std::string TrimEnd(std::string const &str);
|
||||
|
||||
/*
|
||||
Provide a string identifier for the given image type.
|
||||
*/
|
||||
@@ -156,6 +207,11 @@ namespace sharp {
|
||||
*/
|
||||
bool ImageTypeSupportsPage(ImageType imageType);
|
||||
|
||||
/*
|
||||
Does this image type support removal of safety limits?
|
||||
*/
|
||||
bool ImageTypeSupportsUnlimited(ImageType imageType);
|
||||
|
||||
/*
|
||||
Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data)
|
||||
*/
|
||||
@@ -166,12 +222,27 @@ namespace sharp {
|
||||
*/
|
||||
bool HasProfile(VImage image);
|
||||
|
||||
/*
|
||||
Get copy of embedded profile.
|
||||
*/
|
||||
std::pair<char*, size_t> GetProfile(VImage image);
|
||||
|
||||
/*
|
||||
Set embedded profile.
|
||||
*/
|
||||
VImage SetProfile(VImage image, std::pair<char*, size_t> icc);
|
||||
|
||||
/*
|
||||
Does this image have an alpha channel?
|
||||
Uses colour space interpretation with number of channels to guess this.
|
||||
*/
|
||||
bool HasAlpha(VImage image);
|
||||
|
||||
/*
|
||||
Remove all EXIF-related image fields.
|
||||
*/
|
||||
VImage RemoveExif(VImage image);
|
||||
|
||||
/*
|
||||
Get EXIF Orientation of image, if any.
|
||||
*/
|
||||
@@ -189,9 +260,18 @@ namespace sharp {
|
||||
|
||||
/*
|
||||
Set animation properties if necessary.
|
||||
Non-provided properties will be loaded from image.
|
||||
*/
|
||||
VImage SetAnimationProperties(VImage image, int pageHeight, std::vector<int> delay, int loop);
|
||||
VImage SetAnimationProperties(VImage image, int nPages, int pageHeight, std::vector<int> delay, int loop);
|
||||
|
||||
/*
|
||||
Remove animation properties from image.
|
||||
*/
|
||||
VImage RemoveAnimationProperties(VImage image);
|
||||
|
||||
/*
|
||||
Remove GIF palette from image.
|
||||
*/
|
||||
VImage RemoveGifPalette(VImage image);
|
||||
|
||||
/*
|
||||
Does this image have a non-default density?
|
||||
@@ -208,6 +288,12 @@ namespace sharp {
|
||||
*/
|
||||
VImage SetDensity(VImage image, const double density);
|
||||
|
||||
/*
|
||||
Multi-page images can have a page height. Fetch it, and sanity check it.
|
||||
If page-height is not set, it defaults to the image height
|
||||
*/
|
||||
int GetPageHeight(VImage image);
|
||||
|
||||
/*
|
||||
Check the proposed format supports the current dimensions.
|
||||
*/
|
||||
@@ -228,6 +314,16 @@ namespace sharp {
|
||||
*/
|
||||
std::string VipsWarningPop();
|
||||
|
||||
/*
|
||||
Attach an event listener for progress updates, used to detect timeout
|
||||
*/
|
||||
void SetTimeout(VImage image, int const timeoutSeconds);
|
||||
|
||||
/*
|
||||
Event listener for progress updates, used to detect timeout
|
||||
*/
|
||||
void VipsProgressCallBack(VipsImage *image, VipsProgress *progress, int *timeoutSeconds);
|
||||
|
||||
/*
|
||||
Calculate the (left, top) coordinates of the output image
|
||||
within the input image, applying the given gravity during an embed.
|
||||
@@ -260,25 +356,16 @@ namespace sharp {
|
||||
*/
|
||||
double MaximumImageAlpha(VipsInterpretation const interpretation);
|
||||
|
||||
/*
|
||||
Get boolean operation type from string
|
||||
*/
|
||||
VipsOperationBoolean GetBooleanOperation(std::string const opStr);
|
||||
|
||||
/*
|
||||
Get interpretation type from string
|
||||
*/
|
||||
VipsInterpretation GetInterpretation(std::string const typeStr);
|
||||
|
||||
/*
|
||||
Convert RGBA value to another colourspace
|
||||
*/
|
||||
std::vector<double> GetRgbaAsColourspace(std::vector<double> const rgba, VipsInterpretation const interpretation);
|
||||
std::vector<double> GetRgbaAsColourspace(std::vector<double> const rgba,
|
||||
VipsInterpretation const interpretation, bool premultiply);
|
||||
|
||||
/*
|
||||
Apply the alpha channel to a given colour
|
||||
*/
|
||||
std::tuple<VImage, std::vector<double>> ApplyAlpha(VImage image, std::vector<double> colour);
|
||||
std::tuple<VImage, std::vector<double>> ApplyAlpha(VImage image, std::vector<double> colour, bool premultiply);
|
||||
|
||||
/*
|
||||
Removes alpha channel, if any.
|
||||
@@ -288,7 +375,18 @@ namespace sharp {
|
||||
/*
|
||||
Ensures alpha channel, if missing.
|
||||
*/
|
||||
VImage EnsureAlpha(VImage image);
|
||||
VImage EnsureAlpha(VImage image, double const value);
|
||||
|
||||
/*
|
||||
Calculate the horizontal and vertical shrink factors, taking the canvas mode into account.
|
||||
*/
|
||||
std::pair<double, double> ResolveShrink(int width, int height, int targetWidth, int targetHeight,
|
||||
Canvas canvas, bool withoutEnlargement, bool withoutReduction);
|
||||
|
||||
/*
|
||||
Ensure decoding remains sequential.
|
||||
*/
|
||||
VImage StaySequential(VImage image, VipsAccess access, bool condition = TRUE);
|
||||
|
||||
} // namespace sharp
|
||||
|
||||
|
||||
40
src/emscripten/common.gypi
Normal file
40
src/emscripten/common.gypi
Normal file
@@ -0,0 +1,40 @@
|
||||
# Copyright 2013 Lovell Fuller and others.
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
{
|
||||
'variables': {
|
||||
'OS': 'emscripten'
|
||||
},
|
||||
'target_defaults': {
|
||||
'default_configuration': 'Release',
|
||||
'type': 'executable',
|
||||
'cflags': [
|
||||
'-pthread',
|
||||
'-sDEFAULT_TO_CXX=0'
|
||||
],
|
||||
'cflags_cc': [
|
||||
'-pthread'
|
||||
],
|
||||
'ldflags': [
|
||||
'--js-library=<!(node -p "require(\'emnapi\').js_library")',
|
||||
'-sAUTO_JS_LIBRARIES=0',
|
||||
'-sAUTO_NATIVE_LIBRARIES=0',
|
||||
'-sNODEJS_CATCH_EXIT=0',
|
||||
'-sNODEJS_CATCH_REJECTION=0'
|
||||
],
|
||||
'defines': [
|
||||
'__STDC_FORMAT_MACROS',
|
||||
'BUILDING_NODE_EXTENSION',
|
||||
'EMNAPI_WORKER_POOL_SIZE=1'
|
||||
],
|
||||
'include_dirs': [
|
||||
'<!(node -p "require(\'emnapi\').include")'
|
||||
],
|
||||
'sources': [
|
||||
'<!@(node -p "require(\'emnapi\').sources.map(x => JSON.stringify(path.relative(process.cwd(), x))).join(\' \')")'
|
||||
],
|
||||
'configurations': {
|
||||
'Release': {}
|
||||
}
|
||||
}
|
||||
}
|
||||
19
src/emscripten/pre.js
Normal file
19
src/emscripten/pre.js
Normal file
@@ -0,0 +1,19 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
/* global Module, ENV, _vips_shutdown, _uv_library_shutdown */
|
||||
|
||||
Module.preRun = () => {
|
||||
ENV.VIPS_CONCURRENCY = Number(process.env.VIPS_CONCURRENCY) || 1;
|
||||
};
|
||||
|
||||
Module.onRuntimeInitialized = () => {
|
||||
module.exports = Module.emnapiInit({
|
||||
context: require('@emnapi/runtime').getDefaultContext()
|
||||
});
|
||||
|
||||
process.once('exit', () => {
|
||||
_vips_shutdown();
|
||||
_uv_library_shutdown();
|
||||
});
|
||||
};
|
||||
@@ -1,178 +0,0 @@
|
||||
/* Object part of the VSource and VTarget class
|
||||
*/
|
||||
|
||||
/*
|
||||
|
||||
Copyright (C) 1991-2001 The National Gallery
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
||||
02110-1301 USA
|
||||
|
||||
*/
|
||||
|
||||
/*
|
||||
|
||||
These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
|
||||
|
||||
*/
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif /*HAVE_CONFIG_H*/
|
||||
#include <vips/intl.h>
|
||||
|
||||
#include <vips/vips8>
|
||||
|
||||
#include <vips/debug.h>
|
||||
|
||||
/*
|
||||
#define VIPS_DEBUG
|
||||
#define VIPS_DEBUG_VERBOSE
|
||||
*/
|
||||
|
||||
VIPS_NAMESPACE_START
|
||||
|
||||
VSource
|
||||
VSource::new_from_descriptor( int descriptor )
|
||||
{
|
||||
VipsSource *input;
|
||||
|
||||
if( !(input = vips_source_new_from_descriptor( descriptor )) )
|
||||
throw VError();
|
||||
|
||||
VSource out( input );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VSource
|
||||
VSource::new_from_file( const char *filename )
|
||||
{
|
||||
VipsSource *input;
|
||||
|
||||
if( !(input = vips_source_new_from_file( filename )) )
|
||||
throw VError();
|
||||
|
||||
VSource out( input );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VSource
|
||||
VSource::new_from_blob( VipsBlob *blob )
|
||||
{
|
||||
VipsSource *input;
|
||||
|
||||
if( !(input = vips_source_new_from_blob( blob )) )
|
||||
throw VError();
|
||||
|
||||
VSource out( input );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VSource
|
||||
VSource::new_from_memory( const void *data,
|
||||
size_t size )
|
||||
{
|
||||
VipsSource *input;
|
||||
|
||||
if( !(input = vips_source_new_from_memory( data, size )) )
|
||||
throw VError();
|
||||
|
||||
VSource out( input );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VSource
|
||||
VSource::new_from_options( const char *options )
|
||||
{
|
||||
VipsSource *input;
|
||||
|
||||
if( !(input = vips_source_new_from_options( options )) )
|
||||
throw VError();
|
||||
|
||||
VSource out( input );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VOption *
|
||||
VOption::set( const char *name, const VSource value )
|
||||
{
|
||||
Pair *pair = new Pair( name );
|
||||
|
||||
pair->input = true;
|
||||
g_value_init( &pair->value, VIPS_TYPE_SOURCE );
|
||||
g_value_set_object( &pair->value, value.get_source() );
|
||||
options.push_back( pair );
|
||||
|
||||
return( this );
|
||||
}
|
||||
|
||||
VTarget
|
||||
VTarget::new_to_descriptor( int descriptor )
|
||||
{
|
||||
VipsTarget *output;
|
||||
|
||||
if( !(output = vips_target_new_to_descriptor( descriptor )) )
|
||||
throw VError();
|
||||
|
||||
VTarget out( output );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VTarget
|
||||
VTarget::new_to_file( const char *filename )
|
||||
{
|
||||
VipsTarget *output;
|
||||
|
||||
if( !(output = vips_target_new_to_file( filename )) )
|
||||
throw VError();
|
||||
|
||||
VTarget out( output );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VTarget
|
||||
VTarget::new_to_memory()
|
||||
{
|
||||
VipsTarget *output;
|
||||
|
||||
if( !(output = vips_target_new_to_memory()) )
|
||||
throw VError();
|
||||
|
||||
VTarget out( output );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VOption *
|
||||
VOption::set( const char *name, const VTarget value )
|
||||
{
|
||||
Pair *pair = new Pair( name );
|
||||
|
||||
pair->input = true;
|
||||
g_value_init( &pair->value, VIPS_TYPE_TARGET );
|
||||
g_value_set_object( &pair->value, value.get_target() );
|
||||
options.push_back( pair );
|
||||
|
||||
return( this );
|
||||
}
|
||||
|
||||
VIPS_NAMESPACE_END
|
||||
@@ -1,50 +0,0 @@
|
||||
// Code for error type
|
||||
|
||||
/*
|
||||
|
||||
Copyright (C) 1991-2001 The National Gallery
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
||||
02110-1301 USA
|
||||
|
||||
*/
|
||||
|
||||
/*
|
||||
|
||||
These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
|
||||
|
||||
*/
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif /*HAVE_CONFIG_H*/
|
||||
#include <vips/intl.h>
|
||||
|
||||
#include <vips/vips8>
|
||||
|
||||
VIPS_NAMESPACE_START
|
||||
|
||||
std::ostream &operator<<( std::ostream &file, const VError &err )
|
||||
{
|
||||
err.ostream_print( file );
|
||||
return( file );
|
||||
}
|
||||
|
||||
void VError::ostream_print( std::ostream &file ) const
|
||||
{
|
||||
file << _what;
|
||||
}
|
||||
|
||||
VIPS_NAMESPACE_END
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,76 +0,0 @@
|
||||
/* Object part of VInterpolate class
|
||||
*/
|
||||
|
||||
/*
|
||||
|
||||
Copyright (C) 1991-2001 The National Gallery
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
||||
02110-1301 USA
|
||||
|
||||
*/
|
||||
|
||||
/*
|
||||
|
||||
These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
|
||||
|
||||
*/
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif /*HAVE_CONFIG_H*/
|
||||
#include <vips/intl.h>
|
||||
|
||||
#include <vips/vips8>
|
||||
|
||||
#include <vips/debug.h>
|
||||
|
||||
/*
|
||||
#define VIPS_DEBUG
|
||||
#define VIPS_DEBUG_VERBOSE
|
||||
*/
|
||||
|
||||
VIPS_NAMESPACE_START
|
||||
|
||||
VInterpolate
|
||||
VInterpolate::new_from_name( const char *name, VOption *options )
|
||||
{
|
||||
VipsInterpolate *interp;
|
||||
|
||||
if( !(interp = vips_interpolate_new( name )) ) {
|
||||
delete options;
|
||||
throw VError();
|
||||
}
|
||||
delete options;
|
||||
|
||||
VInterpolate out( interp );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VOption *
|
||||
VOption::set( const char *name, const VInterpolate value )
|
||||
{
|
||||
Pair *pair = new Pair( name );
|
||||
|
||||
pair->input = true;
|
||||
g_value_init( &pair->value, VIPS_TYPE_INTERPOLATE );
|
||||
g_value_set_object( &pair->value, value.get_interpolate() );
|
||||
options.push_back( pair );
|
||||
|
||||
return( this );
|
||||
}
|
||||
|
||||
VIPS_NAMESPACE_END
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,16 +1,5 @@
|
||||
// Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Lovell Fuller and contributors.
|
||||
//
|
||||
// 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.
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
#include <numeric>
|
||||
#include <vector>
|
||||
@@ -29,7 +18,7 @@ class MetadataWorker : public Napi::AsyncWorker {
|
||||
|
||||
void Execute() {
|
||||
// Decrement queued task counter
|
||||
g_atomic_int_dec_and_test(&sharp::counterQueue);
|
||||
sharp::counterQueue--;
|
||||
|
||||
vips::VImage image;
|
||||
sharp::ImageType imageType = sharp::ImageType::UNKNOWN;
|
||||
@@ -74,6 +63,15 @@ class MetadataWorker : public Napi::AsyncWorker {
|
||||
if (image.get_typeof("heif-primary") == G_TYPE_INT) {
|
||||
baton->pagePrimary = image.get_int("heif-primary");
|
||||
}
|
||||
if (image.get_typeof("heif-compression") == VIPS_TYPE_REF_STRING) {
|
||||
baton->compression = image.get_string("heif-compression");
|
||||
}
|
||||
if (image.get_typeof(VIPS_META_RESOLUTION_UNIT) == VIPS_TYPE_REF_STRING) {
|
||||
baton->resolutionUnit = image.get_string(VIPS_META_RESOLUTION_UNIT);
|
||||
}
|
||||
if (image.get_typeof("magick-format") == VIPS_TYPE_REF_STRING) {
|
||||
baton->formatMagick = image.get_string("magick-format");
|
||||
}
|
||||
if (image.get_typeof("openslide.level-count") == VIPS_TYPE_REF_STRING) {
|
||||
int const levels = std::stoi(image.get_string("openslide.level-count"));
|
||||
for (int l = 0; l < levels; l++) {
|
||||
@@ -83,7 +81,13 @@ class MetadataWorker : public Napi::AsyncWorker {
|
||||
baton->levels.push_back(std::pair<int, int>(width, height));
|
||||
}
|
||||
}
|
||||
if (image.get_typeof(VIPS_META_N_SUBIFDS) == G_TYPE_INT) {
|
||||
baton->subifds = image.get_int(VIPS_META_N_SUBIFDS);
|
||||
}
|
||||
baton->hasProfile = sharp::HasProfile(image);
|
||||
if (image.get_typeof("background") == VIPS_TYPE_ARRAY_DOUBLE) {
|
||||
baton->background = image.get_array_double("background");
|
||||
}
|
||||
// Derived attributes
|
||||
baton->hasAlpha = sharp::HasAlpha(image);
|
||||
baton->orientation = sharp::ExifOrientation(image);
|
||||
@@ -141,7 +145,7 @@ class MetadataWorker : public Napi::AsyncWorker {
|
||||
// Handle warnings
|
||||
std::string warning = sharp::VipsWarningPop();
|
||||
while (!warning.empty()) {
|
||||
debuglog.Call({ Napi::String::New(env, warning) });
|
||||
debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) });
|
||||
warning = sharp::VipsWarningPop();
|
||||
}
|
||||
|
||||
@@ -186,6 +190,15 @@ class MetadataWorker : public Napi::AsyncWorker {
|
||||
if (baton->pagePrimary > -1) {
|
||||
info.Set("pagePrimary", baton->pagePrimary);
|
||||
}
|
||||
if (!baton->compression.empty()) {
|
||||
info.Set("compression", baton->compression);
|
||||
}
|
||||
if (!baton->resolutionUnit.empty()) {
|
||||
info.Set("resolutionUnit", baton->resolutionUnit == "in" ? "inch" : baton->resolutionUnit);
|
||||
}
|
||||
if (!baton->formatMagick.empty()) {
|
||||
info.Set("formatMagick", baton->formatMagick);
|
||||
}
|
||||
if (!baton->levels.empty()) {
|
||||
int i = 0;
|
||||
Napi::Array levels = Napi::Array::New(env, static_cast<size_t>(baton->levels.size()));
|
||||
@@ -197,30 +210,45 @@ class MetadataWorker : public Napi::AsyncWorker {
|
||||
}
|
||||
info.Set("levels", levels);
|
||||
}
|
||||
if (baton->subifds > 0) {
|
||||
info.Set("subifds", baton->subifds);
|
||||
}
|
||||
if (!baton->background.empty()) {
|
||||
if (baton->background.size() == 3) {
|
||||
Napi::Object background = Napi::Object::New(env);
|
||||
background.Set("r", baton->background[0]);
|
||||
background.Set("g", baton->background[1]);
|
||||
background.Set("b", baton->background[2]);
|
||||
info.Set("background", background);
|
||||
} else {
|
||||
info.Set("background", baton->background[0]);
|
||||
}
|
||||
}
|
||||
info.Set("hasProfile", baton->hasProfile);
|
||||
info.Set("hasAlpha", baton->hasAlpha);
|
||||
if (baton->orientation > 0) {
|
||||
info.Set("orientation", baton->orientation);
|
||||
}
|
||||
if (baton->exifLength > 0) {
|
||||
info.Set("exif", Napi::Buffer<char>::New(env, baton->exif, baton->exifLength, sharp::FreeCallback));
|
||||
info.Set("exif", Napi::Buffer<char>::NewOrCopy(env, baton->exif, baton->exifLength, sharp::FreeCallback));
|
||||
}
|
||||
if (baton->iccLength > 0) {
|
||||
info.Set("icc", Napi::Buffer<char>::New(env, baton->icc, baton->iccLength, sharp::FreeCallback));
|
||||
info.Set("icc", Napi::Buffer<char>::NewOrCopy(env, baton->icc, baton->iccLength, sharp::FreeCallback));
|
||||
}
|
||||
if (baton->iptcLength > 0) {
|
||||
info.Set("iptc", Napi::Buffer<char>::New(env, baton->iptc, baton->iptcLength, sharp::FreeCallback));
|
||||
info.Set("iptc", Napi::Buffer<char>::NewOrCopy(env, baton->iptc, baton->iptcLength, sharp::FreeCallback));
|
||||
}
|
||||
if (baton->xmpLength > 0) {
|
||||
info.Set("xmp", Napi::Buffer<char>::New(env, baton->xmp, baton->xmpLength, sharp::FreeCallback));
|
||||
info.Set("xmp", Napi::Buffer<char>::NewOrCopy(env, baton->xmp, baton->xmpLength, sharp::FreeCallback));
|
||||
}
|
||||
if (baton->tifftagPhotoshopLength > 0) {
|
||||
info.Set("tifftagPhotoshop",
|
||||
Napi::Buffer<char>::New(env, baton->tifftagPhotoshop, baton->tifftagPhotoshopLength, sharp::FreeCallback));
|
||||
Napi::Buffer<char>::NewOrCopy(env, baton->tifftagPhotoshop,
|
||||
baton->tifftagPhotoshopLength, sharp::FreeCallback));
|
||||
}
|
||||
Callback().MakeCallback(Receiver().Value(), { env.Null(), info });
|
||||
Callback().Call(Receiver().Value(), { env.Null(), info });
|
||||
} else {
|
||||
Callback().MakeCallback(Receiver().Value(), { Napi::Error::New(env, baton->err).Value() });
|
||||
Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() });
|
||||
}
|
||||
|
||||
delete baton->input;
|
||||
@@ -238,7 +266,7 @@ class MetadataWorker : public Napi::AsyncWorker {
|
||||
Napi::Value metadata(const Napi::CallbackInfo& info) {
|
||||
// V8 objects are converted to non-V8 types held in the baton struct
|
||||
MetadataBaton *baton = new MetadataBaton;
|
||||
Napi::Object options = info[0].As<Napi::Object>();
|
||||
Napi::Object options = info[size_t(0)].As<Napi::Object>();
|
||||
|
||||
// Input
|
||||
baton->input = sharp::CreateInputDescriptor(options.Get("input").As<Napi::Object>());
|
||||
@@ -247,13 +275,13 @@ Napi::Value metadata(const Napi::CallbackInfo& info) {
|
||||
Napi::Function debuglog = options.Get("debuglog").As<Napi::Function>();
|
||||
|
||||
// Join queue for worker thread
|
||||
Napi::Function callback = info[1].As<Napi::Function>();
|
||||
Napi::Function callback = info[size_t(1)].As<Napi::Function>();
|
||||
MetadataWorker *worker = new MetadataWorker(callback, baton, debuglog);
|
||||
worker->Receiver().Set("options", options);
|
||||
worker->Queue();
|
||||
|
||||
// Increment queued task counter
|
||||
g_atomic_int_inc(&sharp::counterQueue);
|
||||
sharp::counterQueue++;
|
||||
|
||||
return info.Env().Undefined();
|
||||
}
|
||||
|
||||
@@ -1,16 +1,5 @@
|
||||
// Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Lovell Fuller and contributors.
|
||||
//
|
||||
// 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.
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
#ifndef SRC_METADATA_H_
|
||||
#define SRC_METADATA_H_
|
||||
@@ -39,7 +28,12 @@ struct MetadataBaton {
|
||||
int loop;
|
||||
std::vector<int> delay;
|
||||
int pagePrimary;
|
||||
std::string compression;
|
||||
std::string resolutionUnit;
|
||||
std::string formatMagick;
|
||||
std::vector<std::pair<int, int>> levels;
|
||||
int subifds;
|
||||
std::vector<double> background;
|
||||
bool hasProfile;
|
||||
bool hasAlpha;
|
||||
int orientation;
|
||||
@@ -67,6 +61,7 @@ struct MetadataBaton {
|
||||
pageHeight(0),
|
||||
loop(-1),
|
||||
pagePrimary(-1),
|
||||
subifds(0),
|
||||
hasProfile(false),
|
||||
hasAlpha(false),
|
||||
orientation(0),
|
||||
|
||||
@@ -1,23 +1,11 @@
|
||||
// Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Lovell Fuller and contributors.
|
||||
//
|
||||
// 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.
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <tuple>
|
||||
#include <vector>
|
||||
|
||||
#include <vips/vips8>
|
||||
|
||||
#include "common.h"
|
||||
@@ -28,36 +16,50 @@ using vips::VError;
|
||||
|
||||
namespace sharp {
|
||||
/*
|
||||
* Tint an image using the specified chroma, preserving the original image luminance
|
||||
* Tint an image using the provided RGB.
|
||||
*/
|
||||
VImage Tint(VImage image, double const a, double const b) {
|
||||
// Get original colourspace
|
||||
VImage Tint(VImage image, std::vector<double> const tint) {
|
||||
std::vector<double> const tintLab = (VImage::black(1, 1) + tint)
|
||||
.colourspace(VIPS_INTERPRETATION_LAB, VImage::option()->set("source_space", VIPS_INTERPRETATION_sRGB))
|
||||
.getpoint(0, 0);
|
||||
// LAB identity function
|
||||
VImage identityLab = VImage::identity(VImage::option()->set("bands", 3))
|
||||
.colourspace(VIPS_INTERPRETATION_LAB, VImage::option()->set("source_space", VIPS_INTERPRETATION_sRGB));
|
||||
// Scale luminance range, 0.0 to 1.0
|
||||
VImage l = identityLab[0] / 100;
|
||||
// Weighting functions
|
||||
VImage weightL = 1.0 - 4.0 * ((l - 0.5) * (l - 0.5));
|
||||
VImage weightAB = (weightL * tintLab).extract_band(1, VImage::option()->set("n", 2));
|
||||
identityLab = identityLab[0].bandjoin(weightAB);
|
||||
// Convert lookup table to sRGB
|
||||
VImage lut = identityLab.colourspace(VIPS_INTERPRETATION_sRGB,
|
||||
VImage::option()->set("source_space", VIPS_INTERPRETATION_LAB));
|
||||
// Original colourspace
|
||||
VipsInterpretation typeBeforeTint = image.interpretation();
|
||||
if (typeBeforeTint == VIPS_INTERPRETATION_RGB) {
|
||||
typeBeforeTint = VIPS_INTERPRETATION_sRGB;
|
||||
}
|
||||
// Extract luminance
|
||||
VImage luminance = image.colourspace(VIPS_INTERPRETATION_LAB)[0];
|
||||
// Create the tinted version by combining the L from the original and the chroma from the tint
|
||||
std::vector<double> chroma {a, b};
|
||||
VImage tinted = luminance
|
||||
.bandjoin(chroma)
|
||||
.copy(VImage::option()->set("interpretation", VIPS_INTERPRETATION_LAB))
|
||||
.colourspace(typeBeforeTint);
|
||||
// Attach original alpha channel, if any
|
||||
// Apply lookup table
|
||||
if (HasAlpha(image)) {
|
||||
// Extract original alpha channel
|
||||
VImage alpha = image[image.bands() - 1];
|
||||
// Join alpha channel to normalised image
|
||||
tinted = tinted.bandjoin(alpha);
|
||||
image = RemoveAlpha(image)
|
||||
.colourspace(VIPS_INTERPRETATION_B_W)
|
||||
.maplut(lut)
|
||||
.colourspace(typeBeforeTint)
|
||||
.bandjoin(alpha);
|
||||
} else {
|
||||
image = image
|
||||
.colourspace(VIPS_INTERPRETATION_B_W)
|
||||
.maplut(lut)
|
||||
.colourspace(typeBeforeTint);
|
||||
}
|
||||
return tinted;
|
||||
return image;
|
||||
}
|
||||
|
||||
/*
|
||||
* Stretch luminance to cover full dynamic range.
|
||||
*/
|
||||
VImage Normalise(VImage image) {
|
||||
VImage Normalise(VImage image, int const lower, int const upper) {
|
||||
// Get original colourspace
|
||||
VipsInterpretation typeBeforeNormalize = image.interpretation();
|
||||
if (typeBeforeNormalize == VIPS_INTERPRETATION_RGB) {
|
||||
@@ -67,11 +69,12 @@ namespace sharp {
|
||||
VImage lab = image.colourspace(VIPS_INTERPRETATION_LAB);
|
||||
// Extract luminance
|
||||
VImage luminance = lab[0];
|
||||
|
||||
// Find luminance range
|
||||
VImage stats = luminance.stats();
|
||||
double min = stats(0, 0)[0];
|
||||
double max = stats(1, 0)[0];
|
||||
if (min != max) {
|
||||
int const min = lower == 0 ? luminance.min() : luminance.percent(lower);
|
||||
int const max = upper == 100 ? luminance.max() : luminance.percent(upper);
|
||||
|
||||
if (std::abs(max - min) > 1) {
|
||||
// Extract chroma
|
||||
VImage chroma = lab.extract_band(1, VImage::option()->set("n", 2));
|
||||
// Calculate multiplication factor and addition
|
||||
@@ -92,6 +95,13 @@ namespace sharp {
|
||||
return image;
|
||||
}
|
||||
|
||||
/*
|
||||
* Contrast limiting adapative histogram equalization (CLAHE)
|
||||
*/
|
||||
VImage Clahe(VImage image, int const width, int const height, int const maxSlope) {
|
||||
return image.hist_local(width, height, VImage::option()->set("max_slope", maxSlope));
|
||||
}
|
||||
|
||||
/*
|
||||
* Gamma encoding/decoding
|
||||
*/
|
||||
@@ -105,6 +115,32 @@ namespace sharp {
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Flatten image to remove alpha channel
|
||||
*/
|
||||
VImage Flatten(VImage image, std::vector<double> flattenBackground) {
|
||||
double const multiplier = sharp::Is16Bit(image.interpretation()) ? 256.0 : 1.0;
|
||||
std::vector<double> background {
|
||||
flattenBackground[0] * multiplier,
|
||||
flattenBackground[1] * multiplier,
|
||||
flattenBackground[2] * multiplier
|
||||
};
|
||||
return image.flatten(VImage::option()->set("background", background));
|
||||
}
|
||||
|
||||
/**
|
||||
* Produce the "negative" of the image.
|
||||
*/
|
||||
VImage Negate(VImage image, bool const negateAlpha) {
|
||||
if (HasAlpha(image) && !negateAlpha) {
|
||||
// Separate alpha channel
|
||||
VImage alpha = image[image.bands() - 1];
|
||||
return RemoveAlpha(image).invert().bandjoin(alpha);
|
||||
} else {
|
||||
return image.invert();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Gaussian blur. Use sigma of -1.0 for fast blur.
|
||||
*/
|
||||
@@ -119,7 +155,7 @@ namespace sharp {
|
||||
return image.conv(blur);
|
||||
} else {
|
||||
// Slower, accurate Gaussian blur
|
||||
return image.gaussblur(sigma);
|
||||
return StaySequential(image, VIPS_ACCESS_SEQUENTIAL).gaussblur(sigma);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,8 +185,8 @@ namespace sharp {
|
||||
*/
|
||||
VImage Recomb(VImage image, std::unique_ptr<double[]> const &matrix) {
|
||||
double *m = matrix.get();
|
||||
image = image.colourspace(VIPS_INTERPRETATION_sRGB);
|
||||
return image
|
||||
.colourspace(VIPS_INTERPRETATION_sRGB)
|
||||
.recomb(image.bands() == 3
|
||||
? VImage::new_from_memory(
|
||||
m, 9 * sizeof(double), 3, 3, 1, VIPS_FORMAT_DOUBLE
|
||||
@@ -162,7 +198,9 @@ namespace sharp {
|
||||
0.0, 0.0, 0.0, 1.0));
|
||||
}
|
||||
|
||||
VImage Modulate(VImage image, double const brightness, double const saturation, int const hue) {
|
||||
VImage Modulate(VImage image, double const brightness, double const saturation,
|
||||
int const hue, double const lightness) {
|
||||
VipsInterpretation colourspaceBeforeModulate = image.interpretation();
|
||||
if (HasAlpha(image)) {
|
||||
// Separate alpha channel
|
||||
VImage alpha = image[image.bands() - 1];
|
||||
@@ -170,25 +208,26 @@ namespace sharp {
|
||||
.colourspace(VIPS_INTERPRETATION_LCH)
|
||||
.linear(
|
||||
{ brightness, saturation, 1},
|
||||
{ 0.0, 0.0, static_cast<double>(hue) }
|
||||
{ lightness, 0.0, static_cast<double>(hue) }
|
||||
)
|
||||
.colourspace(VIPS_INTERPRETATION_sRGB)
|
||||
.colourspace(colourspaceBeforeModulate)
|
||||
.bandjoin(alpha);
|
||||
} else {
|
||||
return image
|
||||
.colourspace(VIPS_INTERPRETATION_LCH)
|
||||
.linear(
|
||||
{ brightness, saturation, 1 },
|
||||
{ 0.0, 0.0, static_cast<double>(hue) }
|
||||
{ lightness, 0.0, static_cast<double>(hue) }
|
||||
)
|
||||
.colourspace(VIPS_INTERPRETATION_sRGB);
|
||||
.colourspace(colourspaceBeforeModulate);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Sharpen flat and jagged areas. Use sigma of -1.0 for fast sharpen.
|
||||
*/
|
||||
VImage Sharpen(VImage image, double const sigma, double const flat, double const jagged) {
|
||||
VImage Sharpen(VImage image, double const sigma, double const m1, double const m2,
|
||||
double const x1, double const y2, double const y3) {
|
||||
if (sigma == -1.0) {
|
||||
// Fast, mild sharpen
|
||||
VImage sharpen = VImage::new_matrixv(3, 3,
|
||||
@@ -203,8 +242,14 @@ namespace sharp {
|
||||
if (colourspaceBeforeSharpen == VIPS_INTERPRETATION_RGB) {
|
||||
colourspaceBeforeSharpen = VIPS_INTERPRETATION_sRGB;
|
||||
}
|
||||
return image.sharpen(
|
||||
VImage::option()->set("sigma", sigma)->set("m1", flat)->set("m2", jagged))
|
||||
return image
|
||||
.sharpen(VImage::option()
|
||||
->set("sigma", sigma)
|
||||
->set("m1", m1)
|
||||
->set("m2", m2)
|
||||
->set("x1", x1)
|
||||
->set("y2", y2)
|
||||
->set("y3", y3))
|
||||
.colourspace(colourspaceBeforeSharpen);
|
||||
}
|
||||
}
|
||||
@@ -234,45 +279,193 @@ namespace sharp {
|
||||
/*
|
||||
Trim an image
|
||||
*/
|
||||
VImage Trim(VImage image, double const threshold) {
|
||||
VImage Trim(VImage image, std::vector<double> background, double threshold, bool const lineArt) {
|
||||
if (image.width() < 3 && image.height() < 3) {
|
||||
throw VError("Image to trim must be at least 3x3 pixels");
|
||||
}
|
||||
// Top-left pixel provides the background colour
|
||||
VImage background = image.extract_area(0, 0, 1, 1);
|
||||
if (HasAlpha(background)) {
|
||||
background = background.flatten();
|
||||
if (background.size() == 0) {
|
||||
// Top-left pixel provides the default background colour if none is given
|
||||
background = image.extract_area(0, 0, 1, 1)(0, 0);
|
||||
} else if (sharp::Is16Bit(image.interpretation())) {
|
||||
for (size_t i = 0; i < background.size(); i++) {
|
||||
background[i] *= 256.0;
|
||||
}
|
||||
threshold *= 256.0;
|
||||
}
|
||||
std::vector<double> backgroundAlpha({ background.back() });
|
||||
if (HasAlpha(image)) {
|
||||
background.pop_back();
|
||||
} else {
|
||||
background.resize(image.bands());
|
||||
}
|
||||
int left, top, width, height;
|
||||
left = image.find_trim(&top, &width, &height, VImage::option()
|
||||
->set("background", background(0, 0))
|
||||
->set("background", background)
|
||||
->set("line_art", lineArt)
|
||||
->set("threshold", threshold));
|
||||
if (width == 0 || height == 0) {
|
||||
if (HasAlpha(image)) {
|
||||
// Search alpha channel
|
||||
VImage alpha = image[image.bands() - 1];
|
||||
VImage backgroundAlpha = alpha.extract_area(0, 0, 1, 1);
|
||||
left = alpha.find_trim(&top, &width, &height, VImage::option()
|
||||
->set("background", backgroundAlpha(0, 0))
|
||||
->set("threshold", threshold));
|
||||
}
|
||||
if (width == 0 || height == 0) {
|
||||
throw VError("Unexpected error while trimming. Try to lower the tolerance");
|
||||
if (HasAlpha(image)) {
|
||||
// Search alpha channel (A)
|
||||
int leftA, topA, widthA, heightA;
|
||||
VImage alpha = image[image.bands() - 1];
|
||||
leftA = alpha.find_trim(&topA, &widthA, &heightA, VImage::option()
|
||||
->set("background", backgroundAlpha)
|
||||
->set("line_art", lineArt)
|
||||
->set("threshold", threshold));
|
||||
if (widthA > 0 && heightA > 0) {
|
||||
if (width > 0 && height > 0) {
|
||||
// Combined bounding box (B)
|
||||
int const leftB = std::min(left, leftA);
|
||||
int const topB = std::min(top, topA);
|
||||
int const widthB = std::max(left + width, leftA + widthA) - leftB;
|
||||
int const heightB = std::max(top + height, topA + heightA) - topB;
|
||||
return image.extract_area(leftB, topB, widthB, heightB);
|
||||
} else {
|
||||
// Use alpha only
|
||||
return image.extract_area(leftA, topA, widthA, heightA);
|
||||
}
|
||||
}
|
||||
}
|
||||
return image.extract_area(left, top, width, height);
|
||||
if (width > 0 && height > 0) {
|
||||
return image.extract_area(left, top, width, height);
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
/*
|
||||
* Calculate (a * in + b)
|
||||
*/
|
||||
VImage Linear(VImage image, double const a, double const b) {
|
||||
if (HasAlpha(image)) {
|
||||
VImage Linear(VImage image, std::vector<double> const a, std::vector<double> const b) {
|
||||
size_t const bands = static_cast<size_t>(image.bands());
|
||||
if (a.size() > bands) {
|
||||
throw VError("Band expansion using linear is unsupported");
|
||||
}
|
||||
bool const uchar = !Is16Bit(image.interpretation());
|
||||
if (HasAlpha(image) && a.size() != bands && (a.size() == 1 || a.size() == bands - 1 || bands - 1 == 1)) {
|
||||
// Separate alpha channel
|
||||
VImage alpha = image[image.bands() - 1];
|
||||
return RemoveAlpha(image).linear(a, b).bandjoin(alpha);
|
||||
VImage alpha = image[bands - 1];
|
||||
return RemoveAlpha(image).linear(a, b, VImage::option()->set("uchar", uchar)).bandjoin(alpha);
|
||||
} else {
|
||||
return image.linear(a, b);
|
||||
return image.linear(a, b, VImage::option()->set("uchar", uchar));
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Unflatten
|
||||
*/
|
||||
VImage Unflatten(VImage image) {
|
||||
if (HasAlpha(image)) {
|
||||
VImage alpha = image[image.bands() - 1];
|
||||
VImage noAlpha = RemoveAlpha(image);
|
||||
return noAlpha.bandjoin(alpha & (noAlpha.colourspace(VIPS_INTERPRETATION_B_W) < 255));
|
||||
} else {
|
||||
return image.bandjoin(image.colourspace(VIPS_INTERPRETATION_B_W) < 255);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Ensure the image is in a given colourspace
|
||||
*/
|
||||
VImage EnsureColourspace(VImage image, VipsInterpretation colourspace) {
|
||||
if (colourspace != VIPS_INTERPRETATION_LAST && image.interpretation() != colourspace) {
|
||||
image = image.colourspace(colourspace,
|
||||
VImage::option()->set("source_space", image.interpretation()));
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
/*
|
||||
* Split and crop each frame, reassemble, and update pageHeight.
|
||||
*/
|
||||
VImage CropMultiPage(VImage image, int left, int top, int width, int height,
|
||||
int nPages, int *pageHeight) {
|
||||
if (top == 0 && height == *pageHeight) {
|
||||
// Fast path; no need to adjust the height of the multi-page image
|
||||
return image.extract_area(left, 0, width, image.height());
|
||||
} else {
|
||||
std::vector<VImage> pages;
|
||||
pages.reserve(nPages);
|
||||
|
||||
// Split the image into cropped frames
|
||||
image = StaySequential(image, VIPS_ACCESS_SEQUENTIAL);
|
||||
for (int i = 0; i < nPages; i++) {
|
||||
pages.push_back(
|
||||
image.extract_area(left, *pageHeight * i + top, width, height));
|
||||
}
|
||||
|
||||
// Reassemble the frames into a tall, thin image
|
||||
VImage assembled = VImage::arrayjoin(pages,
|
||||
VImage::option()->set("across", 1));
|
||||
|
||||
// Update the page height
|
||||
*pageHeight = height;
|
||||
|
||||
return assembled;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Split into frames, embed each frame, reassemble, and update pageHeight.
|
||||
*/
|
||||
VImage EmbedMultiPage(VImage image, int left, int top, int width, int height,
|
||||
VipsExtend extendWith, std::vector<double> background, int nPages, int *pageHeight) {
|
||||
if (top == 0 && height == *pageHeight) {
|
||||
// Fast path; no need to adjust the height of the multi-page image
|
||||
return image.embed(left, 0, width, image.height(), VImage::option()
|
||||
->set("extend", extendWith)
|
||||
->set("background", background));
|
||||
} else if (left == 0 && width == image.width()) {
|
||||
// Fast path; no need to adjust the width of the multi-page image
|
||||
std::vector<VImage> pages;
|
||||
pages.reserve(nPages);
|
||||
|
||||
// Rearrange the tall image into a vertical grid
|
||||
image = image.grid(*pageHeight, nPages, 1);
|
||||
|
||||
// Do the embed on the wide image
|
||||
image = image.embed(0, top, image.width(), height, VImage::option()
|
||||
->set("extend", extendWith)
|
||||
->set("background", background));
|
||||
|
||||
// Split the wide image into frames
|
||||
for (int i = 0; i < nPages; i++) {
|
||||
pages.push_back(
|
||||
image.extract_area(width * i, 0, width, height));
|
||||
}
|
||||
|
||||
// Reassemble the frames into a tall, thin image
|
||||
VImage assembled = VImage::arrayjoin(pages,
|
||||
VImage::option()->set("across", 1));
|
||||
|
||||
// Update the page height
|
||||
*pageHeight = height;
|
||||
|
||||
return assembled;
|
||||
} else {
|
||||
std::vector<VImage> pages;
|
||||
pages.reserve(nPages);
|
||||
|
||||
// Split the image into frames
|
||||
for (int i = 0; i < nPages; i++) {
|
||||
pages.push_back(
|
||||
image.extract_area(0, *pageHeight * i, image.width(), *pageHeight));
|
||||
}
|
||||
|
||||
// Embed each frame in the target size
|
||||
for (int i = 0; i < nPages; i++) {
|
||||
pages[i] = pages[i].embed(left, top, width, height, VImage::option()
|
||||
->set("extend", extendWith)
|
||||
->set("background", background));
|
||||
}
|
||||
|
||||
// Reassemble the frames into a tall, thin image
|
||||
VImage assembled = VImage::arrayjoin(pages,
|
||||
VImage::option()->set("across", 1));
|
||||
|
||||
// Update the page height
|
||||
*pageHeight = height;
|
||||
|
||||
return assembled;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace sharp
|
||||
|
||||
@@ -1,16 +1,5 @@
|
||||
// Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Lovell Fuller and contributors.
|
||||
//
|
||||
// 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.
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
#ifndef SRC_OPERATIONS_H_
|
||||
#define SRC_OPERATIONS_H_
|
||||
@@ -26,20 +15,35 @@ using vips::VImage;
|
||||
namespace sharp {
|
||||
|
||||
/*
|
||||
* Tint an image using the specified chroma, preserving the original image luminance
|
||||
* Tint an image using the provided RGB.
|
||||
*/
|
||||
VImage Tint(VImage image, double const a, double const b);
|
||||
VImage Tint(VImage image, std::vector<double> const tint);
|
||||
|
||||
/*
|
||||
* Stretch luminance to cover full dynamic range.
|
||||
*/
|
||||
VImage Normalise(VImage image);
|
||||
VImage Normalise(VImage image, int const lower, int const upper);
|
||||
|
||||
/*
|
||||
* Contrast limiting adapative histogram equalization (CLAHE)
|
||||
*/
|
||||
VImage Clahe(VImage image, int const width, int const height, int const maxSlope);
|
||||
|
||||
/*
|
||||
* Gamma encoding/decoding
|
||||
*/
|
||||
VImage Gamma(VImage image, double const exponent);
|
||||
|
||||
/*
|
||||
* Flatten image to remove alpha channel
|
||||
*/
|
||||
VImage Flatten(VImage image, std::vector<double> flattenBackground);
|
||||
|
||||
/*
|
||||
* Produce the "negative" of the image.
|
||||
*/
|
||||
VImage Negate(VImage image, bool const negateAlpha);
|
||||
|
||||
/*
|
||||
* Gaussian blur. Use sigma of -1.0 for fast blur.
|
||||
*/
|
||||
@@ -54,7 +58,8 @@ namespace sharp {
|
||||
/*
|
||||
* Sharpen flat and jagged areas. Use sigma of -1.0 for fast sharpen.
|
||||
*/
|
||||
VImage Sharpen(VImage image, double const sigma, double const flat, double const jagged);
|
||||
VImage Sharpen(VImage image, double const sigma, double const m1, double const m2,
|
||||
double const x1, double const y2, double const y3);
|
||||
|
||||
/*
|
||||
Threshold an image
|
||||
@@ -74,12 +79,17 @@ namespace sharp {
|
||||
/*
|
||||
Trim an image
|
||||
*/
|
||||
VImage Trim(VImage image, double const threshold);
|
||||
VImage Trim(VImage image, std::vector<double> background, double threshold, bool const lineArt);
|
||||
|
||||
/*
|
||||
* Linear adjustment (a * in + b)
|
||||
*/
|
||||
VImage Linear(VImage image, double const a, double const b);
|
||||
VImage Linear(VImage image, std::vector<double> const a, std::vector<double> const b);
|
||||
|
||||
/*
|
||||
* Unflatten
|
||||
*/
|
||||
VImage Unflatten(VImage image);
|
||||
|
||||
/*
|
||||
* Recomb with a Matrix of the given bands/channel size.
|
||||
@@ -88,9 +98,27 @@ namespace sharp {
|
||||
VImage Recomb(VImage image, std::unique_ptr<double[]> const &matrix);
|
||||
|
||||
/*
|
||||
* Modulate brightness, saturation and hue
|
||||
* Modulate brightness, saturation, hue and lightness
|
||||
*/
|
||||
VImage Modulate(VImage image, double const brightness, double const saturation, int const hue);
|
||||
VImage Modulate(VImage image, double const brightness, double const saturation,
|
||||
int const hue, double const lightness);
|
||||
|
||||
/*
|
||||
* Ensure the image is in a given colourspace
|
||||
*/
|
||||
VImage EnsureColourspace(VImage image, VipsInterpretation colourspace);
|
||||
|
||||
/*
|
||||
* Split and crop each frame, reassemble, and update pageHeight.
|
||||
*/
|
||||
VImage CropMultiPage(VImage image, int left, int top, int width, int height,
|
||||
int nPages, int *pageHeight);
|
||||
|
||||
/*
|
||||
* Split into frames, embed each frame, reassemble, and update pageHeight.
|
||||
*/
|
||||
VImage EmbedMultiPage(VImage image, int left, int top, int width, int height,
|
||||
VipsExtend extendWith, std::vector<double> background, int nPages, int *pageHeight);
|
||||
|
||||
} // namespace sharp
|
||||
|
||||
|
||||
1404
src/pipeline.cc
1404
src/pipeline.cc
File diff suppressed because it is too large
Load Diff
202
src/pipeline.h
202
src/pipeline.h
@@ -1,16 +1,5 @@
|
||||
// Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Lovell Fuller and contributors.
|
||||
//
|
||||
// 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.
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
#ifndef SRC_PIPELINE_H_
|
||||
#define SRC_PIPELINE_H_
|
||||
@@ -18,6 +7,7 @@
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <unordered_map>
|
||||
|
||||
#include <napi.h>
|
||||
#include <vips/vips8>
|
||||
@@ -26,20 +16,13 @@
|
||||
|
||||
Napi::Value pipeline(const Napi::CallbackInfo& info);
|
||||
|
||||
enum class Canvas {
|
||||
CROP,
|
||||
EMBED,
|
||||
MAX,
|
||||
MIN,
|
||||
IGNORE_ASPECT
|
||||
};
|
||||
|
||||
struct Composite {
|
||||
sharp::InputDescriptor *input;
|
||||
VipsBlendMode mode;
|
||||
int gravity;
|
||||
int left;
|
||||
int top;
|
||||
bool hasOffset;
|
||||
bool tile;
|
||||
bool premultiplied;
|
||||
|
||||
@@ -47,8 +30,9 @@ struct Composite {
|
||||
input(nullptr),
|
||||
mode(VIPS_BLEND_MODE_OVER),
|
||||
gravity(0),
|
||||
left(-1),
|
||||
top(-1),
|
||||
left(0),
|
||||
top(0),
|
||||
hasOffset(false),
|
||||
tile(false),
|
||||
premultiplied(false) {}
|
||||
};
|
||||
@@ -72,39 +56,55 @@ struct PipelineBaton {
|
||||
int width;
|
||||
int height;
|
||||
int channels;
|
||||
Canvas canvas;
|
||||
VipsKernel kernel;
|
||||
sharp::Canvas canvas;
|
||||
int position;
|
||||
std::vector<double> resizeBackground;
|
||||
bool hasCropOffset;
|
||||
int cropOffsetLeft;
|
||||
int cropOffsetTop;
|
||||
bool hasAttentionCenter;
|
||||
int attentionX;
|
||||
int attentionY;
|
||||
bool premultiplied;
|
||||
std::string kernel;
|
||||
bool tileCentre;
|
||||
bool fastShrinkOnLoad;
|
||||
double tintA;
|
||||
double tintB;
|
||||
std::vector<double> tint;
|
||||
bool flatten;
|
||||
std::vector<double> flattenBackground;
|
||||
bool unflatten;
|
||||
bool negate;
|
||||
bool negateAlpha;
|
||||
double blurSigma;
|
||||
double brightness;
|
||||
double saturation;
|
||||
int hue;
|
||||
double lightness;
|
||||
int medianSize;
|
||||
double sharpenSigma;
|
||||
double sharpenFlat;
|
||||
double sharpenJagged;
|
||||
double sharpenM1;
|
||||
double sharpenM2;
|
||||
double sharpenX1;
|
||||
double sharpenY2;
|
||||
double sharpenY3;
|
||||
int threshold;
|
||||
bool thresholdGrayscale;
|
||||
std::vector<double> trimBackground;
|
||||
double trimThreshold;
|
||||
bool trimLineArt;
|
||||
int trimOffsetLeft;
|
||||
int trimOffsetTop;
|
||||
double linearA;
|
||||
double linearB;
|
||||
std::vector<double> linearA;
|
||||
std::vector<double> linearB;
|
||||
double gamma;
|
||||
double gammaOut;
|
||||
bool greyscale;
|
||||
bool normalise;
|
||||
int normaliseLower;
|
||||
int normaliseUpper;
|
||||
int claheWidth;
|
||||
int claheHeight;
|
||||
int claheMaxSlope;
|
||||
bool useExifOrientation;
|
||||
int angle;
|
||||
double rotationAngle;
|
||||
@@ -117,7 +117,16 @@ struct PipelineBaton {
|
||||
int extendLeft;
|
||||
int extendRight;
|
||||
std::vector<double> extendBackground;
|
||||
VipsExtend extendWith;
|
||||
bool withoutEnlargement;
|
||||
bool withoutReduction;
|
||||
std::vector<double> affineMatrix;
|
||||
std::vector<double> affineBackground;
|
||||
double affineIdx;
|
||||
double affineIdy;
|
||||
double affineOdx;
|
||||
double affineOdy;
|
||||
std::string affineInterpolator;
|
||||
int jpegQuality;
|
||||
bool jpegProgressive;
|
||||
std::string jpegChromaSubsampling;
|
||||
@@ -131,31 +140,61 @@ struct PipelineBaton {
|
||||
bool pngAdaptiveFiltering;
|
||||
bool pngPalette;
|
||||
int pngQuality;
|
||||
int pngColours;
|
||||
int pngEffort;
|
||||
int pngBitdepth;
|
||||
double pngDither;
|
||||
int jp2Quality;
|
||||
bool jp2Lossless;
|
||||
int jp2TileHeight;
|
||||
int jp2TileWidth;
|
||||
std::string jp2ChromaSubsampling;
|
||||
int webpQuality;
|
||||
int webpAlphaQuality;
|
||||
bool webpNearLossless;
|
||||
bool webpLossless;
|
||||
bool webpSmartSubsample;
|
||||
int webpReductionEffort;
|
||||
VipsForeignWebpPreset webpPreset;
|
||||
int webpEffort;
|
||||
bool webpMinSize;
|
||||
bool webpMixed;
|
||||
int gifBitdepth;
|
||||
int gifEffort;
|
||||
double gifDither;
|
||||
double gifInterFrameMaxError;
|
||||
double gifInterPaletteMaxError;
|
||||
bool gifReuse;
|
||||
bool gifProgressive;
|
||||
int tiffQuality;
|
||||
VipsForeignTiffCompression tiffCompression;
|
||||
VipsForeignTiffPredictor tiffPredictor;
|
||||
bool tiffPyramid;
|
||||
int tiffBitdepth;
|
||||
bool tiffMiniswhite;
|
||||
bool tiffTile;
|
||||
int tiffTileHeight;
|
||||
int tiffTileWidth;
|
||||
double tiffXres;
|
||||
double tiffYres;
|
||||
VipsForeignTiffResunit tiffResolutionUnit;
|
||||
int heifQuality;
|
||||
VipsForeignHeifCompression heifCompression;
|
||||
int heifEffort;
|
||||
std::string heifChromaSubsampling;
|
||||
bool heifLossless;
|
||||
int heifBitdepth;
|
||||
double jxlDistance;
|
||||
int jxlDecodingTier;
|
||||
int jxlEffort;
|
||||
bool jxlLossless;
|
||||
VipsBandFormat rawDepth;
|
||||
std::string err;
|
||||
bool withMetadata;
|
||||
int keepMetadata;
|
||||
int withMetadataOrientation;
|
||||
std::string withMetadataIcc;
|
||||
double withMetadataDensity;
|
||||
std::string withIccProfile;
|
||||
std::unordered_map<std::string, std::string> withExif;
|
||||
bool withExifMerge;
|
||||
int timeoutSeconds;
|
||||
std::unique_ptr<double[]> convKernel;
|
||||
int convKernelWidth;
|
||||
int convKernelHeight;
|
||||
@@ -166,9 +205,9 @@ struct PipelineBaton {
|
||||
VipsOperationBoolean bandBoolOp;
|
||||
int extractChannel;
|
||||
bool removeAlpha;
|
||||
bool ensureAlpha;
|
||||
double ensureAlpha;
|
||||
VipsInterpretation colourspacePipeline;
|
||||
VipsInterpretation colourspace;
|
||||
int pageHeight;
|
||||
std::vector<int> delay;
|
||||
int loop;
|
||||
int tileSize;
|
||||
@@ -180,6 +219,8 @@ struct PipelineBaton {
|
||||
std::vector<double> tileBackground;
|
||||
int tileSkipBlanks;
|
||||
VipsForeignDzDepth tileDepth;
|
||||
std::string tileId;
|
||||
std::string tileBasename;
|
||||
std::unique_ptr<double[]> recombMatrix;
|
||||
|
||||
PipelineBaton():
|
||||
@@ -188,36 +229,52 @@ struct PipelineBaton {
|
||||
topOffsetPre(-1),
|
||||
topOffsetPost(-1),
|
||||
channels(0),
|
||||
canvas(Canvas::CROP),
|
||||
kernel(VIPS_KERNEL_LANCZOS3),
|
||||
canvas(sharp::Canvas::CROP),
|
||||
position(0),
|
||||
resizeBackground{ 0.0, 0.0, 0.0, 255.0 },
|
||||
hasCropOffset(false),
|
||||
cropOffsetLeft(0),
|
||||
cropOffsetTop(0),
|
||||
hasAttentionCenter(false),
|
||||
attentionX(0),
|
||||
attentionY(0),
|
||||
premultiplied(false),
|
||||
tintA(128.0),
|
||||
tintB(128.0),
|
||||
tint{ -1.0, 0.0, 0.0, 0.0 },
|
||||
flatten(false),
|
||||
flattenBackground{ 0.0, 0.0, 0.0 },
|
||||
unflatten(false),
|
||||
negate(false),
|
||||
negateAlpha(true),
|
||||
blurSigma(0.0),
|
||||
brightness(1.0),
|
||||
saturation(1.0),
|
||||
hue(0),
|
||||
lightness(0),
|
||||
medianSize(0),
|
||||
sharpenSigma(0.0),
|
||||
sharpenFlat(1.0),
|
||||
sharpenJagged(2.0),
|
||||
sharpenM1(1.0),
|
||||
sharpenM2(2.0),
|
||||
sharpenX1(2.0),
|
||||
sharpenY2(10.0),
|
||||
sharpenY3(20.0),
|
||||
threshold(0),
|
||||
thresholdGrayscale(true),
|
||||
trimThreshold(0.0),
|
||||
trimBackground{},
|
||||
trimThreshold(-1.0),
|
||||
trimLineArt(false),
|
||||
trimOffsetLeft(0),
|
||||
trimOffsetTop(0),
|
||||
linearA(1.0),
|
||||
linearB(0.0),
|
||||
linearA{},
|
||||
linearB{},
|
||||
gamma(0.0),
|
||||
greyscale(false),
|
||||
normalise(false),
|
||||
normaliseLower(1),
|
||||
normaliseUpper(99),
|
||||
claheWidth(0),
|
||||
claheHeight(0),
|
||||
claheMaxSlope(3),
|
||||
useExifOrientation(false),
|
||||
angle(0),
|
||||
rotationAngle(0.0),
|
||||
@@ -229,7 +286,16 @@ struct PipelineBaton {
|
||||
extendLeft(0),
|
||||
extendRight(0),
|
||||
extendBackground{ 0.0, 0.0, 0.0, 255.0 },
|
||||
extendWith(VIPS_EXTEND_BACKGROUND),
|
||||
withoutEnlargement(false),
|
||||
withoutReduction(false),
|
||||
affineMatrix{ 1.0, 0.0, 0.0, 1.0 },
|
||||
affineBackground{ 0.0, 0.0, 0.0, 255.0 },
|
||||
affineIdx(0),
|
||||
affineIdy(0),
|
||||
affineOdx(0),
|
||||
affineOdy(0),
|
||||
affineInterpolator("bicubic"),
|
||||
jpegQuality(80),
|
||||
jpegProgressive(false),
|
||||
jpegChromaSubsampling("4:2:0"),
|
||||
@@ -239,33 +305,62 @@ struct PipelineBaton {
|
||||
jpegOptimiseScans(false),
|
||||
jpegOptimiseCoding(true),
|
||||
pngProgressive(false),
|
||||
pngCompressionLevel(9),
|
||||
pngCompressionLevel(6),
|
||||
pngAdaptiveFiltering(false),
|
||||
pngPalette(false),
|
||||
pngQuality(100),
|
||||
pngColours(256),
|
||||
pngEffort(7),
|
||||
pngBitdepth(8),
|
||||
pngDither(1.0),
|
||||
jp2Quality(80),
|
||||
jp2Lossless(false),
|
||||
jp2TileHeight(512),
|
||||
jp2TileWidth(512),
|
||||
jp2ChromaSubsampling("4:4:4"),
|
||||
webpQuality(80),
|
||||
webpAlphaQuality(100),
|
||||
webpNearLossless(false),
|
||||
webpLossless(false),
|
||||
webpSmartSubsample(false),
|
||||
webpReductionEffort(4),
|
||||
webpPreset(VIPS_FOREIGN_WEBP_PRESET_DEFAULT),
|
||||
webpEffort(4),
|
||||
webpMinSize(false),
|
||||
webpMixed(false),
|
||||
gifBitdepth(8),
|
||||
gifEffort(7),
|
||||
gifDither(1.0),
|
||||
gifInterFrameMaxError(0.0),
|
||||
gifInterPaletteMaxError(3.0),
|
||||
gifReuse(true),
|
||||
gifProgressive(false),
|
||||
tiffQuality(80),
|
||||
tiffCompression(VIPS_FOREIGN_TIFF_COMPRESSION_JPEG),
|
||||
tiffPredictor(VIPS_FOREIGN_TIFF_PREDICTOR_HORIZONTAL),
|
||||
tiffPyramid(false),
|
||||
tiffBitdepth(8),
|
||||
tiffMiniswhite(false),
|
||||
tiffTile(false),
|
||||
tiffTileHeight(256),
|
||||
tiffTileWidth(256),
|
||||
tiffXres(1.0),
|
||||
tiffYres(1.0),
|
||||
heifQuality(80),
|
||||
heifCompression(VIPS_FOREIGN_HEIF_COMPRESSION_HEVC),
|
||||
tiffResolutionUnit(VIPS_FOREIGN_TIFF_RESUNIT_INCH),
|
||||
heifQuality(50),
|
||||
heifCompression(VIPS_FOREIGN_HEIF_COMPRESSION_AV1),
|
||||
heifEffort(4),
|
||||
heifChromaSubsampling("4:4:4"),
|
||||
heifLossless(false),
|
||||
withMetadata(false),
|
||||
heifBitdepth(8),
|
||||
jxlDistance(1.0),
|
||||
jxlDecodingTier(0),
|
||||
jxlEffort(7),
|
||||
jxlLossless(false),
|
||||
rawDepth(VIPS_FORMAT_UCHAR),
|
||||
keepMetadata(0),
|
||||
withMetadataOrientation(-1),
|
||||
withMetadataDensity(0.0),
|
||||
withExifMerge(true),
|
||||
timeoutSeconds(0),
|
||||
convKernelWidth(0),
|
||||
convKernelHeight(0),
|
||||
convKernelScale(0.0),
|
||||
@@ -275,10 +370,9 @@ struct PipelineBaton {
|
||||
bandBoolOp(VIPS_OPERATION_BOOLEAN_LAST),
|
||||
extractChannel(-1),
|
||||
removeAlpha(false),
|
||||
ensureAlpha(false),
|
||||
ensureAlpha(-1.0),
|
||||
colourspacePipeline(VIPS_INTERPRETATION_LAST),
|
||||
colourspace(VIPS_INTERPRETATION_LAST),
|
||||
pageHeight(0),
|
||||
delay{-1},
|
||||
loop(-1),
|
||||
tileSize(256),
|
||||
tileOverlap(0),
|
||||
|
||||
30
src/sharp.cc
30
src/sharp.cc
@@ -1,16 +1,7 @@
|
||||
// Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Lovell Fuller and contributors.
|
||||
//
|
||||
// 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.
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
#include <mutex> // NOLINT(build/c++11)
|
||||
|
||||
#include <napi.h>
|
||||
#include <vips/vips8>
|
||||
@@ -21,14 +12,11 @@
|
||||
#include "utilities.h"
|
||||
#include "stats.h"
|
||||
|
||||
static void* sharp_vips_init(void*) {
|
||||
vips_init("sharp");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Napi::Object init(Napi::Env env, Napi::Object exports) {
|
||||
static GOnce sharp_vips_init_once = G_ONCE_INIT;
|
||||
g_once(&sharp_vips_init_once, static_cast<GThreadFunc>(sharp_vips_init), nullptr);
|
||||
static std::once_flag sharp_vips_init_once;
|
||||
std::call_once(sharp_vips_init_once, []() {
|
||||
vips_init("sharp");
|
||||
});
|
||||
|
||||
g_log_set_handler("VIPS", static_cast<GLogLevelFlags>(G_LOG_LEVEL_WARNING),
|
||||
static_cast<GLogFunc>(sharp::VipsWarningCallback), nullptr);
|
||||
@@ -42,7 +30,9 @@ Napi::Object init(Napi::Env env, Napi::Object exports) {
|
||||
exports.Set("simd", Napi::Function::New(env, simd));
|
||||
exports.Set("libvipsVersion", Napi::Function::New(env, libvipsVersion));
|
||||
exports.Set("format", Napi::Function::New(env, format));
|
||||
exports.Set("block", Napi::Function::New(env, block));
|
||||
exports.Set("_maxColourDistance", Napi::Function::New(env, _maxColourDistance));
|
||||
exports.Set("_isUsingJemalloc", Napi::Function::New(env, _isUsingJemalloc));
|
||||
exports.Set("stats", Napi::Function::New(env, stats));
|
||||
return exports;
|
||||
}
|
||||
|
||||
44
src/stats.cc
44
src/stats.cc
@@ -1,16 +1,5 @@
|
||||
// Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Lovell Fuller and contributors.
|
||||
//
|
||||
// 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.
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
#include <numeric>
|
||||
#include <vector>
|
||||
@@ -41,7 +30,7 @@ class StatsWorker : public Napi::AsyncWorker {
|
||||
|
||||
void Execute() {
|
||||
// Decrement queued task counter
|
||||
g_atomic_int_dec_and_test(&sharp::counterQueue);
|
||||
sharp::counterQueue--;
|
||||
|
||||
vips::VImage image;
|
||||
sharp::ImageType imageType = sharp::ImageType::UNKNOWN;
|
||||
@@ -80,12 +69,14 @@ class StatsWorker : public Napi::AsyncWorker {
|
||||
// Estimate entropy via histogram of greyscale value frequency
|
||||
baton->entropy = std::abs(greyscale.hist_find().hist_entropy());
|
||||
// Estimate sharpness via standard deviation of greyscale laplacian
|
||||
VImage laplacian = VImage::new_matrixv(3, 3,
|
||||
0.0, 1.0, 0.0,
|
||||
1.0, -4.0, 1.0,
|
||||
0.0, 1.0, 0.0);
|
||||
laplacian.set("scale", 9.0);
|
||||
baton->sharpness = greyscale.conv(laplacian).deviate();
|
||||
if (image.width() > 1 || image.height() > 1) {
|
||||
VImage laplacian = VImage::new_matrixv(3, 3,
|
||||
0.0, 1.0, 0.0,
|
||||
1.0, -4.0, 1.0,
|
||||
0.0, 1.0, 0.0);
|
||||
laplacian.set("scale", 9.0);
|
||||
baton->sharpness = greyscale.conv(laplacian).deviate();
|
||||
}
|
||||
// Most dominant sRGB colour via 4096-bin 3D histogram
|
||||
vips::VImage hist = sharp::RemoveAlpha(image)
|
||||
.colourspace(VIPS_INTERPRETATION_sRGB)
|
||||
@@ -115,7 +106,7 @@ class StatsWorker : public Napi::AsyncWorker {
|
||||
// Handle warnings
|
||||
std::string warning = sharp::VipsWarningPop();
|
||||
while (!warning.empty()) {
|
||||
debuglog.Call({ Napi::String::New(env, warning) });
|
||||
debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) });
|
||||
warning = sharp::VipsWarningPop();
|
||||
}
|
||||
|
||||
@@ -150,9 +141,9 @@ class StatsWorker : public Napi::AsyncWorker {
|
||||
dominant.Set("g", baton->dominantGreen);
|
||||
dominant.Set("b", baton->dominantBlue);
|
||||
info.Set("dominant", dominant);
|
||||
Callback().MakeCallback(Receiver().Value(), { env.Null(), info });
|
||||
Callback().Call(Receiver().Value(), { env.Null(), info });
|
||||
} else {
|
||||
Callback().MakeCallback(Receiver().Value(), { Napi::Error::New(env, baton->err).Value() });
|
||||
Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() });
|
||||
}
|
||||
|
||||
delete baton->input;
|
||||
@@ -170,22 +161,23 @@ class StatsWorker : public Napi::AsyncWorker {
|
||||
Napi::Value stats(const Napi::CallbackInfo& info) {
|
||||
// V8 objects are converted to non-V8 types held in the baton struct
|
||||
StatsBaton *baton = new StatsBaton;
|
||||
Napi::Object options = info[0].As<Napi::Object>();
|
||||
Napi::Object options = info[size_t(0)].As<Napi::Object>();
|
||||
|
||||
// Input
|
||||
baton->input = sharp::CreateInputDescriptor(options.Get("input").As<Napi::Object>());
|
||||
baton->input->access = VIPS_ACCESS_RANDOM;
|
||||
|
||||
// Function to notify of libvips warnings
|
||||
Napi::Function debuglog = options.Get("debuglog").As<Napi::Function>();
|
||||
|
||||
// Join queue for worker thread
|
||||
Napi::Function callback = info[1].As<Napi::Function>();
|
||||
Napi::Function callback = info[size_t(1)].As<Napi::Function>();
|
||||
StatsWorker *worker = new StatsWorker(callback, baton, debuglog);
|
||||
worker->Receiver().Set("options", options);
|
||||
worker->Queue();
|
||||
|
||||
// Increment queued task counter
|
||||
g_atomic_int_inc(&sharp::counterQueue);
|
||||
sharp::counterQueue++;
|
||||
|
||||
return info.Env().Undefined();
|
||||
}
|
||||
|
||||
15
src/stats.h
15
src/stats.h
@@ -1,16 +1,5 @@
|
||||
// Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Lovell Fuller and contributors.
|
||||
//
|
||||
// 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.
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
#ifndef SRC_STATS_H_
|
||||
#define SRC_STATS_H_
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user