Compare commits
165 Commits
v0.33.0-al
...
v0.33.4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
19d0e272e6 | ||
|
|
16b764f1c1 | ||
|
|
1593ee3838 | ||
|
|
668b5ba8bc | ||
|
|
29336f4cc7 | ||
|
|
b5fddd7c5e | ||
|
|
da655a1859 | ||
|
|
93c615d39f | ||
|
|
f325dc3ec9 | ||
|
|
0fde71c783 | ||
|
|
9c8fbaa1cc | ||
|
|
a9e662e612 | ||
|
|
ba843002be | ||
|
|
7f3d452bc5 | ||
|
|
aa8bc19362 | ||
|
|
36e60bf040 | ||
|
|
a1309aa3b8 | ||
|
|
3e8a0fc522 | ||
|
|
397ee492d9 | ||
|
|
52b9dc0f63 | ||
|
|
a715c73fc2 | ||
|
|
579cf93030 | ||
|
|
f67228e5ea | ||
|
|
6257994746 | ||
|
|
7950fc0ea3 | ||
|
|
fc93ab3b82 | ||
|
|
0981b24f60 | ||
|
|
02fd565476 | ||
|
|
e55bb93b10 | ||
|
|
55466f122c | ||
|
|
ede8217ab3 | ||
|
|
2689fb4e65 | ||
|
|
eaf31a59e5 | ||
|
|
aa1bbcb5c1 | ||
|
|
3c26080c39 | ||
|
|
dc07fd4e9c | ||
|
|
7bc74feb11 | ||
|
|
c5f318ed4d | ||
|
|
8fbb1cd154 | ||
|
|
88aee8a887 | ||
|
|
0f77b18078 | ||
|
|
3eeaee71c0 | ||
|
|
045d54e2e6 | ||
|
|
75fedf1b75 | ||
|
|
debdacb726 | ||
|
|
1c8ae67ed2 | ||
|
|
0eb57698ec | ||
|
|
bc95531f2d | ||
|
|
60f4048d6c | ||
|
|
fb70fbb09f | ||
|
|
fc439bedf1 | ||
|
|
26d0b7147d | ||
|
|
af6aa8a690 | ||
|
|
bd4f1abba2 | ||
|
|
d2656a3679 | ||
|
|
a3b45ceccc | ||
|
|
0dcc7d50a8 | ||
|
|
bcb22af034 | ||
|
|
d04dc62666 | ||
|
|
c30d355f97 | ||
|
|
49cb148b38 | ||
|
|
3bc31a8b20 | ||
|
|
c28523e70e | ||
|
|
278f393f74 | ||
|
|
cbf68c1395 | ||
|
|
45e8071599 | ||
|
|
b96389d975 | ||
|
|
a77ac6ae25 | ||
|
|
9bcf399b4c | ||
|
|
4aacee8055 | ||
|
|
0b18aeff62 | ||
|
|
bed1c2ac18 | ||
|
|
8cd832656b | ||
|
|
0499f59e71 | ||
|
|
1fa59bf9b3 | ||
|
|
db40ee6912 | ||
|
|
02b98b8e1b | ||
|
|
31fef216e4 | ||
|
|
77ab5d7a51 | ||
|
|
cd5cf7ce2d | ||
|
|
39cb9d9a6c | ||
|
|
4919bc5134 | ||
|
|
a4e64eb01f | ||
|
|
328b18df88 | ||
|
|
5e7bf32e5e | ||
|
|
04403f4e5f | ||
|
|
420e0822b4 | ||
|
|
f7a3ea6415 | ||
|
|
f28e79ef4f | ||
|
|
5cd787bf85 | ||
|
|
021d637fd6 | ||
|
|
2e14096af7 | ||
|
|
fe2b298a2f | ||
|
|
c9e3996007 | ||
|
|
3a0c375692 | ||
|
|
c5eaeb2ddb | ||
|
|
19fa4cd1d3 | ||
|
|
0adf7ef16f | ||
|
|
8f7fb96a44 | ||
|
|
9e3b021b1a | ||
|
|
25164d4cef | ||
|
|
516b1ec332 | ||
|
|
95ba045a69 | ||
|
|
6e02f9288e | ||
|
|
a584ae093e | ||
|
|
1592f96b7b | ||
|
|
004fff975f | ||
|
|
4d049ee8f5 | ||
|
|
c80e92fa16 | ||
|
|
545e09fad2 | ||
|
|
133dc56ff4 | ||
|
|
9c877d93fa | ||
|
|
7ad86fed03 | ||
|
|
31cf07f0ba | ||
|
|
4ffb48711a | ||
|
|
3da96a86e6 | ||
|
|
45ed9ea9bf | ||
|
|
61057f25bc | ||
|
|
68ef72cb61 | ||
|
|
ef32dccb83 | ||
|
|
e78200cc84 | ||
|
|
3f7313d031 | ||
|
|
139e4b9f65 | ||
|
|
9680f00ddd | ||
|
|
0b0ebfe6f8 | ||
|
|
5aadb8294c | ||
|
|
ace1681886 | ||
|
|
75ef61a958 | ||
|
|
2dba5b5451 | ||
|
|
a8f68ba7f0 | ||
|
|
475bf16b09 | ||
|
|
67f49a8dcd | ||
|
|
074004392c | ||
|
|
8c5a493f68 | ||
|
|
cccd1635c5 | ||
|
|
1915c1387e | ||
|
|
4a37a27cca | ||
|
|
ab8a4ed532 | ||
|
|
12fd512b83 | ||
|
|
239435a6dc | ||
|
|
7c1551bdc9 | ||
|
|
bdcf02695f | ||
|
|
d206fd5392 | ||
|
|
0bd1715f36 | ||
|
|
2e7c60675b | ||
|
|
7caaa8e22b | ||
|
|
839c92bf3d | ||
|
|
28aa176957 | ||
|
|
0f24f0f214 | ||
|
|
655da113c8 | ||
|
|
159b986cdd | ||
|
|
069d1786f5 | ||
|
|
f43829a16a | ||
|
|
65e61ad001 | ||
|
|
0107a4de81 | ||
|
|
337ce7b1c2 | ||
|
|
3719f79065 | ||
|
|
8d1747aa6a | ||
|
|
de9bdcba0a | ||
|
|
f8b6cb6d5b | ||
|
|
e6942805b4 | ||
|
|
47e76c9981 | ||
|
|
68fa84ef6f | ||
|
|
ff2fb18c76 | ||
|
|
28a9b1e9fa |
@@ -24,7 +24,7 @@ jobs:
|
|||||||
linux-arm64-glibc-node-18:
|
linux-arm64-glibc-node-18:
|
||||||
resource_class: arm.medium
|
resource_class: arm.medium
|
||||||
machine:
|
machine:
|
||||||
image: ubuntu-2004:current
|
image: ubuntu-2204:current
|
||||||
steps:
|
steps:
|
||||||
- checkout
|
- checkout
|
||||||
- run: |
|
- run: |
|
||||||
@@ -38,7 +38,7 @@ jobs:
|
|||||||
- run: sudo docker exec sharp sh -c "npm test"
|
- run: sudo docker exec sharp sh -c "npm test"
|
||||||
- run: |
|
- run: |
|
||||||
sudo docker exec sharp sh -c "npm run package-from-local-build"
|
sudo docker exec sharp sh -c "npm run package-from-local-build"
|
||||||
sudo docker exec sharp sh -c "npm pkg set \"optionalDependencies.@sharpen/sharp-linux-arm64=file:./npm/linux-arm64\""
|
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 run clean"
|
||||||
sudo docker exec sharp sh -c "npm install --ignore-scripts"
|
sudo docker exec sharp sh -c "npm install --ignore-scripts"
|
||||||
sudo docker exec sharp sh -c "npm test"
|
sudo docker exec sharp sh -c "npm test"
|
||||||
@@ -46,7 +46,7 @@ jobs:
|
|||||||
linux-arm64-glibc-node-20:
|
linux-arm64-glibc-node-20:
|
||||||
resource_class: arm.medium
|
resource_class: arm.medium
|
||||||
machine:
|
machine:
|
||||||
image: ubuntu-2004:current
|
image: ubuntu-2204:current
|
||||||
steps:
|
steps:
|
||||||
- checkout
|
- checkout
|
||||||
- run: |
|
- run: |
|
||||||
@@ -62,14 +62,14 @@ jobs:
|
|||||||
- run: sudo docker exec sharp sh -c "npm test"
|
- run: sudo docker exec sharp sh -c "npm test"
|
||||||
- run: |
|
- run: |
|
||||||
sudo docker exec sharp sh -c "npm run package-from-local-build"
|
sudo docker exec sharp sh -c "npm run package-from-local-build"
|
||||||
sudo docker exec sharp sh -c "npm pkg set \"optionalDependencies.@sharpen/sharp-linux-arm64=file:./npm/linux-arm64\""
|
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 run clean"
|
||||||
sudo docker exec sharp sh -c "npm install --ignore-scripts"
|
sudo docker exec sharp sh -c "npm install --ignore-scripts"
|
||||||
sudo docker exec sharp sh -c "npm test"
|
sudo docker exec sharp sh -c "npm test"
|
||||||
linux-arm64-musl-node-18:
|
linux-arm64-musl-node-18:
|
||||||
resource_class: arm.medium
|
resource_class: arm.medium
|
||||||
machine:
|
machine:
|
||||||
image: ubuntu-2004:current
|
image: ubuntu-2204:current
|
||||||
steps:
|
steps:
|
||||||
- checkout
|
- checkout
|
||||||
- run: |
|
- run: |
|
||||||
@@ -79,7 +79,7 @@ jobs:
|
|||||||
- run: sudo docker exec sharp sh -c "npm test"
|
- run: sudo docker exec sharp sh -c "npm test"
|
||||||
- run: |
|
- run: |
|
||||||
sudo docker exec sharp sh -c "npm run package-from-local-build"
|
sudo docker exec sharp sh -c "npm run package-from-local-build"
|
||||||
sudo docker exec sharp sh -c "npm pkg set \"optionalDependencies.@sharpen/sharp-linuxmusl-arm64=file:./npm/linuxmusl-arm64\""
|
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 run clean"
|
||||||
sudo docker exec sharp sh -c "npm install --ignore-scripts"
|
sudo docker exec sharp sh -c "npm install --ignore-scripts"
|
||||||
sudo docker exec sharp sh -c "npm test"
|
sudo docker exec sharp sh -c "npm test"
|
||||||
@@ -87,7 +87,7 @@ jobs:
|
|||||||
linux-arm64-musl-node-20:
|
linux-arm64-musl-node-20:
|
||||||
resource_class: arm.medium
|
resource_class: arm.medium
|
||||||
machine:
|
machine:
|
||||||
image: ubuntu-2004:current
|
image: ubuntu-2204:current
|
||||||
steps:
|
steps:
|
||||||
- checkout
|
- checkout
|
||||||
- run: |
|
- run: |
|
||||||
@@ -99,7 +99,7 @@ jobs:
|
|||||||
- run: sudo docker exec sharp sh -c "npm test"
|
- run: sudo docker exec sharp sh -c "npm test"
|
||||||
- run: |
|
- run: |
|
||||||
sudo docker exec sharp sh -c "npm run package-from-local-build"
|
sudo docker exec sharp sh -c "npm run package-from-local-build"
|
||||||
sudo docker exec sharp sh -c "npm pkg set \"optionalDependencies.@sharpen/sharp-linuxmusl-arm64=file:./npm/linuxmusl-arm64\""
|
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 run clean"
|
||||||
sudo docker exec sharp sh -c "npm install --ignore-scripts"
|
sudo docker exec sharp sh -c "npm install --ignore-scripts"
|
||||||
sudo docker exec sharp sh -c "npm test"
|
sudo docker exec sharp sh -c "npm test"
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
freebsd_instance:
|
freebsd_instance:
|
||||||
image_family: freebsd-13-2
|
image_family: freebsd-14-0-snap
|
||||||
|
|
||||||
task:
|
task:
|
||||||
name: FreeBSD
|
name: FreeBSD
|
||||||
@@ -10,7 +10,8 @@ task:
|
|||||||
- pkg update -f
|
- pkg update -f
|
||||||
- pkg upgrade -y
|
- pkg upgrade -y
|
||||||
- pkg install -y devel/git devel/pkgconf graphics/vips www/node20 www/npm
|
- pkg install -y devel/git devel/pkgconf graphics/vips www/node20 www/npm
|
||||||
|
- pkg-config --modversion vips-cpp
|
||||||
install_script:
|
install_script:
|
||||||
- npm install --build-from-source
|
- npm install --build-from-source
|
||||||
test_script:
|
test_script:
|
||||||
- npm test
|
- npx mocha --no-config --spec=test/unit/io.js --timeout=30000
|
||||||
|
|||||||
1
.gitattributes
vendored
@@ -1 +0,0 @@
|
|||||||
src/libvips/* linguist-vendored
|
|
||||||
2
.github/CONTRIBUTING.md
vendored
@@ -63,7 +63,7 @@ By way of example, the `background()` method present in v0.20.0 was deprecated i
|
|||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
The public API is documented with [JSDoc](http://usejsdoc.org/) annotated comments.
|
The public API is documented with [JSDoc](https://jsdoc.app/) annotated comments.
|
||||||
|
|
||||||
These can be converted to Markdown by running:
|
These can be converted to Markdown by running:
|
||||||
```sh
|
```sh
|
||||||
|
|||||||
33
.github/ISSUE_TEMPLATE/installation.md
vendored
@@ -11,7 +11,10 @@ labels: installation
|
|||||||
|
|
||||||
<!-- Please place an [x] in the box to confirm. -->
|
<!-- Please place an [x] in the box to confirm. -->
|
||||||
|
|
||||||
- [ ] I have read the [documentation relating to installation](https://sharp.pixelplumbing.com/install).
|
- [ ] I have read and understood all of the [documentation relating to installation](https://sharp.pixelplumbing.com/install).
|
||||||
|
- [ ] I have searched for known bugs relating to this problem in my choice of package manager.
|
||||||
|
|
||||||
|
You must confirm both of these before continuing.
|
||||||
|
|
||||||
### Are you using the latest version of sharp?
|
### Are you using the latest version of sharp?
|
||||||
|
|
||||||
@@ -21,27 +24,37 @@ labels: installation
|
|||||||
|
|
||||||
If you cannot confirm this, please upgrade to the latest version and try again before opening an issue.
|
If you cannot confirm this, please upgrade to the latest version and try again before opening an issue.
|
||||||
|
|
||||||
If you are using another package which depends on a version of `sharp` that is not the latest, please open an issue against that package instead.
|
If you are using another package which depends on a version of `sharp` that is not the latest,
|
||||||
|
please open an issue against that package instead.
|
||||||
|
|
||||||
### Are you using a supported runtime?
|
### Are you using a supported runtime?
|
||||||
|
|
||||||
<!-- Please place an [x] in the relevant box to confirm. -->
|
<!-- Please place an [x] in the relevant box to confirm. -->
|
||||||
|
|
||||||
- [ ] I am using Node.js 18 with a version >= 18.17.0
|
- [ ] I am using Node.js with a version that satisfies `^18.17.0 || ^20.3.0 || >=21.0.0`
|
||||||
- [ ] I am using Node.js 20 with a version >= 20.3.0
|
- [ ] I am using Deno
|
||||||
- [ ] I am using Node.js 21 or later
|
- [ ] I am using Bun
|
||||||
|
|
||||||
If you cannot confirm any of these, please upgrade to the latest version and try again before opening an issue.
|
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?
|
### Are you using a supported package manager and installing optional dependencies?
|
||||||
|
|
||||||
<!-- Please place an [x] in the relevant box to confirm. -->
|
<!-- Please place an [x] in the relevant box to confirm. -->
|
||||||
|
|
||||||
- [ ] I am using npm >= 9.6.5
|
- [ ] I am using npm >= 9.6.5 with `--include=optional`
|
||||||
- [ ] I am using yarn >= 3.2.0
|
- [ ] I am using yarn >= 3.2.0
|
||||||
- [ ] I am using pnpm >= 7.1.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 and try again before opening an issue.
|
If you cannot confirm any of these, please upgrade to the latest version of your chosen package manager
|
||||||
|
and ensure you are allowing the installation of optional or multi-platform dependencies before opening an issue.
|
||||||
|
|
||||||
|
### What is the complete error message, including the full stack trace?
|
||||||
|
|
||||||
|
<!-- Please provide the error message and stack trace here. -->
|
||||||
|
|
||||||
### What is the complete output of running `npm install --verbose --foreground-scripts sharp` in an empty directory?
|
### What is the complete output of running `npm install --verbose --foreground-scripts sharp` in an empty directory?
|
||||||
|
|
||||||
|
|||||||
16
.github/ISSUE_TEMPLATE/possible-bug.md
vendored
@@ -32,6 +32,22 @@ If you are using another package which depends on a version of `sharp` that is n
|
|||||||
|
|
||||||
<!-- Please provide output of the above command here. -->
|
<!-- Please provide output of the above command here. -->
|
||||||
|
|
||||||
|
### Does this problem relate to file caching?
|
||||||
|
|
||||||
|
The default behaviour of libvips is to cache input files, which can lead to `EBUSY` or `EPERM` errors on Windows.
|
||||||
|
Use [`sharp.cache(false)`](https://sharp.pixelplumbing.com/api-utility#cache) to switch this feature off.
|
||||||
|
|
||||||
|
- [ ] Adding `sharp.cache(false)` does not fix this problem.
|
||||||
|
|
||||||
|
### Does this problem relate to images appearing to have been rotated by 90 degrees?
|
||||||
|
|
||||||
|
Images that contain EXIF Orientation metadata are not auto-oriented. By default, EXIF metadata is removed.
|
||||||
|
|
||||||
|
- To auto-orient pixel values use the parameter-less [`rotate()`](https://sharp.pixelplumbing.com/api-operation#rotate) operation.
|
||||||
|
- To retain EXIF Orientation use [`keepExif()`](https://sharp.pixelplumbing.com/api-output#keepexif).
|
||||||
|
|
||||||
|
- [ ] Using `rotate()` or `keepExif()` does not fix this problem.
|
||||||
|
|
||||||
### What are the steps to reproduce?
|
### What are the steps to reproduce?
|
||||||
|
|
||||||
<!-- Please enter steps to reproduce here. -->
|
<!-- Please enter steps to reproduce here. -->
|
||||||
|
|||||||
149
.github/workflows/ci.yml
vendored
@@ -16,12 +16,14 @@ jobs:
|
|||||||
include:
|
include:
|
||||||
- os: ubuntu-22.04
|
- os: ubuntu-22.04
|
||||||
container: rockylinux:8
|
container: rockylinux:8
|
||||||
|
nodejs_arch: x64
|
||||||
nodejs_version: "^18.17.0"
|
nodejs_version: "^18.17.0"
|
||||||
nodejs_version_major: 18
|
nodejs_version_major: 18
|
||||||
platform: linux-x64
|
platform: linux-x64
|
||||||
prebuild: true
|
prebuild: true
|
||||||
- os: ubuntu-22.04
|
- os: ubuntu-22.04
|
||||||
container: rockylinux:8
|
container: rockylinux:8
|
||||||
|
nodejs_arch: x64
|
||||||
nodejs_version: "^20.3.0"
|
nodejs_version: "^20.3.0"
|
||||||
nodejs_version_major: 20
|
nodejs_version_major: 20
|
||||||
platform: linux-x64
|
platform: linux-x64
|
||||||
@@ -45,9 +47,20 @@ jobs:
|
|||||||
nodejs_version: "^20.3.0"
|
nodejs_version: "^20.3.0"
|
||||||
nodejs_version_major: 20
|
nodejs_version_major: 20
|
||||||
platform: darwin-x64
|
platform: darwin-x64
|
||||||
|
- os: macos-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
|
- os: windows-2019
|
||||||
nodejs_arch: x86
|
nodejs_arch: x86
|
||||||
nodejs_version: "^18.17.0"
|
nodejs_version: "18.18.2" # pinned to avoid 18.19.0 and npm 10
|
||||||
nodejs_version_major: 18
|
nodejs_version_major: 18
|
||||||
platform: win32-ia32
|
platform: win32-ia32
|
||||||
prebuild: true
|
prebuild: true
|
||||||
@@ -68,19 +81,9 @@ jobs:
|
|||||||
nodejs_version_major: 20
|
nodejs_version_major: 20
|
||||||
platform: win32-x64
|
platform: win32-x64
|
||||||
steps:
|
steps:
|
||||||
- name: Dependencies (Linux glibc)
|
|
||||||
if: contains(matrix.container, 'centos')
|
|
||||||
run: |
|
|
||||||
yum install -y https://rpm.nodesource.com/pub_${{ matrix.nodejs_version_major }}.x/nodistro/repo/nodesource-release-nodistro-1.noarch.rpm
|
|
||||||
yum install -y https://packages.endpointdev.com/rhel/7/os/x86_64/endpoint-repo.x86_64.rpm
|
|
||||||
yum install -y centos-release-scl
|
|
||||||
yum install -y devtoolset-11-gcc-c++ make git python3 nodejs fontconfig google-noto-sans-fonts
|
|
||||||
echo "/opt/rh/devtoolset-11/root/usr/bin" >> $GITHUB_PATH
|
|
||||||
- name: Dependencies (Rocky Linux glibc)
|
- name: Dependencies (Rocky Linux glibc)
|
||||||
if: contains(matrix.container, 'rockylinux')
|
if: contains(matrix.container, 'rockylinux')
|
||||||
run: |
|
run: |
|
||||||
dnf install -y https://rpm.nodesource.com/pub_${{ matrix.nodejs_version_major }}.x/nodistro/repo/nodesource-release-nodistro-1.noarch.rpm
|
|
||||||
dnf install -y --setopt=nodesource-nodejs.module_hotfixes=1 nodejs
|
|
||||||
dnf install -y gcc-toolset-11-gcc-c++ make git python3 fontconfig google-noto-sans-fonts
|
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
|
echo "/opt/rh/gcc-toolset-11/root/usr/bin" >> $GITHUB_PATH
|
||||||
- name: Dependencies (Linux musl)
|
- name: Dependencies (Linux musl)
|
||||||
@@ -88,12 +91,12 @@ jobs:
|
|||||||
run: apk add build-base git python3 font-noto --update-cache
|
run: apk add build-base git python3 font-noto --update-cache
|
||||||
- name: Dependencies (Python 3.11 - macOS, Windows)
|
- name: Dependencies (Python 3.11 - macOS, Windows)
|
||||||
if: contains(matrix.os, 'macos') || contains(matrix.os, 'windows')
|
if: contains(matrix.os, 'macos') || contains(matrix.os, 'windows')
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v5
|
||||||
with:
|
with:
|
||||||
python-version: '3.11'
|
python-version: "3.12"
|
||||||
- name: Dependencies (Node.js - macOS, Windows)
|
- name: Dependencies (Node.js)
|
||||||
if: contains(matrix.os, 'macos') || contains(matrix.os, 'windows')
|
if: "!contains(matrix.platform, 'linuxmusl')"
|
||||||
uses: actions/setup-node@v3
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: ${{ matrix.nodejs_version }}
|
node-version: ${{ matrix.nodejs_version }}
|
||||||
architecture: ${{ matrix.nodejs_arch }}
|
architecture: ${{ matrix.nodejs_arch }}
|
||||||
@@ -106,7 +109,7 @@ jobs:
|
|||||||
- name: Test packaging
|
- name: Test packaging
|
||||||
run: |
|
run: |
|
||||||
npm run package-from-local-build
|
npm run package-from-local-build
|
||||||
npm pkg set "optionalDependencies.@sharpen/sharp-${{ matrix.platform }}=file:./npm/${{ matrix.platform }}"
|
npm pkg set "optionalDependencies.@img/sharp-${{ matrix.platform }}=file:./npm/${{ matrix.platform }}"
|
||||||
npm run clean
|
npm run clean
|
||||||
npm install --ignore-scripts
|
npm install --ignore-scripts
|
||||||
npm test
|
npm test
|
||||||
@@ -121,73 +124,85 @@ jobs:
|
|||||||
github-runner-qemu:
|
github-runner-qemu:
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
name: linux-arm - Node.js 18 - prebuild
|
name: ${{ matrix.platform }} - Node.js ${{ matrix.nodejs_version_major }} - prebuild
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-22.04
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: uraimo/run-on-arch-action@v2
|
|
||||||
with:
|
|
||||||
arch: armv6
|
|
||||||
distro: buster
|
|
||||||
env: |
|
|
||||||
nodejs_version: "18.17.0"
|
|
||||||
prebuild_upload: "${{ startsWith(github.ref, 'refs/tags/') && secrets.GITHUB_TOKEN || '' }}"
|
|
||||||
run: |
|
|
||||||
apt-get update
|
|
||||||
apt-get install -y fontconfig fonts-noto-core g++ git libatomic1 make python3 xz-utils
|
|
||||||
mkdir /opt/nodejs
|
|
||||||
curl --silent https://unofficial-builds.nodejs.org/download/release/v${nodejs_version}/node-v${nodejs_version}-linux-armv6l.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
|
|
||||||
npm run package-from-local-build
|
|
||||||
npm pkg set "optionalDependencies.@sharpen/sharp-linux-arm=file:./npm/linux-arm"
|
|
||||||
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
|
|
||||||
macstadium-runner:
|
|
||||||
permissions:
|
|
||||||
contents: write
|
|
||||||
name: ${{ matrix.platform }} - Node.js ${{ matrix.nodejs_version_major }} ${{ matrix.prebuild && '- prebuild' }}
|
|
||||||
runs-on: macos-m1
|
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
- nodejs_arch: x64
|
- platform: linux-arm
|
||||||
nodejs_version: "^18.17.0"
|
distro: buster
|
||||||
|
run_on_arch: armv6
|
||||||
|
nodejs_arch: armv6l
|
||||||
|
nodejs_hostname: unofficial-builds.nodejs.org
|
||||||
|
nodejs_version: "18.17.0"
|
||||||
nodejs_version_major: 18
|
nodejs_version_major: 18
|
||||||
platform: darwin-x64
|
- platform: linux-s390x
|
||||||
- nodejs_arch: arm64
|
distro: bullseye
|
||||||
nodejs_version: "^18.17.0"
|
run_on_arch: s390x
|
||||||
|
nodejs_arch: s390x
|
||||||
|
nodejs_hostname: nodejs.org
|
||||||
|
nodejs_version: "18.17.0"
|
||||||
nodejs_version_major: 18
|
nodejs_version_major: 18
|
||||||
platform: darwin-arm64
|
|
||||||
prebuild: true
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
shell: /usr/bin/arch -arch arm64e /bin/bash -l {0}
|
|
||||||
steps:
|
steps:
|
||||||
- name: Dependencies (Node.js)
|
- uses: actions/checkout@v4
|
||||||
uses: actions/setup-node@v3
|
- uses: uraimo/run-on-arch-action@v2
|
||||||
with:
|
with:
|
||||||
node-version: ${{ matrix.nodejs_version }}
|
arch: ${{ matrix.run_on_arch }}
|
||||||
architecture: ${{ matrix.nodejs_arch }}
|
distro: ${{ matrix.distro }}
|
||||||
|
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
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
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
|
- name: Install
|
||||||
run: npm install --build-from-source
|
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
|
- name: Test
|
||||||
run: npm test
|
run: emmake npm test
|
||||||
- name: Test packaging
|
- name: Test packaging
|
||||||
run: |
|
run: |
|
||||||
npm run package-from-local-build
|
emmake npm run package-from-local-build
|
||||||
npm pkg set "optionalDependencies.@sharpen/sharp-${{ matrix.platform }}=file:./npm/${{ matrix.platform }}"
|
npm pkg set "optionalDependencies.@img/sharp-wasm32=file:./npm/wasm32"
|
||||||
npm run clean
|
npm run clean
|
||||||
npm install --ignore-scripts
|
rm -rf node_modules/@img/sharp-linux-x64
|
||||||
|
npm install --cpu=wasm32
|
||||||
npm test
|
npm test
|
||||||
- name: Prebuild
|
- name: Prebuild
|
||||||
if: matrix.prebuild && startsWith(github.ref, 'refs/tags/')
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
env:
|
env:
|
||||||
|
npm_config_nodedir: emscripten
|
||||||
prebuild_upload: ${{ secrets.GITHUB_TOKEN }}
|
prebuild_upload: ${{ secrets.GITHUB_TOKEN }}
|
||||||
run: cd src && ln -s ../package.json && npx prebuild
|
run: cd src && ln -s ../package.json && emmake npx prebuild --platform=emscripten --arch=wasm32 --strip=0
|
||||||
|
|||||||
118
.github/workflows/npm.yml
vendored
@@ -9,33 +9,96 @@ permissions: {}
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
release-smoke-test:
|
release-smoke-test:
|
||||||
name: "${{ github.ref }} ${{ matrix.name }}"
|
name: "${{ github.ref_name }} ${{ matrix.name }}"
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.runs-on }}
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
- name: linux-x64
|
- name: linux-x64-node-npm
|
||||||
os: ubuntu-22.04
|
runs-on: ubuntu-22.04
|
||||||
- name: darwin-x64
|
runtime: node
|
||||||
os: macos-11
|
package-manager: npm
|
||||||
- name: win32-x64
|
- name: linux-x64-node-pnpm
|
||||||
os: windows-2019
|
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:
|
steps:
|
||||||
- name: Install Node.js
|
- name: Install Node.js
|
||||||
uses: actions/setup-node@v3
|
if: ${{ matrix.runtime == 'node' }}
|
||||||
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 20
|
node-version: 20
|
||||||
- name: Install pnpm
|
- name: Install pnpm
|
||||||
|
if: ${{ matrix.package-manager == 'pnpm' }}
|
||||||
uses: pnpm/action-setup@v2
|
uses: pnpm/action-setup@v2
|
||||||
with:
|
with:
|
||||||
version: 8
|
version: 8
|
||||||
- name: Install Deno
|
- name: Install Deno
|
||||||
|
if: ${{ matrix.runtime == 'deno' }}
|
||||||
uses: denoland/setup-deno@v1
|
uses: denoland/setup-deno@v1
|
||||||
with:
|
with:
|
||||||
deno-version: v1.x
|
deno-version: v1.x
|
||||||
- name: Install Bun
|
- name: Install Bun
|
||||||
if: ${{ !contains(matrix.os, 'windows') }}
|
if: ${{ matrix.runtime == 'bun' }}
|
||||||
uses: oven-sh/setup-bun@v1
|
uses: oven-sh/setup-bun@v1
|
||||||
with:
|
with:
|
||||||
bun-version: latest
|
bun-version: latest
|
||||||
@@ -47,54 +110,65 @@ jobs:
|
|||||||
script: |
|
script: |
|
||||||
core.setOutput('semver', context.ref.replace('refs/tags/v',''))
|
core.setOutput('semver', context.ref.replace('refs/tags/v',''))
|
||||||
- name: Create package.json
|
- name: Create package.json
|
||||||
uses: DamianReeves/write-file-action@v1.2
|
uses: DamianReeves/write-file-action@v1.3
|
||||||
with:
|
with:
|
||||||
path: package.json
|
path: package.json
|
||||||
contents: |
|
contents: |
|
||||||
{
|
{
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"sharp": "${{ steps.version.outputs.semver }}"
|
"sharp": "${{ steps.version.outputs.semver }}"
|
||||||
}
|
},
|
||||||
|
"type": "module"
|
||||||
}
|
}
|
||||||
- name: Create release.mjs
|
- name: Create release.mjs
|
||||||
uses: DamianReeves/write-file-action@v1.2
|
uses: DamianReeves/write-file-action@v1.3
|
||||||
with:
|
with:
|
||||||
path: release.mjs
|
path: release.mjs
|
||||||
contents: |
|
contents: |
|
||||||
import { createRequire } from 'node:module';
|
|
||||||
import { deepStrictEqual } from 'node:assert';
|
import { deepStrictEqual } from 'node:assert';
|
||||||
const require = createRequire(import.meta.url);
|
import sharp from 'sharp';
|
||||||
const sharp = require('sharp');
|
deepStrictEqual(['.jpg', '.jpeg', '.jpe', '.jfif'], sharp.format.jpeg.input.fileSuffix);
|
||||||
deepStrictEqual(['.jpg', '.jpeg', '.jpe'], sharp.format.jpeg.input.fileSuffix);
|
|
||||||
|
|
||||||
- name: Run with Node.js + npm
|
- name: Run with Node.js + npm
|
||||||
|
if: ${{ matrix.package-manager == 'npm' }}
|
||||||
run: |
|
run: |
|
||||||
npm install --ignore-scripts
|
npm install --ignore-scripts
|
||||||
node release.mjs
|
node release.mjs
|
||||||
rm -r node_modules/ package-lock.json
|
|
||||||
|
|
||||||
- name: Run with Node.js + pnpm
|
- name: Run with Node.js + pnpm
|
||||||
|
if: ${{ matrix.package-manager == 'pnpm' }}
|
||||||
run: |
|
run: |
|
||||||
pnpm install --ignore-scripts
|
pnpm install --ignore-scripts
|
||||||
node release.mjs
|
node release.mjs
|
||||||
rm -r node_modules/ pnpm-lock.yaml
|
|
||||||
|
|
||||||
- name: Run with Node.js + yarn
|
- name: Run with Node.js + yarn
|
||||||
|
if: ${{ matrix.package-manager == 'yarn' }}
|
||||||
run: |
|
run: |
|
||||||
corepack enable
|
corepack enable
|
||||||
yarn set version stable
|
yarn set version stable
|
||||||
|
yarn config set enableImmutableInstalls false
|
||||||
yarn config set enableScripts false
|
yarn config set enableScripts false
|
||||||
yarn config set nodeLinker node-modules
|
yarn config set nodeLinker node-modules
|
||||||
yarn install
|
yarn install
|
||||||
node release.mjs
|
node release.mjs
|
||||||
rm -r node_modules/ .yarn/ yarn.lock .yarnrc.yml
|
|
||||||
corepack disable
|
- 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
|
- name: Run with Deno
|
||||||
|
if: ${{ matrix.runtime == 'deno' }}
|
||||||
run: deno run --allow-read --allow-ffi release.mjs
|
run: deno run --allow-read --allow-ffi release.mjs
|
||||||
|
|
||||||
- name: Run with Bun
|
- name: Run with Bun
|
||||||
if: ${{ !contains(matrix.os, 'windows') }}
|
if: ${{ matrix.runtime == 'bun' }}
|
||||||
run: |
|
run: |
|
||||||
bun install --ignore-scripts
|
bun install --ignore-scripts
|
||||||
bun release.mjs
|
bun release.mjs
|
||||||
|
|||||||
5
.gitignore
vendored
@@ -8,11 +8,6 @@ test/bench/node_modules
|
|||||||
test/fixtures/output*
|
test/fixtures/output*
|
||||||
test/fixtures/vips-properties.xml
|
test/fixtures/vips-properties.xml
|
||||||
test/leak/libvips.supp
|
test/leak/libvips.supp
|
||||||
test/saliency/report.json
|
|
||||||
test/saliency/Image*
|
|
||||||
test/saliency/[Uu]serData*
|
|
||||||
!test/saliency/userData.js
|
|
||||||
.gitattributes
|
|
||||||
.DS_Store
|
.DS_Store
|
||||||
.nyc_output
|
.nyc_output
|
||||||
.vscode/
|
.vscode/
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"runtime": "napi",
|
"runtime": "napi",
|
||||||
"include-regex": "(sharp-.+\\.node|libvips-.+\\.dll|libglib-.+\\.dll|libgobject-.+\\.dll)",
|
"include-regex": "(sharp-.+\\.node|libvips-.+\\.dll)",
|
||||||
"prerelease": true,
|
"prerelease": true,
|
||||||
"strip": true
|
"strip": true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,14 @@
|
|||||||
|
|
||||||
<img src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right">
|
<img src="https://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
|
is to convert large images in common formats to
|
||||||
smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions.
|
smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions.
|
||||||
|
|
||||||
|
It can be used with all JavaScript runtimes
|
||||||
|
that provide support for Node-API v9, including
|
||||||
|
Node.js (^18.17.0 or >= 20.3.0), Deno and Bun.
|
||||||
|
|
||||||
Resizing an image is typically 4x-5x faster than using the
|
Resizing an image is typically 4x-5x faster than using the
|
||||||
quickest ImageMagick and GraphicsMagick settings
|
quickest ImageMagick and GraphicsMagick settings
|
||||||
due to its use of [libvips](https://github.com/libvips/libvips).
|
due to its use of [libvips](https://github.com/libvips/libvips).
|
||||||
@@ -16,7 +20,7 @@ Lanczos resampling ensures quality is not sacrificed for speed.
|
|||||||
As well as image resizing, operations such as
|
As well as image resizing, operations such as
|
||||||
rotation, extraction, compositing and gamma correction are available.
|
rotation, extraction, compositing and gamma correction are available.
|
||||||
|
|
||||||
Most modern macOS, Windows and Linux systems running Node.js >= 18.17.0
|
Most modern macOS, Windows and Linux systems
|
||||||
do not require any additional install or runtime dependencies.
|
do not require any additional install or runtime dependencies.
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|||||||
@@ -2,10 +2,14 @@
|
|||||||
|
|
||||||
<img src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right">
|
<img src="https://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
|
is to convert large images in common formats to
|
||||||
smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions.
|
smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions.
|
||||||
|
|
||||||
|
It can be used with all JavaScript runtimes
|
||||||
|
that provide support for Node-API v9, including
|
||||||
|
Node.js >= 18.17.0, Deno and Bun.
|
||||||
|
|
||||||
Resizing an image is typically 4x-5x faster than using the
|
Resizing an image is typically 4x-5x faster than using the
|
||||||
quickest ImageMagick and GraphicsMagick settings
|
quickest ImageMagick and GraphicsMagick settings
|
||||||
due to its use of [libvips](https://github.com/libvips/libvips).
|
due to its use of [libvips](https://github.com/libvips/libvips).
|
||||||
@@ -16,7 +20,7 @@ Lanczos resampling ensures quality is not sacrificed for speed.
|
|||||||
As well as image resizing, operations such as
|
As well as image resizing, operations such as
|
||||||
rotation, extraction, compositing and gamma correction are available.
|
rotation, extraction, compositing and gamma correction are available.
|
||||||
|
|
||||||
Most modern macOS, Windows and Linux systems running Node.js >= 14.15.0
|
Most modern macOS, Windows and Linux systems
|
||||||
do not require any additional install or runtime dependencies.
|
do not require any additional install or runtime dependencies.
|
||||||
|
|
||||||
### Formats
|
### Formats
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
## tint
|
## tint
|
||||||
> tint(rgb) ⇒ <code>Sharp</code>
|
> 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.
|
An alpha channel may be present and will be unchanged by the operation.
|
||||||
|
|
||||||
|
|
||||||
@@ -12,7 +12,7 @@ An alpha channel may be present and will be unchanged by the operation.
|
|||||||
|
|
||||||
| Param | Type | Description |
|
| Param | Type | Description |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| rgb | <code>string</code> \| <code>Object</code> | parsed by the [color](https://www.npmjs.org/package/color) module to extract chroma values. |
|
| tint | <code>string</code> \| <code>Object</code> | Parsed by the [color](https://www.npmjs.org/package/color) module. |
|
||||||
|
|
||||||
**Example**
|
**Example**
|
||||||
```js
|
```js
|
||||||
@@ -66,8 +66,6 @@ The input image will be converted to the provided colourspace at the start of th
|
|||||||
All operations will use this colourspace before converting to the output colourspace,
|
All operations will use this colourspace before converting to the output colourspace,
|
||||||
as defined by [toColourspace](#tocolourspace).
|
as defined by [toColourspace](#tocolourspace).
|
||||||
|
|
||||||
This feature is experimental and has not yet been fully-tested with all operations.
|
|
||||||
|
|
||||||
|
|
||||||
**Throws**:
|
**Throws**:
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,10 @@ Non-critical problems encountered during processing are emitted as `warning` eve
|
|||||||
|
|
||||||
Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.
|
Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.
|
||||||
|
|
||||||
|
When loading more than one page/frame of an animated image,
|
||||||
|
these are combined as a vertically-stacked "toilet roll" image
|
||||||
|
where the overall height is the `pageHeight` multiplied by the number of `pages`.
|
||||||
|
|
||||||
**Throws**:
|
**Throws**:
|
||||||
|
|
||||||
- <code>Error</code> Invalid parameters
|
- <code>Error</code> Invalid parameters
|
||||||
@@ -26,7 +30,7 @@ Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_st
|
|||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| [input] | <code>Buffer</code> \| <code>ArrayBuffer</code> \| <code>Uint8Array</code> \| <code>Uint8ClampedArray</code> \| <code>Int8Array</code> \| <code>Uint16Array</code> \| <code>Int16Array</code> \| <code>Uint32Array</code> \| <code>Int32Array</code> \| <code>Float32Array</code> \| <code>Float64Array</code> \| <code>string</code> | | if present, can be a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or a TypedArray containing raw pixel image data, or a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. |
|
| [input] | <code>Buffer</code> \| <code>ArrayBuffer</code> \| <code>Uint8Array</code> \| <code>Uint8ClampedArray</code> \| <code>Int8Array</code> \| <code>Uint16Array</code> \| <code>Int16Array</code> \| <code>Uint32Array</code> \| <code>Int32Array</code> \| <code>Float32Array</code> \| <code>Float64Array</code> \| <code>string</code> | | 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] | <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): 'none' (least), 'truncated', 'error' or 'warning' (most), higher levels imply lower levels, invalid metadata will always abort. |
|
| [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.limitInputPixels] | <code>number</code> \| <code>boolean</code> | <code>268402689</code> | Do not process input images where the number of pixels (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted. An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). |
|
||||||
| [options.unlimited] | <code>boolean</code> | <code>false</code> | Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). |
|
| [options.unlimited] | <code>boolean</code> | <code>false</code> | Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). |
|
||||||
| [options.sequentialRead] | <code>boolean</code> | <code>true</code> | Set this to `false` to use random access rather than sequential read. Some operations will do this automatically. |
|
| [options.sequentialRead] | <code>boolean</code> | <code>true</code> | Set this to `false` to use random access rather than sequential read. Some operations will do this automatically. |
|
||||||
@@ -62,7 +66,7 @@ Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_st
|
|||||||
| [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.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.rgba] | <code>boolean</code> | <code>false</code> | set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`. |
|
||||||
| [options.text.spacing] | <code>number</code> | <code>0</code> | text line height in points. Will use the font line height if none is specified. |
|
| [options.text.spacing] | <code>number</code> | <code>0</code> | text line height in points. Will use the font line height if none is specified. |
|
||||||
| [options.text.wrap] | <code>string</code> | <code>"'word'"</code> | word wrapping style when width is provided, one of: 'word', 'char', 'charWord' (prefer char, fallback to word) or 'none'. |
|
| [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**
|
**Example**
|
||||||
```js
|
```js
|
||||||
@@ -75,14 +79,16 @@ sharp('input.jpg')
|
|||||||
```
|
```
|
||||||
**Example**
|
**Example**
|
||||||
```js
|
```js
|
||||||
// Read image data from readableStream,
|
// Read image data from remote URL,
|
||||||
// resize to 300 pixels wide,
|
// resize to 300 pixels wide,
|
||||||
// emit an 'info' event with calculated dimensions
|
// emit an 'info' event with calculated dimensions
|
||||||
// and finally write image data to writableStream
|
// and finally write image data to writableStream
|
||||||
var transformer = sharp()
|
const { body } = fetch('https://...');
|
||||||
|
const readableStream = Readable.fromWeb(body);
|
||||||
|
const transformer = sharp()
|
||||||
.resize(300)
|
.resize(300)
|
||||||
.on('info', function(info) {
|
.on('info', ({ height }) => {
|
||||||
console.log('Image height is ' + info.height);
|
console.log(`Image height is ${height}`);
|
||||||
});
|
});
|
||||||
readableStream.pipe(transformer).pipe(writableStream);
|
readableStream.pipe(transformer).pipe(writableStream);
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ The use of `rotate` without an angle will remove the EXIF `Orientation` tag, if
|
|||||||
Only one rotation can occur per pipeline.
|
Only one rotation can occur per pipeline.
|
||||||
Previous calls to `rotate` in the same pipeline will be ignored.
|
Previous calls to `rotate` in the same pipeline will be ignored.
|
||||||
|
|
||||||
|
Multi-page images can only be rotated by 180 degrees.
|
||||||
|
|
||||||
Method order is important when rotating, resizing and/or extracting regions,
|
Method order is important when rotating, resizing and/or extracting regions,
|
||||||
for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.
|
for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.
|
||||||
|
|
||||||
|
|||||||
@@ -111,17 +111,157 @@ await sharp(pixelArray, { raw: { width, height, channels } })
|
|||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## keepExif
|
||||||
|
> keepExif() ⇒ <code>Sharp</code>
|
||||||
|
|
||||||
|
Keep all EXIF metadata from the input image in the output image.
|
||||||
|
|
||||||
|
EXIF metadata is unsupported for TIFF output.
|
||||||
|
|
||||||
|
|
||||||
|
**Since**: 0.33.0
|
||||||
|
**Example**
|
||||||
|
```js
|
||||||
|
const outputWithExif = await sharp(inputWithExif)
|
||||||
|
.keepExif()
|
||||||
|
.toBuffer();
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## withExif
|
||||||
|
> withExif(exif) ⇒ <code>Sharp</code>
|
||||||
|
|
||||||
|
Set EXIF metadata in the output image, ignoring any EXIF in the input image.
|
||||||
|
|
||||||
|
|
||||||
|
**Throws**:
|
||||||
|
|
||||||
|
- <code>Error</code> Invalid parameters
|
||||||
|
|
||||||
|
**Since**: 0.33.0
|
||||||
|
|
||||||
|
| Param | Type | Description |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| exif | <code>Object.<string, Object.<string, string>></code> | Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. |
|
||||||
|
|
||||||
|
**Example**
|
||||||
|
```js
|
||||||
|
const dataWithExif = await sharp(input)
|
||||||
|
.withExif({
|
||||||
|
IFD0: {
|
||||||
|
Copyright: 'The National Gallery'
|
||||||
|
},
|
||||||
|
IFD3: {
|
||||||
|
GPSLatitudeRef: 'N',
|
||||||
|
GPSLatitude: '51/1 30/1 3230/100',
|
||||||
|
GPSLongitudeRef: 'W',
|
||||||
|
GPSLongitude: '0/1 7/1 4366/100'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.toBuffer();
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## withExifMerge
|
||||||
|
> withExifMerge(exif) ⇒ <code>Sharp</code>
|
||||||
|
|
||||||
|
Update EXIF metadata from the input image in the output image.
|
||||||
|
|
||||||
|
|
||||||
|
**Throws**:
|
||||||
|
|
||||||
|
- <code>Error</code> Invalid parameters
|
||||||
|
|
||||||
|
**Since**: 0.33.0
|
||||||
|
|
||||||
|
| Param | Type | Description |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| exif | <code>Object.<string, Object.<string, string>></code> | Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. |
|
||||||
|
|
||||||
|
**Example**
|
||||||
|
```js
|
||||||
|
const dataWithMergedExif = await sharp(inputWithExif)
|
||||||
|
.withExifMerge({
|
||||||
|
IFD0: {
|
||||||
|
Copyright: 'The National Gallery'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.toBuffer();
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## keepIccProfile
|
||||||
|
> keepIccProfile() ⇒ <code>Sharp</code>
|
||||||
|
|
||||||
|
Keep ICC profile from the input image in the output image.
|
||||||
|
|
||||||
|
Where necessary, will attempt to convert the output colour space to match the profile.
|
||||||
|
|
||||||
|
|
||||||
|
**Since**: 0.33.0
|
||||||
|
**Example**
|
||||||
|
```js
|
||||||
|
const outputWithIccProfile = await sharp(inputWithIccProfile)
|
||||||
|
.keepIccProfile()
|
||||||
|
.toBuffer();
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## withIccProfile
|
||||||
|
> withIccProfile(icc, [options]) ⇒ <code>Sharp</code>
|
||||||
|
|
||||||
|
Transform using an ICC profile and attach to the output image.
|
||||||
|
|
||||||
|
This can either be an absolute filesystem path or
|
||||||
|
built-in profile name (`srgb`, `p3`, `cmyk`).
|
||||||
|
|
||||||
|
|
||||||
|
**Throws**:
|
||||||
|
|
||||||
|
- <code>Error</code> Invalid parameters
|
||||||
|
|
||||||
|
**Since**: 0.33.0
|
||||||
|
|
||||||
|
| Param | Type | Default | Description |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| icc | <code>string</code> | | Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk). |
|
||||||
|
| [options] | <code>Object</code> | | |
|
||||||
|
| [options.attach] | <code>number</code> | <code>true</code> | Should the ICC profile be included in the output image metadata? |
|
||||||
|
|
||||||
|
**Example**
|
||||||
|
```js
|
||||||
|
const outputWithP3 = await sharp(input)
|
||||||
|
.withIccProfile('p3')
|
||||||
|
.toBuffer();
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## keepMetadata
|
||||||
|
> keepMetadata() ⇒ <code>Sharp</code>
|
||||||
|
|
||||||
|
Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image.
|
||||||
|
|
||||||
|
The default behaviour, when `keepMetadata` is not used, is to convert to the device-independent
|
||||||
|
sRGB colour space and strip all metadata, including the removal of any ICC profile.
|
||||||
|
|
||||||
|
|
||||||
|
**Since**: 0.33.0
|
||||||
|
**Example**
|
||||||
|
```js
|
||||||
|
const outputWithMetadata = await sharp(inputWithMetadata)
|
||||||
|
.keepMetadata()
|
||||||
|
.toBuffer();
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
## withMetadata
|
## withMetadata
|
||||||
> withMetadata([options]) ⇒ <code>Sharp</code>
|
> withMetadata([options]) ⇒ <code>Sharp</code>
|
||||||
|
|
||||||
Include all metadata (EXIF, XMP, IPTC) from the input image in the output image.
|
Keep most metadata (EXIF, XMP, IPTC) from the input image in the output image.
|
||||||
This will also convert to and add a web-friendly sRGB ICC profile if appropriate,
|
|
||||||
unless a custom output profile is provided.
|
|
||||||
|
|
||||||
The default behaviour, when `withMetadata` is not used, is to convert to the device-independent
|
This will also convert to and add a web-friendly sRGB ICC profile if appropriate.
|
||||||
sRGB colour space and strip all metadata, including the removal of any ICC profile.
|
|
||||||
|
|
||||||
EXIF metadata is unsupported for TIFF output.
|
Allows orientation and density to be set or updated.
|
||||||
|
|
||||||
|
|
||||||
**Throws**:
|
**Throws**:
|
||||||
@@ -129,38 +269,16 @@ EXIF metadata is unsupported for TIFF output.
|
|||||||
- <code>Error</code> Invalid parameters
|
- <code>Error</code> Invalid parameters
|
||||||
|
|
||||||
|
|
||||||
| Param | Type | Default | Description |
|
| Param | Type | Description |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| [options] | <code>Object</code> | | |
|
| [options] | <code>Object</code> | |
|
||||||
| [options.orientation] | <code>number</code> | | value between 1 and 8, used to update the EXIF `Orientation` tag. |
|
| [options.orientation] | <code>number</code> | Used to update the EXIF `Orientation` tag, integer between 1 and 8. |
|
||||||
| [options.icc] | <code>string</code> | <code>"'srgb'"</code> | Filesystem path to output ICC profile, relative to `process.cwd()`, defaults to built-in sRGB. |
|
| [options.density] | <code>number</code> | Number of pixels per inch (DPI). |
|
||||||
| [options.exif] | <code>Object.<Object></code> | <code>{}</code> | Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. |
|
|
||||||
| [options.density] | <code>number</code> | | Number of pixels per inch (DPI). |
|
|
||||||
|
|
||||||
**Example**
|
**Example**
|
||||||
```js
|
```js
|
||||||
sharp('input.jpg')
|
const outputSrgbWithMetadata = await sharp(inputRgbWithMetadata)
|
||||||
.withMetadata()
|
.withMetadata()
|
||||||
.toFile('output-with-metadata.jpg')
|
|
||||||
.then(info => { ... });
|
|
||||||
```
|
|
||||||
**Example**
|
|
||||||
```js
|
|
||||||
// Set output EXIF metadata
|
|
||||||
const data = await sharp(input)
|
|
||||||
.withMetadata({
|
|
||||||
exif: {
|
|
||||||
IFD0: {
|
|
||||||
Copyright: 'The National Gallery'
|
|
||||||
},
|
|
||||||
IFD3: {
|
|
||||||
GPSLatitudeRef: 'N',
|
|
||||||
GPSLatitude: '51/1 30/1 3230/100',
|
|
||||||
GPSLongitudeRef: 'W',
|
|
||||||
GPSLongitude: '0/1 7/1 4366/100'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.toBuffer();
|
.toBuffer();
|
||||||
```
|
```
|
||||||
**Example**
|
**Example**
|
||||||
@@ -249,10 +367,14 @@ const data = await sharp(input)
|
|||||||
|
|
||||||
Use these PNG options for output image.
|
Use these PNG options for output image.
|
||||||
|
|
||||||
By default, PNG output is full colour at 8 or 16 bits per pixel.
|
By default, PNG output is full colour at 8 bits per pixel.
|
||||||
|
|
||||||
Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel.
|
Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel.
|
||||||
Set `palette` to `true` for slower, indexed PNG output.
|
Set `palette` to `true` for slower, indexed PNG output.
|
||||||
|
|
||||||
|
For 16 bits per pixel output, convert to `rgb16` via
|
||||||
|
[toColourspace](/api-colour#tocolourspace).
|
||||||
|
|
||||||
|
|
||||||
**Throws**:
|
**Throws**:
|
||||||
|
|
||||||
@@ -287,6 +409,14 @@ const data = await sharp(input)
|
|||||||
.png({ palette: true })
|
.png({ palette: true })
|
||||||
.toBuffer();
|
.toBuffer();
|
||||||
```
|
```
|
||||||
|
**Example**
|
||||||
|
```js
|
||||||
|
// Output 16 bits per pixel RGB(A)
|
||||||
|
const data = await sharp(input)
|
||||||
|
.toColourspace('rgb16')
|
||||||
|
.png()
|
||||||
|
.toBuffer();
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
## webp
|
## webp
|
||||||
@@ -466,6 +596,7 @@ instead of providing `xres` and `yres` in pixels/mm.
|
|||||||
| [options.yres] | <code>number</code> | <code>1.0</code> | vertical resolution in pixels/mm |
|
| [options.yres] | <code>number</code> | <code>1.0</code> | vertical resolution in pixels/mm |
|
||||||
| [options.resolutionUnit] | <code>string</code> | <code>"'inch'"</code> | resolution unit options: inch, cm |
|
| [options.resolutionUnit] | <code>string</code> | <code>"'inch'"</code> | resolution unit options: inch, cm |
|
||||||
| [options.bitdepth] | <code>number</code> | <code>8</code> | reduce bitdepth to 1, 2 or 4 bit |
|
| [options.bitdepth] | <code>number</code> | <code>8</code> | reduce bitdepth to 1, 2 or 4 bit |
|
||||||
|
| [options.miniswhite] | <code>boolean</code> | <code>false</code> | write 1-bit images as miniswhite |
|
||||||
|
|
||||||
**Example**
|
**Example**
|
||||||
```js
|
```js
|
||||||
@@ -486,6 +617,7 @@ sharp('input.svg')
|
|||||||
Use these AVIF options for output image.
|
Use these AVIF options for output image.
|
||||||
|
|
||||||
AVIF image sequences are not supported.
|
AVIF image sequences are not supported.
|
||||||
|
Prebuilt binaries support a bitdepth of 8 only.
|
||||||
|
|
||||||
|
|
||||||
**Throws**:
|
**Throws**:
|
||||||
@@ -501,6 +633,7 @@ AVIF image sequences are not supported.
|
|||||||
| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression |
|
| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression |
|
||||||
| [options.effort] | <code>number</code> | <code>4</code> | CPU effort, between 0 (fastest) and 9 (slowest) |
|
| [options.effort] | <code>number</code> | <code>4</code> | CPU effort, between 0 (fastest) and 9 (slowest) |
|
||||||
| [options.chromaSubsampling] | <code>string</code> | <code>"'4:4:4'"</code> | set to '4:2:0' to use chroma subsampling |
|
| [options.chromaSubsampling] | <code>string</code> | <code>"'4:4:4'"</code> | set to '4:2:0' to use chroma subsampling |
|
||||||
|
| [options.bitdepth] | <code>number</code> | <code>8</code> | set bitdepth to 8, 10 or 12 bit |
|
||||||
|
|
||||||
**Example**
|
**Example**
|
||||||
```js
|
```js
|
||||||
@@ -539,6 +672,7 @@ globally-installed libvips compiled with support for libheif, libde265 and x265.
|
|||||||
| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression |
|
| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression |
|
||||||
| [options.effort] | <code>number</code> | <code>4</code> | CPU effort, between 0 (fastest) and 9 (slowest) |
|
| [options.effort] | <code>number</code> | <code>4</code> | CPU effort, between 0 (fastest) and 9 (slowest) |
|
||||||
| [options.chromaSubsampling] | <code>string</code> | <code>"'4:4:4'"</code> | set to '4:2:0' to use chroma subsampling |
|
| [options.chromaSubsampling] | <code>string</code> | <code>"'4:4:4'"</code> | set to '4:2:0' to use chroma subsampling |
|
||||||
|
| [options.bitdepth] | <code>number</code> | <code>8</code> | set bitdepth to 8, 10 or 12 bit |
|
||||||
|
|
||||||
**Example**
|
**Example**
|
||||||
```js
|
```js
|
||||||
@@ -644,7 +778,7 @@ The prebuilt binaries do not include this - see
|
|||||||
| [options.angle] | <code>number</code> | <code>0</code> | tile angle of rotation, must be a multiple of 90. |
|
| [options.angle] | <code>number</code> | <code>0</code> | tile angle of rotation, must be a multiple of 90. |
|
||||||
| [options.background] | <code>string</code> \| <code>Object</code> | <code>"{r: 255, g: 255, b: 255, alpha: 1}"</code> | background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to white without transparency. |
|
| [options.background] | <code>string</code> \| <code>Object</code> | <code>"{r: 255, g: 255, b: 255, alpha: 1}"</code> | background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to white without transparency. |
|
||||||
| [options.depth] | <code>string</code> | | how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout. |
|
| [options.depth] | <code>string</code> | | how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout. |
|
||||||
| [options.skipBlanks] | <code>number</code> | <code>-1</code> | threshold to skip tile generation, a value 0 - 255 for 8-bit images or 0 - 65535 for 16-bit images |
|
| [options.skipBlanks] | <code>number</code> | <code>-1</code> | Threshold to skip tile generation. Range is 0-255 for 8-bit images, 0-65535 for 16-bit images. Default is 5 for `google` layout, -1 (no skip) otherwise. |
|
||||||
| [options.container] | <code>string</code> | <code>"'fs'"</code> | tile container, with value `fs` (filesystem) or `zip` (compressed file). |
|
| [options.container] | <code>string</code> | <code>"'fs'"</code> | tile container, with value `fs` (filesystem) or `zip` (compressed file). |
|
||||||
| [options.layout] | <code>string</code> | <code>"'dz'"</code> | filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`. |
|
| [options.layout] | <code>string</code> | <code>"'dz'"</code> | filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`. |
|
||||||
| [options.centre] | <code>boolean</code> | <code>false</code> | centre image in tile. |
|
| [options.centre] | <code>boolean</code> | <code>false</code> | centre image in tile. |
|
||||||
|
|||||||
@@ -21,18 +21,22 @@ When using a **fit** of `cover` or `contain`, the default **position** is `centr
|
|||||||
|
|
||||||
Some of these values are based on the [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS property.
|
Some of these values are based on the [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS property.
|
||||||
|
|
||||||
The experimental strategy-based approach resizes so one dimension is at its target length
|
The strategy-based approach initially resizes so one dimension is at its target length
|
||||||
then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.
|
then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.
|
||||||
- `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29).
|
- `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29).
|
||||||
- `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
|
- `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
|
||||||
|
|
||||||
Possible interpolation kernels are:
|
Possible downsizing kernels are:
|
||||||
- `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation).
|
- `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation).
|
||||||
|
- `linear`: Use a [triangle filter](https://en.wikipedia.org/wiki/Triangular_function).
|
||||||
- `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline).
|
- `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline).
|
||||||
- `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf).
|
- `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf).
|
||||||
- `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`.
|
- `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`.
|
||||||
- `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
|
- `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
|
||||||
|
|
||||||
|
When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators.
|
||||||
|
Downsampling kernels without a matching upsampling interpolator map to `cubic`.
|
||||||
|
|
||||||
Only one resize can occur per pipeline.
|
Only one resize can occur per pipeline.
|
||||||
Previous calls to `resize` in the same pipeline will be ignored.
|
Previous calls to `resize` in the same pipeline will be ignored.
|
||||||
|
|
||||||
@@ -52,7 +56,7 @@ Previous calls to `resize` in the same pipeline will be ignored.
|
|||||||
| [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.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.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.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.kernel] | <code>String</code> | <code>'lanczos3'</code> | The kernel to use for image reduction and the inferred interpolator to use for upsampling. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load. |
|
||||||
| [options.withoutEnlargement] | <code>Boolean</code> | <code>false</code> | Do not scale up if the width *or* height are already less than the target dimensions, equivalent to GraphicsMagick's `>` geometry option. This may result in output dimensions smaller than the target dimensions. |
|
| [options.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.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. |
|
| [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. |
|
||||||
@@ -251,7 +255,7 @@ sharp(input)
|
|||||||
|
|
||||||
|
|
||||||
## trim
|
## trim
|
||||||
> trim(trim) ⇒ <code>Sharp</code>
|
> trim([options]) ⇒ <code>Sharp</code>
|
||||||
|
|
||||||
Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.
|
Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.
|
||||||
|
|
||||||
@@ -259,8 +263,7 @@ Images with an alpha channel will use the combined bounding box of alpha and non
|
|||||||
|
|
||||||
If the result of this operation would trim an image to nothing then no change is made.
|
If the result of this operation would trim an image to nothing then no change is made.
|
||||||
|
|
||||||
The `info` response Object, obtained from callback of `.toFile()` or `.toBuffer()`,
|
The `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` properties.
|
||||||
will contain `trimOffsetLeft` and `trimOffsetTop` properties.
|
|
||||||
|
|
||||||
|
|
||||||
**Throws**:
|
**Throws**:
|
||||||
@@ -270,46 +273,44 @@ will contain `trimOffsetLeft` and `trimOffsetTop` properties.
|
|||||||
|
|
||||||
| Param | Type | Default | Description |
|
| Param | Type | Default | Description |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| trim | <code>string</code> \| <code>number</code> \| <code>Object</code> | | the specific background colour to trim, the threshold for doing so or an Object with both. |
|
| [options] | <code>Object</code> | | |
|
||||||
| [trim.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.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. |
|
||||||
| [trim.threshold] | <code>number</code> | <code>10</code> | the allowed difference from the above colour, a positive number. |
|
| [options.threshold] | <code>number</code> | <code>10</code> | Allowed difference from the above colour, a positive number. |
|
||||||
|
| [options.lineArt] | <code>boolean</code> | <code>false</code> | Does the input more closely resemble line art (e.g. vector) rather than being photographic? |
|
||||||
|
|
||||||
**Example**
|
**Example**
|
||||||
```js
|
```js
|
||||||
// Trim pixels with a colour similar to that of the top-left pixel.
|
// Trim pixels with a colour similar to that of the top-left pixel.
|
||||||
sharp(input)
|
await sharp(input)
|
||||||
.trim()
|
.trim()
|
||||||
.toFile(output, function(err, info) {
|
.toFile(output);
|
||||||
...
|
|
||||||
});
|
|
||||||
```
|
```
|
||||||
**Example**
|
**Example**
|
||||||
```js
|
```js
|
||||||
// Trim pixels with the exact same colour as that of the top-left pixel.
|
// Trim pixels with the exact same colour as that of the top-left pixel.
|
||||||
sharp(input)
|
await sharp(input)
|
||||||
.trim(0)
|
.trim({
|
||||||
.toFile(output, function(err, info) {
|
threshold: 0
|
||||||
...
|
})
|
||||||
});
|
.toFile(output);
|
||||||
```
|
```
|
||||||
**Example**
|
**Example**
|
||||||
```js
|
```js
|
||||||
// Trim only pixels with a similar colour to red.
|
// Assume input is line art and trim only pixels with a similar colour to red.
|
||||||
sharp(input)
|
const output = await sharp(input)
|
||||||
.trim("#FF0000")
|
.trim({
|
||||||
.toFile(output, function(err, info) {
|
background: "#FF0000",
|
||||||
...
|
lineArt: true
|
||||||
});
|
})
|
||||||
|
.toBuffer();
|
||||||
```
|
```
|
||||||
**Example**
|
**Example**
|
||||||
```js
|
```js
|
||||||
// Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
|
// Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
|
||||||
sharp(input)
|
const output = await sharp(input)
|
||||||
.trim({
|
.trim({
|
||||||
background: "yellow",
|
background: "yellow",
|
||||||
threshold: 42,
|
threshold: 42,
|
||||||
})
|
})
|
||||||
.toFile(output, function(err, info) {
|
.toBuffer();
|
||||||
...
|
|
||||||
});
|
|
||||||
```
|
```
|
||||||
@@ -151,7 +151,7 @@ const counters = sharp.counters(); // { queue: 2, process: 4 }
|
|||||||
> simd([simd]) ⇒ <code>boolean</code>
|
> simd([simd]) ⇒ <code>boolean</code>
|
||||||
|
|
||||||
Get and set use of SIMD vector unit instructions.
|
Get and set use of SIMD vector unit instructions.
|
||||||
Requires libvips to have been compiled with liborc support.
|
Requires libvips to have been compiled with highway support.
|
||||||
|
|
||||||
Improves the performance of `resize`, `blur` and `sharpen` operations
|
Improves the performance of `resize`, `blur` and `sharpen` operations
|
||||||
by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.
|
by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.
|
||||||
@@ -165,12 +165,12 @@ by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM N
|
|||||||
**Example**
|
**Example**
|
||||||
```js
|
```js
|
||||||
const simd = sharp.simd();
|
const simd = sharp.simd();
|
||||||
// simd is `true` if the runtime use of liborc is currently enabled
|
// simd is `true` if the runtime use of highway is currently enabled
|
||||||
```
|
```
|
||||||
**Example**
|
**Example**
|
||||||
```js
|
```js
|
||||||
const simd = sharp.simd(false);
|
const simd = sharp.simd(false);
|
||||||
// prevent libvips from using liborc at runtime
|
// prevent libvips from using highway at runtime
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,86 @@
|
|||||||
|
|
||||||
## v0.33 - *gauge*
|
## v0.33 - *gauge*
|
||||||
|
|
||||||
Requires libvips v8.14.5
|
Requires libvips v8.15.2
|
||||||
|
|
||||||
### v0.33.0 - TBD
|
### v0.33.4 - 16th May 2024
|
||||||
|
|
||||||
* Drop support for Node.js 14 and 16, now requires Node.js >= 18.17.0
|
* Remove experimental status from `pipelineColourspace`.
|
||||||
|
|
||||||
|
* Reduce default concurrency when musl thread over-subscription detected.
|
||||||
|
|
||||||
|
* TypeScript: add missing definitions for `OverlayOptions`.
|
||||||
|
[#4048](https://github.com/lovell/sharp/pull/4048)
|
||||||
|
[@ike-gg](https://github.com/ike-gg)
|
||||||
|
|
||||||
|
* Install: add advanced option to force use of a globally-installed libvips.
|
||||||
|
[#4060](https://github.com/lovell/sharp/issues/4060)
|
||||||
|
|
||||||
|
* Expose `bilinear` resizing kernel (and interpolator).
|
||||||
|
[#4061](https://github.com/lovell/sharp/issues/4061)
|
||||||
|
|
||||||
|
* Ensure `extend` operation stays sequential for multi-page TIFF (regression in 0.32.0).
|
||||||
|
[#4069](https://github.com/lovell/sharp/issues/4069)
|
||||||
|
|
||||||
|
* Tighten validation of constructor `text` integer properties.
|
||||||
|
[#4071](https://github.com/lovell/sharp/issues/4071)
|
||||||
|
|
||||||
|
* Simplify internal StaySequential logic.
|
||||||
|
[#4074](https://github.com/lovell/sharp/pull/4074)
|
||||||
|
[@kleisauke](https://github.com/kleisauke)
|
||||||
|
|
||||||
|
* Ensure negate operation occurs after profile conversion.
|
||||||
|
[#4096](https://github.com/lovell/sharp/pull/4096)
|
||||||
|
[@adriaanmeuris](https://github.com/adriaanmeuris)
|
||||||
|
|
||||||
|
### v0.33.3 - 23rd March 2024
|
||||||
|
|
||||||
|
* Upgrade to libvips v8.15.2 for upstream bug fixes.
|
||||||
|
|
||||||
|
* Ensure `keepIccProfile` retains P3 and CMYK input profiles.
|
||||||
|
[#3906](https://github.com/lovell/sharp/issues/3906)
|
||||||
|
[#4008](https://github.com/lovell/sharp/issues/4008)
|
||||||
|
|
||||||
|
* Ensure `text.wrap` property can accept `word-char` as value.
|
||||||
|
[#4028](https://github.com/lovell/sharp/pull/4028)
|
||||||
|
[@yolopunk](https://github.com/yolopunk)
|
||||||
|
|
||||||
|
* Ensure `clone` takes a deep copy of existing options.
|
||||||
|
[#4029](https://github.com/lovell/sharp/issues/4029)
|
||||||
|
|
||||||
|
* Add `bitdepth` option to `heif` output (prebuilt binaries support 8-bit only).
|
||||||
|
[#4036](https://github.com/lovell/sharp/pull/4036)
|
||||||
|
[@mertalev](https://github.com/mertalev)
|
||||||
|
|
||||||
|
### v0.33.2 - 12th January 2024
|
||||||
|
|
||||||
|
* Upgrade to libvips v8.15.1 for upstream bug fixes.
|
||||||
|
|
||||||
|
* TypeScript: add definition for `keepMetadata`.
|
||||||
|
[#3914](https://github.com/lovell/sharp/pull/3914)
|
||||||
|
[@abhi0498](https://github.com/abhi0498)
|
||||||
|
|
||||||
|
* Ensure `extend` operation stays sequential when copying (regression in 0.32.0).
|
||||||
|
[#3928](https://github.com/lovell/sharp/issues/3928)
|
||||||
|
|
||||||
|
* Improve error handling for unsupported multi-page rotation.
|
||||||
|
[#3940](https://github.com/lovell/sharp/issues/3940)
|
||||||
|
|
||||||
|
### v0.33.1 - 17th December 2023
|
||||||
|
|
||||||
|
* Add support for Yarn Plug'n'Play filesystem layout.
|
||||||
|
[#3888](https://github.com/lovell/sharp/issues/3888)
|
||||||
|
|
||||||
|
* Emit warning when attempting to use invalid ICC profiles.
|
||||||
|
[#3895](https://github.com/lovell/sharp/issues/3895)
|
||||||
|
|
||||||
|
* Ensure `VIPS_NOVECTOR` environment variable is respected.
|
||||||
|
[#3897](https://github.com/lovell/sharp/pull/3897)
|
||||||
|
[@icetee](https://github.com/icetee)
|
||||||
|
|
||||||
|
### v0.33.0 - 29th November 2023
|
||||||
|
|
||||||
|
* Drop support for Node.js 14 and 16, now requires Node.js ^18.17.0 or >= 20.3.0
|
||||||
|
|
||||||
* Prebuilt binaries distributed via npm registry and installed via package manager.
|
* Prebuilt binaries distributed via npm registry and installed via package manager.
|
||||||
|
|
||||||
@@ -14,12 +89,41 @@ Requires libvips v8.14.5
|
|||||||
|
|
||||||
* Remove `sharp.vendor`.
|
* 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.
|
* Make `compression` option of `heif` mandatory to help reduce HEIF vs HEIC confusion.
|
||||||
[#3740](https://github.com/lovell/sharp/issues/3740)
|
[#3740](https://github.com/lovell/sharp/issues/3740)
|
||||||
|
|
||||||
* Ensure correct interpretation of 16-bit raw input.
|
* Ensure correct interpretation of 16-bit raw input.
|
||||||
[#3808](https://github.com/lovell/sharp/issues/3808)
|
[#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*
|
## v0.32 - *flow*
|
||||||
|
|
||||||
Requires libvips v8.14.5
|
Requires libvips v8.14.5
|
||||||
|
|||||||
@@ -275,3 +275,21 @@ GitHub: https://github.com/LachlanNewman
|
|||||||
|
|
||||||
Name: BJJ
|
Name: BJJ
|
||||||
GitHub: https://github.com/bianjunjie1981
|
GitHub: https://github.com/bianjunjie1981
|
||||||
|
|
||||||
|
Name: Dennis Beatty
|
||||||
|
GitHub: https://github.com/dnsbty
|
||||||
|
|
||||||
|
Name: Ingvar Stepanyan
|
||||||
|
GitHub: https://github.com/RReverser
|
||||||
|
|
||||||
|
Name: Tamás András Horváth
|
||||||
|
GitHub: https://github.com/icetee
|
||||||
|
|
||||||
|
Name: Aaron Che
|
||||||
|
GitHub: https://github.com/yolopunk
|
||||||
|
|
||||||
|
Name: Mert Alev
|
||||||
|
GitHub: https://github.com/mertalev
|
||||||
|
|
||||||
|
Name: Adriaan Meuris
|
||||||
|
GitHub: https://github.com/adriaanmeuris
|
||||||
|
|||||||
@@ -7,15 +7,13 @@
|
|||||||
<meta name="description" content="Resize large images in common formats to smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions">
|
<meta name="description" content="Resize large images in common formats to smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions">
|
||||||
<meta property="og:title" content="sharp - High performance Node.js image processing">
|
<meta property="og:title" content="sharp - High performance Node.js image processing">
|
||||||
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo-600.png">
|
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo-600.png">
|
||||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; object-src 'none'; style-src 'unsafe-inline';
|
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; connect-src 'self'; object-src 'none';
|
||||||
img-src 'unsafe-inline' data: https://cdn.jsdelivr.net/gh/lovell/ https://www.google-analytics.com;
|
style-src 'unsafe-inline';
|
||||||
connect-src 'self' https://www.google-analytics.com;
|
img-src 'unsafe-inline' data: https://cdn.jsdelivr.net/gh/lovell/;
|
||||||
script-src 'self' 'unsafe-inline' 'unsafe-eval'
|
script-src 'self' 'unsafe-inline' 'unsafe-eval' https://static.cloudflareinsights.com/beacon.min.js;">
|
||||||
https://www.google-analytics.com/analytics.js;">
|
|
||||||
<link rel="icon" type="image/svg+xml" href="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo.svg">
|
<link rel="icon" type="image/svg+xml" href="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo.svg">
|
||||||
<link rel="icon" type="image/png" sizes="32x32" href="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo-32.png">
|
<link rel="icon" type="image/png" sizes="32x32" href="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo-32.png">
|
||||||
<link rel="author" href="/humans.txt" type="text/plain">
|
<link rel="author" href="/humans.txt" type="text/plain">
|
||||||
<link rel="dns-prefetch" href="https://www.google-analytics.com">
|
|
||||||
<script type="application/ld+json">
|
<script type="application/ld+json">
|
||||||
{
|
{
|
||||||
"@context": "https://schema.org",
|
"@context": "https://schema.org",
|
||||||
@@ -67,7 +65,6 @@
|
|||||||
<div id="docute"></div>
|
<div id="docute"></div>
|
||||||
<script src="docute.min.js"></script>
|
<script src="docute.min.js"></script>
|
||||||
<script>
|
<script>
|
||||||
/* docute-google-analytics@1/dist/index.min.js */ !function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e=e||self).docuteGoogleAnalytics=n()}(this,function(){"use strict";function e(e){var n;window.ga||((n=document.createElement("script")).async=!0,n.src="https://www.google-analytics.com/analytics.js",document.body.appendChild(n),window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)},ga.l=Number(new Date),ga("create",e,"auto"))}function n(n,t){e(t),ga("set","page",n),ga("send","pageview")}return function(e){return{name:"@google-analytics",extend:function(t){!function(e,t){"function"==typeof e?e(function(e){n(e,t)}):e.afterEach(function(e){n(e.fullPath,t)})}(t.router,e)}}}});
|
|
||||||
const docuteApiTitlePlugin = {
|
const docuteApiTitlePlugin = {
|
||||||
name: 'apiTitle',
|
name: 'apiTitle',
|
||||||
extend(api) {
|
extend(api) {
|
||||||
@@ -126,7 +123,6 @@
|
|||||||
detectSystemDarkTheme: true,
|
detectSystemDarkTheme: true,
|
||||||
footer: '<a href="https://pixelplumbing.com/" target="_blank">pixelplumbing.com<a>',
|
footer: '<a href="https://pixelplumbing.com/" target="_blank">pixelplumbing.com<a>',
|
||||||
plugins: [
|
plugins: [
|
||||||
docuteGoogleAnalytics('UA-13034748-12'),
|
|
||||||
docuteApiTitlePlugin,
|
docuteApiTitlePlugin,
|
||||||
docuteApiSearchPlugin
|
docuteApiSearchPlugin
|
||||||
],
|
],
|
||||||
|
|||||||
153
docs/install.md
@@ -1,5 +1,13 @@
|
|||||||
# Installation
|
# 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
|
```sh
|
||||||
npm install sharp
|
npm install sharp
|
||||||
```
|
```
|
||||||
@@ -12,11 +20,22 @@ pnpm add sharp
|
|||||||
yarn add sharp
|
yarn add sharp
|
||||||
```
|
```
|
||||||
|
|
||||||
Yarn Plug'n'Play is unsupported.
|
```sh
|
||||||
|
# yarn v1 (maintenance mode)
|
||||||
|
yarn add sharp --ignore-engines
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh
|
||||||
|
bun add sharp
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh
|
||||||
|
deno run --allow-ffi ...
|
||||||
|
```
|
||||||
|
|
||||||
## Prerequisites
|
## Prerequisites
|
||||||
|
|
||||||
* Node.js >= 18.17.0
|
* Node-API v9 compatible runtime e.g. Node.js ^18.17.0 or >=20.3.0.
|
||||||
|
|
||||||
## Prebuilt binaries
|
## Prebuilt binaries
|
||||||
|
|
||||||
@@ -24,15 +43,52 @@ Ready-compiled sharp and libvips binaries are provided for use on the most commo
|
|||||||
|
|
||||||
* macOS x64 (>= 10.13)
|
* macOS x64 (>= 10.13)
|
||||||
* macOS ARM64
|
* macOS ARM64
|
||||||
* Linux x64 (glibc >= 2.26, musl >= 1.2.2, CPU with SSE4.2)
|
|
||||||
* Linux ARM64 (glibc >= 2.26, musl >= 1.2.2)
|
|
||||||
* Linux ARM (glibc >= 2.28)
|
* Linux ARM (glibc >= 2.28)
|
||||||
|
* Linux ARM64 (glibc >= 2.26, musl >= 1.2.2)
|
||||||
|
* Linux s390x (glibc >= 2.31)
|
||||||
|
* Linux x64 (glibc >= 2.26, musl >= 1.2.2, CPU with SSE4.2)
|
||||||
* Windows x64
|
* Windows x64
|
||||||
* Windows x86
|
* Windows x86
|
||||||
|
|
||||||
This provides support for the
|
This provides support for the
|
||||||
JPEG, PNG, WebP, AVIF (limited to 8-bit depth), TIFF, GIF and SVG (input) image formats.
|
JPEG, PNG, WebP, AVIF (limited to 8-bit depth), TIFF, GIF and SVG (input) image formats.
|
||||||
|
|
||||||
|
## Cross-platform
|
||||||
|
|
||||||
|
At install time, package managers will automatically select prebuilt binaries
|
||||||
|
for the current OS platform and CPU architecture, where available.
|
||||||
|
|
||||||
|
Some package managers support multiple platforms and architectures
|
||||||
|
within the same installation tree and/or using the same lockfile.
|
||||||
|
|
||||||
|
### npm v10+
|
||||||
|
|
||||||
|
> ⚠️ **npm `package-lock.json` files can cause installation problems due to [npm bug #4828](https://github.com/npm/cli/issues/4828)**
|
||||||
|
|
||||||
|
Provides limited support via `--os`, `--cpu` and `--libc` flags.
|
||||||
|
|
||||||
|
To support macOS with Intel x64 and ARM64 CPUs:
|
||||||
|
```sh
|
||||||
|
npm install --cpu=x64 --os=darwin sharp
|
||||||
|
npm install --cpu=arm64 --os=darwin sharp
|
||||||
|
```
|
||||||
|
|
||||||
|
When the cross-target is Linux, the C standard library must be specified.
|
||||||
|
|
||||||
|
To support glibc (e.g. Debian) and musl (e.g. Alpine) Linux with Intel x64 CPUs:
|
||||||
|
```sh
|
||||||
|
npm install --cpu=x64 --os=linux --libc=glibc sharp
|
||||||
|
npm install --cpu=x64 --os=linux --libc=musl sharp
|
||||||
|
```
|
||||||
|
|
||||||
|
### yarn v3+
|
||||||
|
|
||||||
|
Use the [supportedArchitectures](https://yarnpkg.com/configuration/yarnrc#supportedArchitectures) configuration.
|
||||||
|
|
||||||
|
### pnpm v8+
|
||||||
|
|
||||||
|
Use the [supportedArchitectures](https://pnpm.io/package_json#pnpmsupportedarchitectures) configuration.
|
||||||
|
|
||||||
## Custom libvips
|
## Custom libvips
|
||||||
|
|
||||||
To use a custom, globally-installed version of libvips instead of the provided binaries,
|
To use a custom, globally-installed version of libvips instead of the provided binaries,
|
||||||
@@ -49,14 +105,19 @@ and on macOS when running Node.js under Rosetta.
|
|||||||
|
|
||||||
This module will be compiled from source at `npm install` time when:
|
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), or
|
* a globally-installed libvips is detected, or
|
||||||
* when the `npm install --build-from-source` flag is used.
|
* when the `npm install --build-from-source` flag is used.
|
||||||
|
|
||||||
|
The logic to detect a globally-installed libvips can be skipped by setting the
|
||||||
|
`SHARP_IGNORE_GLOBAL_LIBVIPS` (never try to use it) or
|
||||||
|
`SHARP_FORCE_GLOBAL_LIBVIPS` (always try to use it, even when missing or outdated)
|
||||||
|
environment variables.
|
||||||
|
|
||||||
Building from source requires:
|
Building from source requires:
|
||||||
|
|
||||||
* C++11 compiler
|
* C++11 compiler
|
||||||
* [node-addon-api](https://www.npmjs.com/package/node-addon-api)
|
* [node-addon-api](https://www.npmjs.com/package/node-addon-api) version 7+
|
||||||
* [node-gyp](https://github.com/nodejs/node-gyp#installation) and its dependencies
|
* [node-gyp](https://github.com/nodejs/node-gyp#installation) version 9+ and its dependencies
|
||||||
|
|
||||||
There is an install-time check for these dependencies.
|
There is an install-time check for these dependencies.
|
||||||
If `node-addon-api` or `node-gyp` cannot be found, try adding them via:
|
If `node-addon-api` or `node-gyp` cannot be found, try adding them via:
|
||||||
@@ -69,6 +130,19 @@ For cross-compiling, the `--platform`, `--arch` and `--libc` npm flags
|
|||||||
(or the `npm_config_platform`, `npm_config_arch` and `npm_config_libc` environment variables)
|
(or the `npm_config_platform`, `npm_config_arch` and `npm_config_libc` environment variables)
|
||||||
can be used to configure the target environment.
|
can be used to configure the target environment.
|
||||||
|
|
||||||
|
## 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 install --cpu=wasm32 sharp
|
||||||
|
```
|
||||||
|
|
||||||
## FreeBSD
|
## FreeBSD
|
||||||
|
|
||||||
The `vips` package must be installed before `npm install` is run.
|
The `vips` package must be installed before `npm install` is run.
|
||||||
@@ -106,15 +180,11 @@ must include binaries for either the linux-x64 or linux-arm64 platforms
|
|||||||
depending on the chosen architecture.
|
depending on the chosen architecture.
|
||||||
|
|
||||||
When building your deployment package on a machine that differs from the target architecture,
|
When building your deployment package on a machine that differs from the target architecture,
|
||||||
you will need to install either `@sharpen/sharp-linux-x64` or `@sharpen/sharp-linux-arm64` package.
|
see the [cross-platform](#cross-platform) section to help decide which package manager is appropriate
|
||||||
|
and how to configure it.
|
||||||
|
|
||||||
```sh
|
Some package managers use symbolic links
|
||||||
npm install --force @sharpen/sharp-linux-x64
|
but AWS Lambda does not support these within deployment packages.
|
||||||
```
|
|
||||||
|
|
||||||
```sh
|
|
||||||
npm install --force @sharpen/sharp-linux-arm64
|
|
||||||
```
|
|
||||||
|
|
||||||
To get the best performance select the largest memory available.
|
To get the best performance select the largest memory available.
|
||||||
A 1536 MB function provides ~12x more CPU time than a 128 MB function.
|
A 1536 MB function provides ~12x more CPU time than a 128 MB function.
|
||||||
@@ -165,7 +235,45 @@ custom:
|
|||||||
- sharp
|
- sharp
|
||||||
packagerOptions:
|
packagerOptions:
|
||||||
scripts:
|
scripts:
|
||||||
- npm install --force @sharpen/sharp-linux-x64
|
- 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
|
||||||
@@ -204,19 +312,6 @@ use the `FONTCONFIG_PATH` environment variable to point to a custom location.
|
|||||||
|
|
||||||
Embedded SVG fonts are unsupported.
|
Embedded SVG fonts are unsupported.
|
||||||
|
|
||||||
## Worker threads
|
|
||||||
|
|
||||||
On some platforms, including glibc-based Linux,
|
|
||||||
the main thread must call `require('sharp')`
|
|
||||||
_before_ worker threads are created.
|
|
||||||
This is to ensure shared libraries remain loaded in memory
|
|
||||||
until after all threads are complete.
|
|
||||||
|
|
||||||
Without this, the following error may occur:
|
|
||||||
```
|
|
||||||
Module did not self-register
|
|
||||||
```
|
|
||||||
|
|
||||||
## Known conflicts
|
## Known conflicts
|
||||||
|
|
||||||
### Canvas and Windows
|
### Canvas and Windows
|
||||||
|
|||||||
@@ -9,26 +9,26 @@ The I/O limits of the relevant (de)compression library will generally determine
|
|||||||
|
|
||||||
## Contenders
|
## Contenders
|
||||||
|
|
||||||
* [jimp](https://www.npmjs.com/package/jimp) v0.22.7 - Image processing in pure JavaScript.
|
* [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*".
|
* [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.
|
* [gm](https://www.npmjs.com/package/gm) v1.25.0 - Fully featured wrapper around GraphicsMagick's `gm` command line utility.
|
||||||
* [@squoosh/lib](https://www.npmjs.com/package/@squoosh/lib) v0.4.0 - Image libraries transpiled to WebAssembly, includes GPLv3 code, but "*Project no longer maintained*".
|
* [@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*".
|
* [@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.32.0 / libvips v8.14.2 - Caching within libvips disabled to ensure a fair comparison.
|
* sharp v0.33.0 / libvips v8.15.0 - Caching within libvips disabled to ensure a fair comparison.
|
||||||
|
|
||||||
## Environment
|
## Environment
|
||||||
|
|
||||||
### AMD64
|
### AMD64
|
||||||
|
|
||||||
* AWS EC2 us-east-2 [c6a.xlarge](https://aws.amazon.com/ec2/instance-types/c6a/) (4x AMD EPYC 7R13)
|
* AWS EC2 us-east-2 [c7a.xlarge](https://aws.amazon.com/ec2/instance-types/c7a/) (4x AMD EPYC 9R14)
|
||||||
* Ubuntu 22.04 20230303 (ami-0122295b0eb922138)
|
* Ubuntu 23.10 [13f233a16be2](https://hub.docker.com/layers/library/ubuntu/23.10/images/sha256-13f233a16be210b57907b98b0d927ceff7571df390701e14fe1f3901b2c4a4d7)
|
||||||
* Node.js 16.19.1
|
* Node.js 20.10.0
|
||||||
|
|
||||||
### ARM64
|
### ARM64
|
||||||
|
|
||||||
* AWS EC2 us-east-2 [c7g.xlarge](https://aws.amazon.com/ec2/instance-types/c7g/) (4x ARM Graviton3)
|
* AWS EC2 us-east-2 [c7g.xlarge](https://aws.amazon.com/ec2/instance-types/c7g/) (4x ARM Graviton3)
|
||||||
* Ubuntu 22.04 20230303 (ami-0af198159897e7a29)
|
* Ubuntu 23.10 [7708743264cb](https://hub.docker.com/layers/library/ubuntu/23.10/images/sha256-7708743264cbb7f6cf7fc13e915faece45a6cdda455748bc55e58e8de3d27b63)
|
||||||
* Node.js 16.19.1
|
* Node.js 20.10.0
|
||||||
|
|
||||||
## Task: JPEG
|
## Task: JPEG
|
||||||
|
|
||||||
@@ -43,28 +43,28 @@ Note: jimp does not support Lanczos 3, bicubic resampling used instead.
|
|||||||
| Module | Input | Output | Ops/sec | Speed-up |
|
| Module | Input | Output | Ops/sec | Speed-up |
|
||||||
| :----------------- | :----- | :----- | ------: | -------: |
|
| :----------------- | :----- | :----- | ------: | -------: |
|
||||||
| jimp | buffer | buffer | 0.84 | 1.0 |
|
| jimp | buffer | buffer | 0.84 | 1.0 |
|
||||||
| squoosh-cli | file | file | 1.07 | 1.3 |
|
| squoosh-cli | file | file | 1.54 | 1.8 |
|
||||||
| squoosh-lib | buffer | buffer | 1.82 | 2.2 |
|
| squoosh-lib | buffer | buffer | 2.24 | 2.7 |
|
||||||
| gm | buffer | buffer | 8.41 | 10.0 |
|
| imagemagick | file | file | 11.75 | 14.0 |
|
||||||
| gm | file | file | 8.45 | 10.0 |
|
| gm | buffer | buffer | 12.66 | 15.1 |
|
||||||
| imagemagick | file | file | 8.77 | 10.4 |
|
| gm | file | file | 12.72 | 15.1 |
|
||||||
| sharp | stream | stream | 36.36 | 43.3 |
|
| sharp | stream | stream | 48.31 | 57.5 |
|
||||||
| sharp | file | file | 38.67 | 46.0 |
|
| sharp | file | file | 51.42 | 61.2 |
|
||||||
| sharp | buffer | buffer | 39.44 | 47.0 |
|
| sharp | buffer | buffer | 52.41 | 62.4 |
|
||||||
|
|
||||||
#### Results: JPEG (ARM64)
|
#### Results: JPEG (ARM64)
|
||||||
|
|
||||||
| Module | Input | Output | Ops/sec | Speed-up |
|
| Module | Input | Output | Ops/sec | Speed-up |
|
||||||
| :----------------- | :----- | :----- | ------: | -------: |
|
| :----------------- | :----- | :----- | ------: | -------: |
|
||||||
| jimp | buffer | buffer | 1.02 | 1.0 |
|
| jimp | buffer | buffer | 0.88 | 1.0 |
|
||||||
| squoosh-cli | file | file | 1.11 | 1.1 |
|
| squoosh-cli | file | file | 1.18 | 1.3 |
|
||||||
| squoosh-lib | buffer | buffer | 2.08 | 2.0 |
|
| squoosh-lib | buffer | buffer | 1.99 | 2.3 |
|
||||||
| gm | buffer | buffer | 8.80 | 8.6 |
|
| gm | buffer | buffer | 6.06 | 6.9 |
|
||||||
| gm | file | file | 10.05 | 9.9 |
|
| gm | file | file | 10.81 | 12.3 |
|
||||||
| imagemagick | file | file | 10.28 | 10.1 |
|
| imagemagick | file | file | 10.95 | 12.4 |
|
||||||
| sharp | stream | stream | 26.87 | 26.3 |
|
| sharp | stream | stream | 33.15 | 37.7 |
|
||||||
| sharp | file | file | 27.88 | 27.3 |
|
| sharp | file | file | 34.99 | 39.8 |
|
||||||
| sharp | buffer | buffer | 28.40 | 27.8 |
|
| sharp | buffer | buffer | 36.05 | 41.0 |
|
||||||
|
|
||||||
## Task: PNG
|
## Task: PNG
|
||||||
|
|
||||||
@@ -80,25 +80,25 @@ Note: jimp does not support premultiply/unpremultiply.
|
|||||||
|
|
||||||
| Module | Input | Output | Ops/sec | Speed-up |
|
| Module | Input | Output | Ops/sec | Speed-up |
|
||||||
| :----------------- | :----- | :----- | ------: | -------: |
|
| :----------------- | :----- | :----- | ------: | -------: |
|
||||||
| squoosh-cli | file | file | 0.40 | 1.0 |
|
| squoosh-cli | file | file | 0.34 | 1.0 |
|
||||||
| squoosh-lib | buffer | buffer | 0.47 | 1.2 |
|
| squoosh-lib | buffer | buffer | 0.51 | 1.5 |
|
||||||
| gm | file | file | 6.47 | 16.2 |
|
| jimp | buffer | buffer | 3.59 | 10.6 |
|
||||||
| jimp | buffer | buffer | 6.60 | 16.5 |
|
| gm | file | file | 8.54 | 25.1 |
|
||||||
| imagemagick | file | file | 7.08 | 17.7 |
|
| imagemagick | file | file | 9.23 | 27.1 |
|
||||||
| sharp | file | file | 17.80 | 44.5 |
|
| sharp | file | file | 25.43 | 74.8 |
|
||||||
| sharp | buffer | buffer | 18.02 | 45.0 |
|
| sharp | buffer | buffer | 25.70 | 75.6 |
|
||||||
|
|
||||||
### Results: PNG (ARM64)
|
### Results: PNG (ARM64)
|
||||||
|
|
||||||
| Module | Input | Output | Ops/sec | Speed-up |
|
| Module | Input | Output | Ops/sec | Speed-up |
|
||||||
| :----------------- | :----- | :----- | ------: | -------: |
|
| :----------------- | :----- | :----- | ------: | -------: |
|
||||||
| squoosh-cli | file | file | 0.40 | 1.0 |
|
| squoosh-cli | file | file | 0.33 | 1.0 |
|
||||||
| squoosh-lib | buffer | buffer | 0.48 | 1.2 |
|
| squoosh-lib | buffer | buffer | 0.46 | 1.4 |
|
||||||
| gm | file | file | 7.20 | 18.0 |
|
| jimp | buffer | buffer | 3.51 | 10.6 |
|
||||||
| jimp | buffer | buffer | 7.62 | 19.1 |
|
| gm | file | file | 7.47 | 22.6 |
|
||||||
| imagemagick | file | file | 7.96 | 19.9 |
|
| imagemagick | file | file | 8.06 | 24.4 |
|
||||||
| sharp | file | file | 12.97 | 32.4 |
|
| sharp | file | file | 17.31 | 52.5 |
|
||||||
| sharp | buffer | buffer | 13.12 | 32.8 |
|
| sharp | buffer | buffer | 17.66 | 53.5 |
|
||||||
|
|
||||||
## Running the benchmark test
|
## Running the benchmark test
|
||||||
|
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ module.exports = [
|
|||||||
'current',
|
'current',
|
||||||
'date',
|
'date',
|
||||||
'default',
|
'default',
|
||||||
|
'deprecated',
|
||||||
'does',
|
'does',
|
||||||
'each',
|
'each',
|
||||||
'either',
|
'either',
|
||||||
@@ -46,6 +47,7 @@ module.exports = [
|
|||||||
'given',
|
'given',
|
||||||
'has',
|
'has',
|
||||||
'have',
|
'have',
|
||||||
|
'helps',
|
||||||
'how',
|
'how',
|
||||||
'image',
|
'image',
|
||||||
'implies',
|
'implies',
|
||||||
@@ -58,6 +60,7 @@ module.exports = [
|
|||||||
'lots',
|
'lots',
|
||||||
'make',
|
'make',
|
||||||
'may',
|
'may',
|
||||||
|
'meaning',
|
||||||
'more',
|
'more',
|
||||||
'most',
|
'most',
|
||||||
'much',
|
'much',
|
||||||
@@ -79,6 +82,7 @@ module.exports = [
|
|||||||
'pre',
|
'pre',
|
||||||
'previously',
|
'previously',
|
||||||
'produce',
|
'produce',
|
||||||
|
'proper',
|
||||||
'provide',
|
'provide',
|
||||||
'provided',
|
'provided',
|
||||||
'ready',
|
'ready',
|
||||||
@@ -116,6 +120,7 @@ module.exports = [
|
|||||||
'unless',
|
'unless',
|
||||||
'unmaintained',
|
'unmaintained',
|
||||||
'unsuitable',
|
'unsuitable',
|
||||||
|
'unsupported',
|
||||||
'until',
|
'until',
|
||||||
'use',
|
'use',
|
||||||
'used',
|
'used',
|
||||||
|
|||||||
@@ -3,34 +3,39 @@
|
|||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const { useGlobalLibvips, globalLibvipsVersion, log, spawnRebuild } = require('../lib/libvips');
|
try {
|
||||||
|
const { useGlobalLibvips, globalLibvipsVersion, log, spawnRebuild } = require('../lib/libvips');
|
||||||
|
|
||||||
const buildFromSource = (msg) => {
|
const buildFromSource = (msg) => {
|
||||||
log(msg);
|
log(msg);
|
||||||
log('Attempting to build from source via node-gyp');
|
log('Attempting to build from source via node-gyp');
|
||||||
try {
|
try {
|
||||||
require('node-addon-api');
|
const addonApi = require('node-addon-api');
|
||||||
log('Found node-addon-api');
|
log(`Found node-addon-api ${addonApi.version || ''}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
log('Please add node-addon-api to your dependencies');
|
log('Please add node-addon-api to your dependencies');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const gyp = require('node-gyp');
|
const gyp = require('node-gyp');
|
||||||
log(`Found node-gyp version ${gyp().version}`);
|
log(`Found node-gyp version ${gyp().version}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
log('Please add node-gyp to your dependencies');
|
log('Please add node-gyp to your dependencies');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
log('See https://sharp.pixelplumbing.com/install#building-from-source');
|
log('See https://sharp.pixelplumbing.com/install#building-from-source');
|
||||||
const status = spawnRebuild();
|
const status = spawnRebuild();
|
||||||
if (status !== 0) {
|
if (status !== 0) {
|
||||||
process.exit(status);
|
process.exit(status);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (useGlobalLibvips()) {
|
if (useGlobalLibvips()) {
|
||||||
buildFromSource(`Detected globally-installed libvips v${globalLibvipsVersion()}`);
|
buildFromSource(`Detected globally-installed libvips v${globalLibvipsVersion()}`);
|
||||||
} else if (process.env.npm_config_build_from_source) {
|
} else if (process.env.npm_config_build_from_source) {
|
||||||
buildFromSource('Detected --build-from-source flag');
|
buildFromSource('Detected --build-from-source flag');
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
const summary = err.message.split(/\n/).slice(0, 1);
|
||||||
|
console.log(`sharp: skipping install check: ${summary}`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ const colourspace = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tint the image using the provided chroma while preserving the image luminance.
|
* Tint the image using the provided colour.
|
||||||
* An alpha channel may be present and will be unchanged by the operation.
|
* An alpha channel may be present and will be unchanged by the operation.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
@@ -27,14 +27,12 @@ const colourspace = {
|
|||||||
* .tint({ r: 255, g: 240, b: 16 })
|
* .tint({ r: 255, g: 240, b: 16 })
|
||||||
* .toBuffer();
|
* .toBuffer();
|
||||||
*
|
*
|
||||||
* @param {string|Object} rgb - parsed by the [color](https://www.npmjs.org/package/color) module to extract chroma values.
|
* @param {string|Object} tint - Parsed by the [color](https://www.npmjs.org/package/color) module.
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid parameter
|
* @throws {Error} Invalid parameter
|
||||||
*/
|
*/
|
||||||
function tint (rgb) {
|
function tint (tint) {
|
||||||
const colour = color(rgb);
|
this._setBackgroundColourOption('tint', tint);
|
||||||
this.options.tintA = colour.a();
|
|
||||||
this.options.tintB = colour.b();
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,8 +71,6 @@ function grayscale (grayscale) {
|
|||||||
* All operations will use this colourspace before converting to the output colourspace,
|
* All operations will use this colourspace before converting to the output colourspace,
|
||||||
* as defined by {@link #tocolourspace|toColourspace}.
|
* as defined by {@link #tocolourspace|toColourspace}.
|
||||||
*
|
*
|
||||||
* This feature is experimental and has not yet been fully-tested with all operations.
|
|
||||||
*
|
|
||||||
* @since 0.29.0
|
* @since 0.29.0
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
@@ -92,7 +88,7 @@ function pipelineColourspace (colourspace) {
|
|||||||
if (!is.string(colourspace)) {
|
if (!is.string(colourspace)) {
|
||||||
throw is.invalidParameterError('colourspace', 'string', colourspace);
|
throw is.invalidParameterError('colourspace', 'string', colourspace);
|
||||||
}
|
}
|
||||||
this.options.colourspaceInput = colourspace;
|
this.options.colourspacePipeline = colourspace;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,6 +22,10 @@ const debuglog = util.debuglog('sharp');
|
|||||||
*
|
*
|
||||||
* Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.
|
* Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.
|
||||||
*
|
*
|
||||||
|
* When loading more than one page/frame of an animated image,
|
||||||
|
* these are combined as a vertically-stacked "toilet roll" image
|
||||||
|
* where the overall height is the `pageHeight` multiplied by the number of `pages`.
|
||||||
|
*
|
||||||
* @constructs Sharp
|
* @constructs Sharp
|
||||||
*
|
*
|
||||||
* @emits Sharp#info
|
* @emits Sharp#info
|
||||||
@@ -36,14 +40,16 @@ const debuglog = util.debuglog('sharp');
|
|||||||
* });
|
* });
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* // Read image data from readableStream,
|
* // Read image data from remote URL,
|
||||||
* // resize to 300 pixels wide,
|
* // resize to 300 pixels wide,
|
||||||
* // emit an 'info' event with calculated dimensions
|
* // emit an 'info' event with calculated dimensions
|
||||||
* // and finally write image data to writableStream
|
* // and finally write image data to writableStream
|
||||||
* var transformer = sharp()
|
* const { body } = fetch('https://...');
|
||||||
|
* const readableStream = Readable.fromWeb(body);
|
||||||
|
* const transformer = sharp()
|
||||||
* .resize(300)
|
* .resize(300)
|
||||||
* .on('info', function(info) {
|
* .on('info', ({ height }) => {
|
||||||
* console.log('Image height is ' + info.height);
|
* console.log(`Image height is ${height}`);
|
||||||
* });
|
* });
|
||||||
* readableStream.pipe(transformer).pipe(writableStream);
|
* readableStream.pipe(transformer).pipe(writableStream);
|
||||||
*
|
*
|
||||||
@@ -121,7 +127,7 @@ const debuglog = util.debuglog('sharp');
|
|||||||
* a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file.
|
* a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file.
|
||||||
* JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present.
|
* JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present.
|
||||||
* @param {Object} [options] - if present, is an Object with optional attributes.
|
* @param {Object} [options] - if present, is an Object with optional attributes.
|
||||||
* @param {string} [options.failOn='warning'] - when to abort processing of invalid pixel data, one of (in order of sensitivity): 'none' (least), 'truncated', 'error' or 'warning' (most), higher levels imply lower levels, invalid metadata will always abort.
|
* @param {string} [options.failOn='warning'] - When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort.
|
||||||
* @param {number|boolean} [options.limitInputPixels=268402689] - Do not process input images where the number of pixels
|
* @param {number|boolean} [options.limitInputPixels=268402689] - Do not process input images where the number of pixels
|
||||||
* (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted.
|
* (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted.
|
||||||
* An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF).
|
* An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF).
|
||||||
@@ -160,7 +166,7 @@ const debuglog = util.debuglog('sharp');
|
|||||||
* @param {number} [options.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified.
|
* @param {number} [options.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified.
|
||||||
* @param {boolean} [options.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`.
|
* @param {boolean} [options.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`.
|
||||||
* @param {number} [options.text.spacing=0] - text line height in points. Will use the font line height if none is specified.
|
* @param {number} [options.text.spacing=0] - text line height in points. Will use the font line height if none is specified.
|
||||||
* @param {string} [options.text.wrap='word'] - word wrapping style when width is provided, one of: 'word', 'char', 'charWord' (prefer char, fallback to word) or 'none'.
|
* @param {string} [options.text.wrap='word'] - word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'.
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid parameters
|
* @throws {Error} Invalid parameters
|
||||||
*/
|
*/
|
||||||
@@ -212,8 +218,7 @@ const Sharp = function (input, options) {
|
|||||||
kernel: 'lanczos3',
|
kernel: 'lanczos3',
|
||||||
fastShrinkOnLoad: true,
|
fastShrinkOnLoad: true,
|
||||||
// operations
|
// operations
|
||||||
tintA: 128,
|
tint: [-1, 0, 0, 0],
|
||||||
tintB: 128,
|
|
||||||
flatten: false,
|
flatten: false,
|
||||||
flattenBackground: [0, 0, 0],
|
flattenBackground: [0, 0, 0],
|
||||||
unflatten: false,
|
unflatten: false,
|
||||||
@@ -230,7 +235,8 @@ const Sharp = function (input, options) {
|
|||||||
threshold: 0,
|
threshold: 0,
|
||||||
thresholdGrayscale: true,
|
thresholdGrayscale: true,
|
||||||
trimBackground: [],
|
trimBackground: [],
|
||||||
trimThreshold: 0,
|
trimThreshold: -1,
|
||||||
|
trimLineArt: false,
|
||||||
gamma: 0,
|
gamma: 0,
|
||||||
gammaOut: 0,
|
gammaOut: 0,
|
||||||
greyscale: false,
|
greyscale: false,
|
||||||
@@ -251,17 +257,18 @@ const Sharp = function (input, options) {
|
|||||||
removeAlpha: false,
|
removeAlpha: false,
|
||||||
ensureAlpha: -1,
|
ensureAlpha: -1,
|
||||||
colourspace: 'srgb',
|
colourspace: 'srgb',
|
||||||
colourspaceInput: 'last',
|
colourspacePipeline: 'last',
|
||||||
composite: [],
|
composite: [],
|
||||||
// output
|
// output
|
||||||
fileOut: '',
|
fileOut: '',
|
||||||
formatOut: 'input',
|
formatOut: 'input',
|
||||||
streamOut: false,
|
streamOut: false,
|
||||||
withMetadata: false,
|
keepMetadata: 0,
|
||||||
withMetadataOrientation: -1,
|
withMetadataOrientation: -1,
|
||||||
withMetadataDensity: 0,
|
withMetadataDensity: 0,
|
||||||
withMetadataIcc: '',
|
withIccProfile: '',
|
||||||
withMetadataStrs: {},
|
withExif: {},
|
||||||
|
withExifMerge: true,
|
||||||
resolveWithObject: false,
|
resolveWithObject: false,
|
||||||
// output format
|
// output format
|
||||||
jpegQuality: 80,
|
jpegQuality: 80,
|
||||||
@@ -305,6 +312,7 @@ const Sharp = function (input, options) {
|
|||||||
tiffCompression: 'jpeg',
|
tiffCompression: 'jpeg',
|
||||||
tiffPredictor: 'horizontal',
|
tiffPredictor: 'horizontal',
|
||||||
tiffPyramid: false,
|
tiffPyramid: false,
|
||||||
|
tiffMiniswhite: false,
|
||||||
tiffBitdepth: 8,
|
tiffBitdepth: 8,
|
||||||
tiffTile: false,
|
tiffTile: false,
|
||||||
tiffTileHeight: 256,
|
tiffTileHeight: 256,
|
||||||
@@ -317,6 +325,7 @@ const Sharp = function (input, options) {
|
|||||||
heifCompression: 'av1',
|
heifCompression: 'av1',
|
||||||
heifEffort: 4,
|
heifEffort: 4,
|
||||||
heifChromaSubsampling: '4:4:4',
|
heifChromaSubsampling: '4:4:4',
|
||||||
|
heifBitdepth: 8,
|
||||||
jxlDistance: 1,
|
jxlDistance: 1,
|
||||||
jxlDecodingTier: 0,
|
jxlDecodingTier: 0,
|
||||||
jxlEffort: 7,
|
jxlEffort: 7,
|
||||||
@@ -417,13 +426,16 @@ Object.setPrototypeOf(Sharp, stream.Duplex);
|
|||||||
function clone () {
|
function clone () {
|
||||||
// Clone existing options
|
// Clone existing options
|
||||||
const clone = this.constructor.call();
|
const clone = this.constructor.call();
|
||||||
clone.options = Object.assign({}, this.options);
|
const { debuglog, queueListener, ...options } = this.options;
|
||||||
|
clone.options = structuredClone(options);
|
||||||
|
clone.options.debuglog = debuglog;
|
||||||
|
clone.options.queueListener = queueListener;
|
||||||
// Pass 'finish' event to clone for Stream-based input
|
// Pass 'finish' event to clone for Stream-based input
|
||||||
if (this._isStreamInput()) {
|
if (this._isStreamInput()) {
|
||||||
this.on('finish', () => {
|
this.on('finish', () => {
|
||||||
// Clone inherits input data
|
// Clone inherits input data
|
||||||
this._flattenBufferIn();
|
this._flattenBufferIn();
|
||||||
clone.options.bufferIn = this.options.bufferIn;
|
clone.options.input.buffer = this.options.input.buffer;
|
||||||
clone.emit('finish');
|
clone.emit('finish');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
121
lib/index.d.ts
vendored
@@ -126,7 +126,7 @@ declare namespace sharp {
|
|||||||
function counters(): SharpCounters;
|
function counters(): SharpCounters;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get and set use of SIMD vector unit instructions. Requires libvips to have been compiled with liborc support.
|
* Get and set use of SIMD vector unit instructions. Requires libvips to have been compiled with highway support.
|
||||||
* Improves the performance of resize, blur and sharpen operations by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.
|
* Improves the performance of resize, blur and sharpen operations by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.
|
||||||
* @param enable enable or disable use of SIMD vector unit instructions
|
* @param enable enable or disable use of SIMD vector unit instructions
|
||||||
* @returns true if usage of SIMD vector unit instructions is enabled
|
* @returns true if usage of SIMD vector unit instructions is enabled
|
||||||
@@ -239,12 +239,12 @@ declare namespace sharp {
|
|||||||
//#region Color functions
|
//#region Color functions
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tint the image using the provided chroma while preserving the image luminance.
|
* Tint the image using the provided colour.
|
||||||
* An alpha channel may be present and will be unchanged by the operation.
|
* An alpha channel may be present and will be unchanged by the operation.
|
||||||
* @param rgb Parsed by the color module to extract chroma values.
|
* @param tint Parsed by the color module.
|
||||||
* @returns A sharp instance that can be used to chain operations
|
* @returns A sharp instance that can be used to chain operations
|
||||||
*/
|
*/
|
||||||
tint(rgb: Color): Sharp;
|
tint(tint: Color): Sharp;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert to 8-bit greyscale; 256 shades of grey.
|
* Convert to 8-bit greyscale; 256 shades of grey.
|
||||||
@@ -341,6 +341,12 @@ declare namespace sharp {
|
|||||||
*/
|
*/
|
||||||
metadata(): Promise<Metadata>;
|
metadata(): Promise<Metadata>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image.
|
||||||
|
* @returns A sharp instance that can be used to chain operations
|
||||||
|
*/
|
||||||
|
keepMetadata(): Sharp;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Access to pixel-derived image statistics for every channel in the image.
|
* Access to pixel-derived image statistics for every channel in the image.
|
||||||
* @returns A sharp instance that can be used to chain operations
|
* @returns A sharp instance that can be used to chain operations
|
||||||
@@ -633,6 +639,43 @@ declare namespace sharp {
|
|||||||
*/
|
*/
|
||||||
toBuffer(options: { resolveWithObject: true }): Promise<{ data: Buffer; info: OutputInfo }>;
|
toBuffer(options: { resolveWithObject: true }): Promise<{ data: Buffer; info: OutputInfo }>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep all EXIF metadata from the input image in the output image.
|
||||||
|
* EXIF metadata is unsupported for TIFF output.
|
||||||
|
* @returns A sharp instance that can be used to chain operations
|
||||||
|
*/
|
||||||
|
keepExif(): Sharp;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set EXIF metadata in the output image, ignoring any EXIF in the input image.
|
||||||
|
* @param {Exif} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.
|
||||||
|
* @returns A sharp instance that can be used to chain operations
|
||||||
|
* @throws {Error} Invalid parameters
|
||||||
|
*/
|
||||||
|
withExif(exif: Exif): Sharp;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update EXIF metadata from the input image in the output image.
|
||||||
|
* @param {Exif} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.
|
||||||
|
* @returns A sharp instance that can be used to chain operations
|
||||||
|
* @throws {Error} Invalid parameters
|
||||||
|
*/
|
||||||
|
withExifMerge(exif: Exif): Sharp;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep ICC profile from the input image in the output image where possible.
|
||||||
|
* @returns A sharp instance that can be used to chain operations
|
||||||
|
*/
|
||||||
|
keepIccProfile(): Sharp;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transform using an ICC profile and attach to the output image.
|
||||||
|
* @param {string} icc - Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk).
|
||||||
|
* @returns A sharp instance that can be used to chain operations
|
||||||
|
* @throws {Error} Invalid parameters
|
||||||
|
*/
|
||||||
|
withIccProfile(icc: string, options?: WithIccProfileOptions): Sharp;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Include all metadata (EXIF, XMP, IPTC) from the input image in the output image.
|
* Include all metadata (EXIF, XMP, IPTC) from the input image in the output image.
|
||||||
* The default behaviour, when withMetadata is not used, is to strip all metadata and convert to the device-independent sRGB colour space.
|
* The default behaviour, when withMetadata is not used, is to strip all metadata and convert to the device-independent sRGB colour space.
|
||||||
@@ -847,11 +890,11 @@ declare namespace sharp {
|
|||||||
* Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.
|
* Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.
|
||||||
* Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels.
|
* Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels.
|
||||||
* The info response Object will contain trimOffsetLeft and trimOffsetTop properties.
|
* The info response Object will contain trimOffsetLeft and trimOffsetTop properties.
|
||||||
* @param trim The specific background colour to trim, the threshold for doing so or an Object with both.
|
* @param options trim options
|
||||||
* @throws {Error} Invalid parameters
|
* @throws {Error} Invalid parameters
|
||||||
* @returns A sharp instance that can be used to chain operations
|
* @returns A sharp instance that can be used to chain operations
|
||||||
*/
|
*/
|
||||||
trim(trim?: string | number | TrimOptions): Sharp;
|
trim(options?: TrimOptions): Sharp;
|
||||||
|
|
||||||
//#endregion
|
//#endregion
|
||||||
}
|
}
|
||||||
@@ -974,19 +1017,36 @@ declare namespace sharp {
|
|||||||
rgba?: boolean;
|
rgba?: boolean;
|
||||||
/** Text line height in points. Will use the font line height if none is specified. (optional, default `0`) */
|
/** Text line height in points. Will use the font line height if none is specified. (optional, default `0`) */
|
||||||
spacing?: number;
|
spacing?: number;
|
||||||
/** Word wrapping style when width is provided, one of: 'word', 'char', 'charWord' (prefer char, fallback to word) or 'none' */
|
/** Word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none' */
|
||||||
wrap?: TextWrap;
|
wrap?: TextWrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface ExifDir {
|
||||||
|
[k: string]: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Exif {
|
||||||
|
'IFD0'?: ExifDir;
|
||||||
|
'IFD1'?: ExifDir;
|
||||||
|
'IFD2'?: ExifDir;
|
||||||
|
'IFD3'?: ExifDir;
|
||||||
|
}
|
||||||
|
|
||||||
interface WriteableMetadata {
|
interface WriteableMetadata {
|
||||||
/** Value between 1 and 8, used to update the EXIF Orientation tag. */
|
|
||||||
orientation?: number | undefined;
|
|
||||||
/** Filesystem path to output ICC profile, defaults to sRGB. */
|
|
||||||
icc?: string | undefined;
|
|
||||||
/** Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. (optional, default {}) */
|
|
||||||
exif?: Record<string, any> | undefined;
|
|
||||||
/** Number of pixels per inch (DPI) */
|
/** Number of pixels per inch (DPI) */
|
||||||
density?: number | undefined;
|
density?: number | undefined;
|
||||||
|
/** Value between 1 and 8, used to update the EXIF Orientation tag. */
|
||||||
|
orientation?: number | undefined;
|
||||||
|
/**
|
||||||
|
* Filesystem path to output ICC profile, defaults to sRGB.
|
||||||
|
* @deprecated Use `withIccProfile()` instead.
|
||||||
|
*/
|
||||||
|
icc?: string | undefined;
|
||||||
|
/**
|
||||||
|
* Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.
|
||||||
|
* @deprecated Use `withExif()` or `withExifMerge()` instead.
|
||||||
|
*/
|
||||||
|
exif?: Exif | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Metadata {
|
interface Metadata {
|
||||||
@@ -1096,6 +1156,11 @@ declare namespace sharp {
|
|||||||
force?: boolean | undefined;
|
force?: boolean | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface WithIccProfileOptions {
|
||||||
|
/** Should the ICC profile be included in the output image metadata? (optional, default true) */
|
||||||
|
attach?: boolean | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
interface JpegOptions extends OutputOptions {
|
interface JpegOptions extends OutputOptions {
|
||||||
/** Quality, integer 1-100 (optional, default 80) */
|
/** Quality, integer 1-100 (optional, default 80) */
|
||||||
quality?: number | undefined;
|
quality?: number | undefined;
|
||||||
@@ -1179,6 +1244,8 @@ declare namespace sharp {
|
|||||||
effort?: number | undefined;
|
effort?: number | undefined;
|
||||||
/** set to '4:2:0' to use chroma subsampling, requires libvips v8.11.0 (optional, default '4:4:4') */
|
/** set to '4:2:0' to use chroma subsampling, requires libvips v8.11.0 (optional, default '4:4:4') */
|
||||||
chromaSubsampling?: string | undefined;
|
chromaSubsampling?: string | undefined;
|
||||||
|
/** Set bitdepth to 8, 10 or 12 bit (optional, default 8) */
|
||||||
|
bitdepth?: 8 | 10 | 12 | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface HeifOptions extends OutputOptions {
|
interface HeifOptions extends OutputOptions {
|
||||||
@@ -1192,6 +1259,8 @@ declare namespace sharp {
|
|||||||
effort?: number | undefined;
|
effort?: number | undefined;
|
||||||
/** set to '4:2:0' to use chroma subsampling (optional, default '4:4:4') */
|
/** set to '4:2:0' to use chroma subsampling (optional, default '4:4:4') */
|
||||||
chromaSubsampling?: string | undefined;
|
chromaSubsampling?: string | undefined;
|
||||||
|
/** Set bitdepth to 8, 10 or 12 bit (optional, default 8) */
|
||||||
|
bitdepth?: 8 | 10 | 12 | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface GifOptions extends OutputOptions, AnimationOptions {
|
interface GifOptions extends OutputOptions, AnimationOptions {
|
||||||
@@ -1234,6 +1303,8 @@ declare namespace sharp {
|
|||||||
yres?: number | undefined;
|
yres?: number | undefined;
|
||||||
/** Reduce bitdepth to 1, 2 or 4 bit (optional, default 8) */
|
/** Reduce bitdepth to 1, 2 or 4 bit (optional, default 8) */
|
||||||
bitdepth?: 1 | 2 | 4 | 8 | undefined;
|
bitdepth?: 1 | 2 | 4 | 8 | undefined;
|
||||||
|
/** Write 1-bit images as miniswhite (optional, default false) */
|
||||||
|
miniswhite?: boolean | undefined;
|
||||||
/** Resolution unit options: inch, cm (optional, default 'inch') */
|
/** Resolution unit options: inch, cm (optional, default 'inch') */
|
||||||
resolutionUnit?: 'inch' | 'cm' | undefined;
|
resolutionUnit?: 'inch' | 'cm' | undefined;
|
||||||
}
|
}
|
||||||
@@ -1275,10 +1346,10 @@ declare namespace sharp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface NormaliseOptions {
|
interface NormaliseOptions {
|
||||||
/** Percentile below which luminance values will be underexposed. */
|
/** Percentile below which luminance values will be underexposed. */
|
||||||
lower?: number | undefined;
|
lower?: number | undefined;
|
||||||
/** Percentile above which luminance values will be overexposed. */
|
/** Percentile above which luminance values will be overexposed. */
|
||||||
upper?: number | undefined;
|
upper?: number | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ResizeOptions {
|
interface ResizeOptions {
|
||||||
@@ -1340,10 +1411,12 @@ declare namespace sharp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface TrimOptions {
|
interface TrimOptions {
|
||||||
/** background colour, parsed by the color module, defaults to that of the top-left pixel. (optional) */
|
/** Background colour, parsed by the color module, defaults to that of the top-left pixel. (optional) */
|
||||||
background?: Color | undefined;
|
background?: Color | undefined;
|
||||||
/** the allowed difference from the above colour, a positive number. (optional, default `10`) */
|
/** Allowed difference from the above colour, a positive number. (optional, default 10) */
|
||||||
threshold?: number | undefined;
|
threshold?: number | undefined;
|
||||||
|
/** Does the input more closely resemble line art (e.g. vector) rather than being photographic? (optional, default false) */
|
||||||
|
lineArt?: boolean | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface RawOptions {
|
interface RawOptions {
|
||||||
@@ -1406,6 +1479,14 @@ declare namespace sharp {
|
|||||||
tile?: boolean | undefined;
|
tile?: boolean | undefined;
|
||||||
/** Set to true to avoid premultipling the image below. Equivalent to the --premultiplied vips option. */
|
/** Set to true to avoid premultipling the image below. Equivalent to the --premultiplied vips option. */
|
||||||
premultiplied?: boolean | undefined;
|
premultiplied?: boolean | undefined;
|
||||||
|
/** number representing the DPI for vector overlay image. (optional, default 72)*/
|
||||||
|
density?: number | undefined;
|
||||||
|
/** Set to true to read all frames/pages of an animated image. (optional, default false) */
|
||||||
|
animated?: boolean | undefined;
|
||||||
|
/** see sharp() constructor, (optional, default 'warning') */
|
||||||
|
failOn?: FailOnOptions | undefined;
|
||||||
|
/** see sharp() constructor, (optional, default 268402689) */
|
||||||
|
limitInputPixels?: number | boolean | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TileOptions {
|
interface TileOptions {
|
||||||
@@ -1544,7 +1625,7 @@ declare namespace sharp {
|
|||||||
|
|
||||||
type TextAlign = 'left' | 'centre' | 'center' | 'right';
|
type TextAlign = 'left' | 'centre' | 'center' | 'right';
|
||||||
|
|
||||||
type TextWrap = 'word' | 'char' | 'charWord' | 'none';
|
type TextWrap = 'word' | 'char' | 'word-char' | 'none';
|
||||||
|
|
||||||
type TileContainer = 'fs' | 'zip';
|
type TileContainer = 'fs' | 'zip';
|
||||||
|
|
||||||
|
|||||||
62
lib/input.js
@@ -296,17 +296,17 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(inputOptions.text.width)) {
|
if (is.defined(inputOptions.text.width)) {
|
||||||
if (is.number(inputOptions.text.width)) {
|
if (is.integer(inputOptions.text.width) && inputOptions.text.width > 0) {
|
||||||
inputDescriptor.textWidth = inputOptions.text.width;
|
inputDescriptor.textWidth = inputOptions.text.width;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('text.textWidth', 'number', inputOptions.text.width);
|
throw is.invalidParameterError('text.width', 'positive integer', inputOptions.text.width);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(inputOptions.text.height)) {
|
if (is.defined(inputOptions.text.height)) {
|
||||||
if (is.number(inputOptions.text.height)) {
|
if (is.integer(inputOptions.text.height) && inputOptions.text.height > 0) {
|
||||||
inputDescriptor.textHeight = inputOptions.text.height;
|
inputDescriptor.textHeight = inputOptions.text.height;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('text.height', 'number', inputOptions.text.height);
|
throw is.invalidParameterError('text.height', 'positive integer', inputOptions.text.height);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(inputOptions.text.align)) {
|
if (is.defined(inputOptions.text.align)) {
|
||||||
@@ -324,10 +324,10 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(inputOptions.text.dpi)) {
|
if (is.defined(inputOptions.text.dpi)) {
|
||||||
if (is.number(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 100000)) {
|
if (is.integer(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 1000000)) {
|
||||||
inputDescriptor.textDpi = inputOptions.text.dpi;
|
inputDescriptor.textDpi = inputOptions.text.dpi;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('text.dpi', 'number between 1 and 100000', inputOptions.text.dpi);
|
throw is.invalidParameterError('text.dpi', 'integer between 1 and 1000000', inputOptions.text.dpi);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(inputOptions.text.rgba)) {
|
if (is.defined(inputOptions.text.rgba)) {
|
||||||
@@ -338,17 +338,17 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(inputOptions.text.spacing)) {
|
if (is.defined(inputOptions.text.spacing)) {
|
||||||
if (is.number(inputOptions.text.spacing)) {
|
if (is.integer(inputOptions.text.spacing) && is.inRange(inputOptions.text.spacing, -1000000, 1000000)) {
|
||||||
inputDescriptor.textSpacing = inputOptions.text.spacing;
|
inputDescriptor.textSpacing = inputOptions.text.spacing;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('text.spacing', 'number', inputOptions.text.spacing);
|
throw is.invalidParameterError('text.spacing', 'integer between -1000000 and 1000000', inputOptions.text.spacing);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(inputOptions.text.wrap)) {
|
if (is.defined(inputOptions.text.wrap)) {
|
||||||
if (is.string(inputOptions.text.wrap) && is.inArray(inputOptions.text.wrap, ['word', 'char', 'wordChar', 'none'])) {
|
if (is.string(inputOptions.text.wrap) && is.inArray(inputOptions.text.wrap, ['word', 'char', 'word-char', 'none'])) {
|
||||||
inputDescriptor.textWrap = inputOptions.text.wrap;
|
inputDescriptor.textWrap = inputOptions.text.wrap;
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('text.wrap', 'one of: word, char, wordChar, none', inputOptions.text.wrap);
|
throw is.invalidParameterError('text.wrap', 'one of: word, char, word-char, none', inputOptions.text.wrap);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
delete inputDescriptor.buffer;
|
delete inputDescriptor.buffer;
|
||||||
@@ -483,14 +483,27 @@ function _isStreamInput () {
|
|||||||
* @returns {Promise<Object>|Sharp}
|
* @returns {Promise<Object>|Sharp}
|
||||||
*/
|
*/
|
||||||
function metadata (callback) {
|
function metadata (callback) {
|
||||||
|
const stack = Error();
|
||||||
if (is.fn(callback)) {
|
if (is.fn(callback)) {
|
||||||
if (this._isStreamInput()) {
|
if (this._isStreamInput()) {
|
||||||
this.on('finish', () => {
|
this.on('finish', () => {
|
||||||
this._flattenBufferIn();
|
this._flattenBufferIn();
|
||||||
sharp.metadata(this.options, callback);
|
sharp.metadata(this.options, (err, metadata) => {
|
||||||
|
if (err) {
|
||||||
|
callback(is.nativeError(err, stack));
|
||||||
|
} else {
|
||||||
|
callback(null, metadata);
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
sharp.metadata(this.options, callback);
|
sharp.metadata(this.options, (err, metadata) => {
|
||||||
|
if (err) {
|
||||||
|
callback(is.nativeError(err, stack));
|
||||||
|
} else {
|
||||||
|
callback(null, metadata);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
} else {
|
} else {
|
||||||
@@ -500,7 +513,7 @@ function metadata (callback) {
|
|||||||
this._flattenBufferIn();
|
this._flattenBufferIn();
|
||||||
sharp.metadata(this.options, (err, metadata) => {
|
sharp.metadata(this.options, (err, metadata) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(is.nativeError(err, stack));
|
||||||
} else {
|
} else {
|
||||||
resolve(metadata);
|
resolve(metadata);
|
||||||
}
|
}
|
||||||
@@ -516,7 +529,7 @@ function metadata (callback) {
|
|||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
sharp.metadata(this.options, (err, metadata) => {
|
sharp.metadata(this.options, (err, metadata) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(is.nativeError(err, stack));
|
||||||
} else {
|
} else {
|
||||||
resolve(metadata);
|
resolve(metadata);
|
||||||
}
|
}
|
||||||
@@ -572,14 +585,27 @@ function metadata (callback) {
|
|||||||
* @returns {Promise<Object>}
|
* @returns {Promise<Object>}
|
||||||
*/
|
*/
|
||||||
function stats (callback) {
|
function stats (callback) {
|
||||||
|
const stack = Error();
|
||||||
if (is.fn(callback)) {
|
if (is.fn(callback)) {
|
||||||
if (this._isStreamInput()) {
|
if (this._isStreamInput()) {
|
||||||
this.on('finish', () => {
|
this.on('finish', () => {
|
||||||
this._flattenBufferIn();
|
this._flattenBufferIn();
|
||||||
sharp.stats(this.options, callback);
|
sharp.stats(this.options, (err, stats) => {
|
||||||
|
if (err) {
|
||||||
|
callback(is.nativeError(err, stack));
|
||||||
|
} else {
|
||||||
|
callback(null, stats);
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
sharp.stats(this.options, callback);
|
sharp.stats(this.options, (err, stats) => {
|
||||||
|
if (err) {
|
||||||
|
callback(is.nativeError(err, stack));
|
||||||
|
} else {
|
||||||
|
callback(null, stats);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
} else {
|
} else {
|
||||||
@@ -589,7 +615,7 @@ function stats (callback) {
|
|||||||
this._flattenBufferIn();
|
this._flattenBufferIn();
|
||||||
sharp.stats(this.options, (err, stats) => {
|
sharp.stats(this.options, (err, stats) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(is.nativeError(err, stack));
|
||||||
} else {
|
} else {
|
||||||
resolve(stats);
|
resolve(stats);
|
||||||
}
|
}
|
||||||
@@ -600,7 +626,7 @@ function stats (callback) {
|
|||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
sharp.stats(this.options, (err, stats) => {
|
sharp.stats(this.options, (err, stats) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(is.nativeError(err, stack));
|
||||||
} else {
|
} else {
|
||||||
resolve(stats);
|
resolve(stats);
|
||||||
}
|
}
|
||||||
|
|||||||
16
lib/is.js
@@ -137,6 +137,19 @@ const invalidParameterError = function (name, expected, actual) {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensures an Error from C++ contains a JS stack.
|
||||||
|
*
|
||||||
|
* @param {Error} native - Error with message from C++.
|
||||||
|
* @param {Error} context - Error with stack from JS.
|
||||||
|
* @returns {Error} Error with message and stack.
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
const nativeError = function (native, context) {
|
||||||
|
context.message = native.message;
|
||||||
|
return context;
|
||||||
|
};
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
defined,
|
defined,
|
||||||
object,
|
object,
|
||||||
@@ -151,5 +164,6 @@ module.exports = {
|
|||||||
integer,
|
integer,
|
||||||
inRange,
|
inRange,
|
||||||
inArray,
|
inArray,
|
||||||
invalidParameterError
|
invalidParameterError,
|
||||||
|
nativeError
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,11 +4,13 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const { spawnSync } = require('node:child_process');
|
const { spawnSync } = require('node:child_process');
|
||||||
|
const { createHash } = require('node:crypto');
|
||||||
const semverCoerce = require('semver/functions/coerce');
|
const semverCoerce = require('semver/functions/coerce');
|
||||||
const semverGreaterThanOrEqualTo = require('semver/functions/gte');
|
const semverGreaterThanOrEqualTo = require('semver/functions/gte');
|
||||||
|
const semverSatisfies = require('semver/functions/satisfies');
|
||||||
const detectLibc = require('detect-libc');
|
const detectLibc = require('detect-libc');
|
||||||
|
|
||||||
const { engines } = require('../package.json');
|
const { engines, optionalDependencies } = require('../package.json');
|
||||||
|
|
||||||
const minimumLibvipsVersionLabelled = process.env.npm_package_config_libvips || /* istanbul ignore next */
|
const minimumLibvipsVersionLabelled = process.env.npm_package_config_libvips || /* istanbul ignore next */
|
||||||
engines.libvips;
|
engines.libvips;
|
||||||
@@ -16,7 +18,7 @@ const minimumLibvipsVersion = semverCoerce(minimumLibvipsVersionLabelled).versio
|
|||||||
|
|
||||||
const prebuiltPlatforms = [
|
const prebuiltPlatforms = [
|
||||||
'darwin-arm64', 'darwin-x64',
|
'darwin-arm64', 'darwin-x64',
|
||||||
'linux-arm', 'linux-arm64', 'linux-x64',
|
'linux-arm', 'linux-arm64', 'linux-s390x', 'linux-x64',
|
||||||
'linuxmusl-arm64', 'linuxmusl-x64',
|
'linuxmusl-arm64', 'linuxmusl-x64',
|
||||||
'win32-ia32', 'win32-x64'
|
'win32-ia32', 'win32-x64'
|
||||||
];
|
];
|
||||||
@@ -41,22 +43,30 @@ const runtimePlatformArch = () => `${process.platform}${runtimeLibc()}-${process
|
|||||||
|
|
||||||
/* istanbul ignore next */
|
/* istanbul ignore next */
|
||||||
const buildPlatformArch = () => {
|
const buildPlatformArch = () => {
|
||||||
|
if (isEmscripten()) {
|
||||||
|
return 'wasm32';
|
||||||
|
}
|
||||||
/* eslint camelcase: ["error", { allow: ["^npm_config_"] }] */
|
/* eslint camelcase: ["error", { allow: ["^npm_config_"] }] */
|
||||||
const { npm_config_arch, npm_config_platform, npm_config_libc } = process.env;
|
const { npm_config_arch, npm_config_platform, npm_config_libc } = process.env;
|
||||||
return `${npm_config_platform || process.platform}${npm_config_libc || runtimeLibc()}-${npm_config_arch || process.arch}`;
|
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 = () => {
|
const buildSharpLibvipsIncludeDir = () => {
|
||||||
try {
|
try {
|
||||||
return require('@sharpen/sharp-libvips-dev/include');
|
return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/include`);
|
||||||
} catch {}
|
} catch {
|
||||||
|
try {
|
||||||
|
return require('@img/sharp-libvips-dev/include');
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
/* istanbul ignore next */
|
/* istanbul ignore next */
|
||||||
return '';
|
return '';
|
||||||
};
|
};
|
||||||
|
|
||||||
const buildSharpLibvipsCPlusPlusDir = () => {
|
const buildSharpLibvipsCPlusPlusDir = () => {
|
||||||
try {
|
try {
|
||||||
return require('@sharpen/sharp-libvips-dev/cplusplus');
|
return require('@img/sharp-libvips-dev/cplusplus');
|
||||||
} catch {}
|
} catch {}
|
||||||
/* istanbul ignore next */
|
/* istanbul ignore next */
|
||||||
return '';
|
return '';
|
||||||
@@ -64,12 +74,31 @@ const buildSharpLibvipsCPlusPlusDir = () => {
|
|||||||
|
|
||||||
const buildSharpLibvipsLibDir = () => {
|
const buildSharpLibvipsLibDir = () => {
|
||||||
try {
|
try {
|
||||||
return require(`@sharpen/sharp-libvips-${buildPlatformArch()}/lib`);
|
return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/lib`);
|
||||||
} catch {}
|
} catch {
|
||||||
|
try {
|
||||||
|
return require(`@img/sharp-libvips-${buildPlatformArch()}/lib`);
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
/* istanbul ignore next */
|
/* istanbul ignore next */
|
||||||
return '';
|
return '';
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const isUnsupportedNodeRuntime = () => {
|
||||||
|
/* istanbul ignore next */
|
||||||
|
if (process.release?.name === 'node' && process.versions) {
|
||||||
|
if (!semverSatisfies(process.versions.node, engines.node)) {
|
||||||
|
return { found: process.versions.node, expected: engines.node };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/* istanbul ignore next */
|
||||||
|
const isEmscripten = () => {
|
||||||
|
const { CC } = process.env;
|
||||||
|
return Boolean(CC && CC.endsWith('/emcc'));
|
||||||
|
};
|
||||||
|
|
||||||
const isRosetta = () => {
|
const isRosetta = () => {
|
||||||
/* istanbul ignore next */
|
/* istanbul ignore next */
|
||||||
if (process.platform === 'darwin' && process.arch === 'x64') {
|
if (process.platform === 'darwin' && process.arch === 'x64') {
|
||||||
@@ -79,9 +108,20 @@ const isRosetta = () => {
|
|||||||
return false;
|
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 */
|
/* istanbul ignore next */
|
||||||
const spawnRebuild = () =>
|
const spawnRebuild = () =>
|
||||||
spawnSync('node-gyp rebuild --directory=src', {
|
spawnSync(`node-gyp rebuild --directory=src ${isEmscripten() ? '--nodedir=emscripten' : ''}`, {
|
||||||
...spawnSyncOptions,
|
...spawnSyncOptions,
|
||||||
stdio: 'inherit'
|
stdio: 'inherit'
|
||||||
}).status;
|
}).status;
|
||||||
@@ -122,15 +162,21 @@ const pkgConfigPath = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const skipSearch = (status, reason) => {
|
||||||
|
log(`Detected ${reason}, skipping search for globally-installed libvips`);
|
||||||
|
return status;
|
||||||
|
};
|
||||||
|
|
||||||
const useGlobalLibvips = () => {
|
const useGlobalLibvips = () => {
|
||||||
if (Boolean(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS) === true) {
|
if (Boolean(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS) === true) {
|
||||||
log('Detected SHARP_IGNORE_GLOBAL_LIBVIPS, skipping search for globally-installed libvips');
|
return skipSearch(false, 'SHARP_IGNORE_GLOBAL_LIBVIPS');
|
||||||
return false;
|
}
|
||||||
|
if (Boolean(process.env.SHARP_FORCE_GLOBAL_LIBVIPS) === true) {
|
||||||
|
return skipSearch(true, 'SHARP_FORCE_GLOBAL_LIBVIPS');
|
||||||
}
|
}
|
||||||
/* istanbul ignore next */
|
/* istanbul ignore next */
|
||||||
if (isRosetta()) {
|
if (isRosetta()) {
|
||||||
log('Detected Rosetta, skipping search for globally-installed libvips');
|
return skipSearch(false, 'Rosetta');
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
const globalVipsVersion = globalLibvipsVersion();
|
const globalVipsVersion = globalLibvipsVersion();
|
||||||
return !!globalVipsVersion && /* istanbul ignore next */
|
return !!globalVipsVersion && /* istanbul ignore next */
|
||||||
@@ -144,8 +190,10 @@ module.exports = {
|
|||||||
buildSharpLibvipsIncludeDir,
|
buildSharpLibvipsIncludeDir,
|
||||||
buildSharpLibvipsCPlusPlusDir,
|
buildSharpLibvipsCPlusPlusDir,
|
||||||
buildSharpLibvipsLibDir,
|
buildSharpLibvipsLibDir,
|
||||||
|
isUnsupportedNodeRuntime,
|
||||||
runtimePlatformArch,
|
runtimePlatformArch,
|
||||||
log,
|
log,
|
||||||
|
yarnLocator,
|
||||||
spawnRebuild,
|
spawnRebuild,
|
||||||
globalLibvipsVersion,
|
globalLibvipsVersion,
|
||||||
pkgConfigPath,
|
pkgConfigPath,
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ const is = require('./is');
|
|||||||
* Only one rotation can occur per pipeline.
|
* Only one rotation can occur per pipeline.
|
||||||
* Previous calls to `rotate` in the same pipeline will be ignored.
|
* Previous calls to `rotate` in the same pipeline will be ignored.
|
||||||
*
|
*
|
||||||
|
* Multi-page images can only be rotated by 180 degrees.
|
||||||
|
*
|
||||||
* Method order is important when rotating, resizing and/or extracting regions,
|
* Method order is important when rotating, resizing and/or extracting regions,
|
||||||
* for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.
|
* for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.
|
||||||
*
|
*
|
||||||
|
|||||||
299
lib/output.js
@@ -86,7 +86,8 @@ function toFile (fileOut, callback) {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
this.options.fileOut = fileOut;
|
this.options.fileOut = fileOut;
|
||||||
return this._pipeline(callback);
|
const stack = Error();
|
||||||
|
return this._pipeline(callback, stack);
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
@@ -157,43 +158,190 @@ function toBuffer (options, callback) {
|
|||||||
this.options.resolveWithObject = false;
|
this.options.resolveWithObject = false;
|
||||||
}
|
}
|
||||||
this.options.fileOut = '';
|
this.options.fileOut = '';
|
||||||
return this._pipeline(is.fn(options) ? options : callback);
|
const stack = Error();
|
||||||
|
return this._pipeline(is.fn(options) ? options : callback, stack);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Include all metadata (EXIF, XMP, IPTC) from the input image in the output image.
|
* Keep all EXIF metadata from the input image in the output image.
|
||||||
* This will also convert to and add a web-friendly sRGB ICC profile if appropriate,
|
|
||||||
* unless a custom output profile is provided.
|
|
||||||
*
|
|
||||||
* The default behaviour, when `withMetadata` is not used, is to convert to the device-independent
|
|
||||||
* sRGB colour space and strip all metadata, including the removal of any ICC profile.
|
|
||||||
*
|
*
|
||||||
* EXIF metadata is unsupported for TIFF output.
|
* EXIF metadata is unsupported for TIFF output.
|
||||||
*
|
*
|
||||||
* @example
|
* @since 0.33.0
|
||||||
* sharp('input.jpg')
|
|
||||||
* .withMetadata()
|
|
||||||
* .toFile('output-with-metadata.jpg')
|
|
||||||
* .then(info => { ... });
|
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* // Set output EXIF metadata
|
* const outputWithExif = await sharp(inputWithExif)
|
||||||
* const data = await sharp(input)
|
* .keepExif()
|
||||||
* .withMetadata({
|
* .toBuffer();
|
||||||
* exif: {
|
*
|
||||||
* IFD0: {
|
* @returns {Sharp}
|
||||||
* Copyright: 'The National Gallery'
|
*/
|
||||||
* },
|
function keepExif () {
|
||||||
* IFD3: {
|
this.options.keepMetadata |= 0b00001;
|
||||||
* GPSLatitudeRef: 'N',
|
return this;
|
||||||
* GPSLatitude: '51/1 30/1 3230/100',
|
}
|
||||||
* GPSLongitudeRef: 'W',
|
|
||||||
* GPSLongitude: '0/1 7/1 4366/100'
|
/**
|
||||||
* }
|
* Set EXIF metadata in the output image, ignoring any EXIF in the input image.
|
||||||
|
*
|
||||||
|
* @since 0.33.0
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const dataWithExif = await sharp(input)
|
||||||
|
* .withExif({
|
||||||
|
* IFD0: {
|
||||||
|
* Copyright: 'The National Gallery'
|
||||||
|
* },
|
||||||
|
* IFD3: {
|
||||||
|
* GPSLatitudeRef: 'N',
|
||||||
|
* GPSLatitude: '51/1 30/1 3230/100',
|
||||||
|
* GPSLongitudeRef: 'W',
|
||||||
|
* GPSLongitude: '0/1 7/1 4366/100'
|
||||||
* }
|
* }
|
||||||
* })
|
* })
|
||||||
* .toBuffer();
|
* .toBuffer();
|
||||||
*
|
*
|
||||||
|
* @param {Object<string, Object<string, string>>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.
|
||||||
|
* @returns {Sharp}
|
||||||
|
* @throws {Error} Invalid parameters
|
||||||
|
*/
|
||||||
|
function withExif (exif) {
|
||||||
|
if (is.object(exif)) {
|
||||||
|
for (const [ifd, entries] of Object.entries(exif)) {
|
||||||
|
if (is.object(entries)) {
|
||||||
|
for (const [k, v] of Object.entries(entries)) {
|
||||||
|
if (is.string(v)) {
|
||||||
|
this.options.withExif[`exif-${ifd.toLowerCase()}-${k}`] = v;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError(`${ifd}.${k}`, 'string', v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError(ifd, 'object', entries);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('exif', 'object', exif);
|
||||||
|
}
|
||||||
|
this.options.withExifMerge = false;
|
||||||
|
return this.keepExif();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update EXIF metadata from the input image in the output image.
|
||||||
|
*
|
||||||
|
* @since 0.33.0
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const dataWithMergedExif = await sharp(inputWithExif)
|
||||||
|
* .withExifMerge({
|
||||||
|
* IFD0: {
|
||||||
|
* Copyright: 'The National Gallery'
|
||||||
|
* }
|
||||||
|
* })
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
|
* @param {Object<string, Object<string, string>>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.
|
||||||
|
* @returns {Sharp}
|
||||||
|
* @throws {Error} Invalid parameters
|
||||||
|
*/
|
||||||
|
function withExifMerge (exif) {
|
||||||
|
this.withExif(exif);
|
||||||
|
this.options.withExifMerge = true;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep ICC profile from the input image in the output image.
|
||||||
|
*
|
||||||
|
* Where necessary, will attempt to convert the output colour space to match the profile.
|
||||||
|
*
|
||||||
|
* @since 0.33.0
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const outputWithIccProfile = await sharp(inputWithIccProfile)
|
||||||
|
* .keepIccProfile()
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
|
* @returns {Sharp}
|
||||||
|
*/
|
||||||
|
function keepIccProfile () {
|
||||||
|
this.options.keepMetadata |= 0b01000;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transform using an ICC profile and attach to the output image.
|
||||||
|
*
|
||||||
|
* This can either be an absolute filesystem path or
|
||||||
|
* built-in profile name (`srgb`, `p3`, `cmyk`).
|
||||||
|
*
|
||||||
|
* @since 0.33.0
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const outputWithP3 = await sharp(input)
|
||||||
|
* .withIccProfile('p3')
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
|
* @param {string} icc - Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk).
|
||||||
|
* @param {Object} [options]
|
||||||
|
* @param {number} [options.attach=true] Should the ICC profile be included in the output image metadata?
|
||||||
|
* @returns {Sharp}
|
||||||
|
* @throws {Error} Invalid parameters
|
||||||
|
*/
|
||||||
|
function withIccProfile (icc, options) {
|
||||||
|
if (is.string(icc)) {
|
||||||
|
this.options.withIccProfile = icc;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('icc', 'string', icc);
|
||||||
|
}
|
||||||
|
this.keepIccProfile();
|
||||||
|
if (is.object(options)) {
|
||||||
|
if (is.defined(options.attach)) {
|
||||||
|
if (is.bool(options.attach)) {
|
||||||
|
if (!options.attach) {
|
||||||
|
this.options.keepMetadata &= ~0b01000;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('attach', 'boolean', options.attach);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image.
|
||||||
|
*
|
||||||
|
* The default behaviour, when `keepMetadata` is not used, is to convert to the device-independent
|
||||||
|
* sRGB colour space and strip all metadata, including the removal of any ICC profile.
|
||||||
|
*
|
||||||
|
* @since 0.33.0
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const outputWithMetadata = await sharp(inputWithMetadata)
|
||||||
|
* .keepMetadata()
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
|
* @returns {Sharp}
|
||||||
|
*/
|
||||||
|
function keepMetadata () {
|
||||||
|
this.options.keepMetadata = 0b11111;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep most metadata (EXIF, XMP, IPTC) from the input image in the output image.
|
||||||
|
*
|
||||||
|
* This will also convert to and add a web-friendly sRGB ICC profile if appropriate.
|
||||||
|
*
|
||||||
|
* Allows orientation and density to be set or updated.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const outputSrgbWithMetadata = await sharp(inputRgbWithMetadata)
|
||||||
|
* .withMetadata()
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
* @example
|
* @example
|
||||||
* // Set output metadata to 96 DPI
|
* // Set output metadata to 96 DPI
|
||||||
* const data = await sharp(input)
|
* const data = await sharp(input)
|
||||||
@@ -201,15 +349,14 @@ function toBuffer (options, callback) {
|
|||||||
* .toBuffer();
|
* .toBuffer();
|
||||||
*
|
*
|
||||||
* @param {Object} [options]
|
* @param {Object} [options]
|
||||||
* @param {number} [options.orientation] value between 1 and 8, used to update the EXIF `Orientation` tag.
|
* @param {number} [options.orientation] Used to update the EXIF `Orientation` tag, integer between 1 and 8.
|
||||||
* @param {string} [options.icc='srgb'] Filesystem path to output ICC profile, relative to `process.cwd()`, defaults to built-in sRGB.
|
|
||||||
* @param {Object<Object>} [options.exif={}] Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.
|
|
||||||
* @param {number} [options.density] Number of pixels per inch (DPI).
|
* @param {number} [options.density] Number of pixels per inch (DPI).
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid parameters
|
* @throws {Error} Invalid parameters
|
||||||
*/
|
*/
|
||||||
function withMetadata (options) {
|
function withMetadata (options) {
|
||||||
this.options.withMetadata = is.bool(options) ? options : true;
|
this.keepMetadata();
|
||||||
|
this.withIccProfile('srgb');
|
||||||
if (is.object(options)) {
|
if (is.object(options)) {
|
||||||
if (is.defined(options.orientation)) {
|
if (is.defined(options.orientation)) {
|
||||||
if (is.integer(options.orientation) && is.inRange(options.orientation, 1, 8)) {
|
if (is.integer(options.orientation) && is.inRange(options.orientation, 1, 8)) {
|
||||||
@@ -226,30 +373,10 @@ function withMetadata (options) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (is.defined(options.icc)) {
|
if (is.defined(options.icc)) {
|
||||||
if (is.string(options.icc)) {
|
this.withIccProfile(options.icc);
|
||||||
this.options.withMetadataIcc = options.icc;
|
|
||||||
} else {
|
|
||||||
throw is.invalidParameterError('icc', 'string filesystem path to ICC profile', options.icc);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (is.defined(options.exif)) {
|
if (is.defined(options.exif)) {
|
||||||
if (is.object(options.exif)) {
|
this.withExifMerge(options.exif);
|
||||||
for (const [ifd, entries] of Object.entries(options.exif)) {
|
|
||||||
if (is.object(entries)) {
|
|
||||||
for (const [k, v] of Object.entries(entries)) {
|
|
||||||
if (is.string(v)) {
|
|
||||||
this.options.withMetadataStrs[`exif-${ifd.toLowerCase()}-${k}`] = v;
|
|
||||||
} else {
|
|
||||||
throw is.invalidParameterError(`exif.${ifd}.${k}`, 'string', v);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
throw is.invalidParameterError(`exif.${ifd}`, 'object', entries);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
throw is.invalidParameterError('exif', 'object', options.exif);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
@@ -377,10 +504,14 @@ function jpeg (options) {
|
|||||||
/**
|
/**
|
||||||
* Use these PNG options for output image.
|
* Use these PNG options for output image.
|
||||||
*
|
*
|
||||||
* By default, PNG output is full colour at 8 or 16 bits per pixel.
|
* By default, PNG output is full colour at 8 bits per pixel.
|
||||||
|
*
|
||||||
* Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel.
|
* Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel.
|
||||||
* Set `palette` to `true` for slower, indexed PNG output.
|
* Set `palette` to `true` for slower, indexed PNG output.
|
||||||
*
|
*
|
||||||
|
* For 16 bits per pixel output, convert to `rgb16` via
|
||||||
|
* {@link /api-colour#tocolourspace|toColourspace}.
|
||||||
|
*
|
||||||
* @example
|
* @example
|
||||||
* // Convert any input to full colour PNG output
|
* // Convert any input to full colour PNG output
|
||||||
* const data = await sharp(input)
|
* const data = await sharp(input)
|
||||||
@@ -393,6 +524,13 @@ function jpeg (options) {
|
|||||||
* .png({ palette: true })
|
* .png({ palette: true })
|
||||||
* .toBuffer();
|
* .toBuffer();
|
||||||
*
|
*
|
||||||
|
* @example
|
||||||
|
* // Output 16 bits per pixel RGB(A)
|
||||||
|
* const data = await sharp(input)
|
||||||
|
* .toColourspace('rgb16')
|
||||||
|
* .png()
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
* @param {Object} [options]
|
* @param {Object} [options]
|
||||||
* @param {boolean} [options.progressive=false] - use progressive (interlace) scan
|
* @param {boolean} [options.progressive=false] - use progressive (interlace) scan
|
||||||
* @param {number} [options.compressionLevel=6] - zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest)
|
* @param {number} [options.compressionLevel=6] - zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest)
|
||||||
@@ -780,6 +918,7 @@ function trySetAnimationOptions (source, target) {
|
|||||||
* @param {number} [options.yres=1.0] - vertical resolution in pixels/mm
|
* @param {number} [options.yres=1.0] - vertical resolution in pixels/mm
|
||||||
* @param {string} [options.resolutionUnit='inch'] - resolution unit options: inch, cm
|
* @param {string} [options.resolutionUnit='inch'] - resolution unit options: inch, cm
|
||||||
* @param {number} [options.bitdepth=8] - reduce bitdepth to 1, 2 or 4 bit
|
* @param {number} [options.bitdepth=8] - reduce bitdepth to 1, 2 or 4 bit
|
||||||
|
* @param {boolean} [options.miniswhite=false] - write 1-bit images as miniswhite
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid options
|
* @throws {Error} Invalid options
|
||||||
*/
|
*/
|
||||||
@@ -817,6 +956,10 @@ function tiff (options) {
|
|||||||
throw is.invalidParameterError('tileHeight', 'integer greater than zero', options.tileHeight);
|
throw is.invalidParameterError('tileHeight', 'integer greater than zero', options.tileHeight);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// miniswhite
|
||||||
|
if (is.defined(options.miniswhite)) {
|
||||||
|
this._setBooleanOption('tiffMiniswhite', options.miniswhite);
|
||||||
|
}
|
||||||
// pyramid
|
// pyramid
|
||||||
if (is.defined(options.pyramid)) {
|
if (is.defined(options.pyramid)) {
|
||||||
this._setBooleanOption('tiffPyramid', options.pyramid);
|
this._setBooleanOption('tiffPyramid', options.pyramid);
|
||||||
@@ -868,6 +1011,7 @@ function tiff (options) {
|
|||||||
* Use these AVIF options for output image.
|
* Use these AVIF options for output image.
|
||||||
*
|
*
|
||||||
* AVIF image sequences are not supported.
|
* AVIF image sequences are not supported.
|
||||||
|
* Prebuilt binaries support a bitdepth of 8 only.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* const data = await sharp(input)
|
* const data = await sharp(input)
|
||||||
@@ -886,6 +1030,7 @@ function tiff (options) {
|
|||||||
* @param {boolean} [options.lossless=false] - use lossless compression
|
* @param {boolean} [options.lossless=false] - use lossless compression
|
||||||
* @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest)
|
* @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest)
|
||||||
* @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling
|
* @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling
|
||||||
|
* @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid options
|
* @throws {Error} Invalid options
|
||||||
*/
|
*/
|
||||||
@@ -912,6 +1057,7 @@ function avif (options) {
|
|||||||
* @param {boolean} [options.lossless=false] - use lossless compression
|
* @param {boolean} [options.lossless=false] - use lossless compression
|
||||||
* @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest)
|
* @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest)
|
||||||
* @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling
|
* @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling
|
||||||
|
* @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid options
|
* @throws {Error} Invalid options
|
||||||
*/
|
*/
|
||||||
@@ -950,6 +1096,16 @@ function heif (options) {
|
|||||||
throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);
|
throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (is.defined(options.bitdepth)) {
|
||||||
|
if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [8, 10, 12])) {
|
||||||
|
if (options.bitdepth !== 8 && this.constructor.versions.heif) {
|
||||||
|
throw is.invalidParameterError('bitdepth when using prebuilt binaries', 8, options.bitdepth);
|
||||||
|
}
|
||||||
|
this.options.heifBitdepth = options.bitdepth;
|
||||||
|
} else {
|
||||||
|
throw is.invalidParameterError('bitdepth', '8, 10 or 12', options.bitdepth);
|
||||||
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
throw is.invalidParameterError('options', 'Object', options);
|
throw is.invalidParameterError('options', 'Object', options);
|
||||||
}
|
}
|
||||||
@@ -1101,7 +1257,7 @@ function raw (options) {
|
|||||||
* @param {number} [options.angle=0] tile angle of rotation, must be a multiple of 90.
|
* @param {number} [options.angle=0] tile angle of rotation, must be a multiple of 90.
|
||||||
* @param {string|Object} [options.background={r: 255, g: 255, b: 255, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to white without transparency.
|
* @param {string|Object} [options.background={r: 255, g: 255, b: 255, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to white without transparency.
|
||||||
* @param {string} [options.depth] how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout.
|
* @param {string} [options.depth] how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout.
|
||||||
* @param {number} [options.skipBlanks=-1] threshold to skip tile generation, a value 0 - 255 for 8-bit images or 0 - 65535 for 16-bit images
|
* @param {number} [options.skipBlanks=-1] Threshold to skip tile generation. Range is 0-255 for 8-bit images, 0-65535 for 16-bit images. Default is 5 for `google` layout, -1 (no skip) otherwise.
|
||||||
* @param {string} [options.container='fs'] tile container, with value `fs` (filesystem) or `zip` (compressed file).
|
* @param {string} [options.container='fs'] tile container, with value `fs` (filesystem) or `zip` (compressed file).
|
||||||
* @param {string} [options.layout='dz'] filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`.
|
* @param {string} [options.layout='dz'] filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`.
|
||||||
* @param {boolean} [options.centre=false] centre image in tile.
|
* @param {boolean} [options.centre=false] centre image in tile.
|
||||||
@@ -1282,7 +1438,8 @@ function _read () {
|
|||||||
/* istanbul ignore else */
|
/* istanbul ignore else */
|
||||||
if (!this.options.streamOut) {
|
if (!this.options.streamOut) {
|
||||||
this.options.streamOut = true;
|
this.options.streamOut = true;
|
||||||
this._pipeline();
|
const stack = Error();
|
||||||
|
this._pipeline(undefined, stack);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1291,18 +1448,30 @@ function _read () {
|
|||||||
* Supports callback, stream and promise variants
|
* Supports callback, stream and promise variants
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
function _pipeline (callback) {
|
function _pipeline (callback, stack) {
|
||||||
if (typeof callback === 'function') {
|
if (typeof callback === 'function') {
|
||||||
// output=file/buffer
|
// output=file/buffer
|
||||||
if (this._isStreamInput()) {
|
if (this._isStreamInput()) {
|
||||||
// output=file/buffer, input=stream
|
// output=file/buffer, input=stream
|
||||||
this.on('finish', () => {
|
this.on('finish', () => {
|
||||||
this._flattenBufferIn();
|
this._flattenBufferIn();
|
||||||
sharp.pipeline(this.options, callback);
|
sharp.pipeline(this.options, (err, data, info) => {
|
||||||
|
if (err) {
|
||||||
|
callback(is.nativeError(err, stack));
|
||||||
|
} else {
|
||||||
|
callback(null, data, info);
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// output=file/buffer, input=file/buffer
|
// output=file/buffer, input=file/buffer
|
||||||
sharp.pipeline(this.options, callback);
|
sharp.pipeline(this.options, (err, data, info) => {
|
||||||
|
if (err) {
|
||||||
|
callback(is.nativeError(err, stack));
|
||||||
|
} else {
|
||||||
|
callback(null, data, info);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
} else if (this.options.streamOut) {
|
} else if (this.options.streamOut) {
|
||||||
@@ -1313,7 +1482,7 @@ function _pipeline (callback) {
|
|||||||
this._flattenBufferIn();
|
this._flattenBufferIn();
|
||||||
sharp.pipeline(this.options, (err, data, info) => {
|
sharp.pipeline(this.options, (err, data, info) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
this.emit('error', err);
|
this.emit('error', is.nativeError(err, stack));
|
||||||
} else {
|
} else {
|
||||||
this.emit('info', info);
|
this.emit('info', info);
|
||||||
this.push(data);
|
this.push(data);
|
||||||
@@ -1329,7 +1498,7 @@ function _pipeline (callback) {
|
|||||||
// output=stream, input=file/buffer
|
// output=stream, input=file/buffer
|
||||||
sharp.pipeline(this.options, (err, data, info) => {
|
sharp.pipeline(this.options, (err, data, info) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
this.emit('error', err);
|
this.emit('error', is.nativeError(err, stack));
|
||||||
} else {
|
} else {
|
||||||
this.emit('info', info);
|
this.emit('info', info);
|
||||||
this.push(data);
|
this.push(data);
|
||||||
@@ -1348,7 +1517,7 @@ function _pipeline (callback) {
|
|||||||
this._flattenBufferIn();
|
this._flattenBufferIn();
|
||||||
sharp.pipeline(this.options, (err, data, info) => {
|
sharp.pipeline(this.options, (err, data, info) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(is.nativeError(err, stack));
|
||||||
} else {
|
} else {
|
||||||
if (this.options.resolveWithObject) {
|
if (this.options.resolveWithObject) {
|
||||||
resolve({ data, info });
|
resolve({ data, info });
|
||||||
@@ -1364,7 +1533,7 @@ function _pipeline (callback) {
|
|||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
sharp.pipeline(this.options, (err, data, info) => {
|
sharp.pipeline(this.options, (err, data, info) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(is.nativeError(err, stack));
|
||||||
} else {
|
} else {
|
||||||
if (this.options.resolveWithObject) {
|
if (this.options.resolveWithObject) {
|
||||||
resolve({ data, info });
|
resolve({ data, info });
|
||||||
@@ -1387,6 +1556,12 @@ module.exports = function (Sharp) {
|
|||||||
// Public
|
// Public
|
||||||
toFile,
|
toFile,
|
||||||
toBuffer,
|
toBuffer,
|
||||||
|
keepExif,
|
||||||
|
withExif,
|
||||||
|
withExifMerge,
|
||||||
|
keepIccProfile,
|
||||||
|
withIccProfile,
|
||||||
|
keepMetadata,
|
||||||
withMetadata,
|
withMetadata,
|
||||||
toFormat,
|
toFormat,
|
||||||
jpeg,
|
jpeg,
|
||||||
|
|||||||
@@ -68,6 +68,7 @@ const strategy = {
|
|||||||
*/
|
*/
|
||||||
const kernel = {
|
const kernel = {
|
||||||
nearest: 'nearest',
|
nearest: 'nearest',
|
||||||
|
linear: 'linear',
|
||||||
cubic: 'cubic',
|
cubic: 'cubic',
|
||||||
mitchell: 'mitchell',
|
mitchell: 'mitchell',
|
||||||
lanczos2: 'lanczos2',
|
lanczos2: 'lanczos2',
|
||||||
@@ -135,18 +136,22 @@ function isResizeExpected (options) {
|
|||||||
*
|
*
|
||||||
* Some of these values are based on the [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS property.
|
* Some of these values are based on the [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS property.
|
||||||
*
|
*
|
||||||
* The experimental strategy-based approach resizes so one dimension is at its target length
|
* The strategy-based approach initially resizes so one dimension is at its target length
|
||||||
* then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.
|
* then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.
|
||||||
* - `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29).
|
* - `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29).
|
||||||
* - `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
|
* - `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
|
||||||
*
|
*
|
||||||
* Possible interpolation kernels are:
|
* Possible downsizing kernels are:
|
||||||
* - `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation).
|
* - `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation).
|
||||||
|
* - `linear`: Use a [triangle filter](https://en.wikipedia.org/wiki/Triangular_function).
|
||||||
* - `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline).
|
* - `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline).
|
||||||
* - `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf).
|
* - `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf).
|
||||||
* - `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`.
|
* - `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`.
|
||||||
* - `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
|
* - `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
|
||||||
*
|
*
|
||||||
|
* When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators.
|
||||||
|
* Downsampling kernels without a matching upsampling interpolator map to `cubic`.
|
||||||
|
*
|
||||||
* Only one resize can occur per pipeline.
|
* Only one resize can occur per pipeline.
|
||||||
* Previous calls to `resize` in the same pipeline will be ignored.
|
* Previous calls to `resize` in the same pipeline will be ignored.
|
||||||
*
|
*
|
||||||
@@ -239,7 +244,7 @@ function isResizeExpected (options) {
|
|||||||
* @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.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} [options.position='centre'] - A position, gravity or strategy to use when `fit` is `cover` or `contain`.
|
||||||
* @param {String|Object} [options.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency.
|
* @param {String|Object} [options.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency.
|
||||||
* @param {String} [options.kernel='lanczos3'] - The kernel to use for image reduction. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load.
|
* @param {String} [options.kernel='lanczos3'] - The kernel to use for image reduction and the inferred interpolator to use for upsampling. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load.
|
||||||
* @param {Boolean} [options.withoutEnlargement=false] - Do not scale up if the width *or* height are already less than the target dimensions, equivalent to GraphicsMagick's `>` geometry option. This may result in output dimensions smaller than the target dimensions.
|
* @param {Boolean} [options.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.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.
|
* @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.
|
||||||
@@ -494,70 +499,67 @@ function extract (options) {
|
|||||||
*
|
*
|
||||||
* If the result of this operation would trim an image to nothing then no change is made.
|
* If the result of this operation would trim an image to nothing then no change is made.
|
||||||
*
|
*
|
||||||
* The `info` response Object, obtained from callback of `.toFile()` or `.toBuffer()`,
|
* The `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` properties.
|
||||||
* will contain `trimOffsetLeft` and `trimOffsetTop` properties.
|
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* // Trim pixels with a colour similar to that of the top-left pixel.
|
* // Trim pixels with a colour similar to that of the top-left pixel.
|
||||||
* sharp(input)
|
* await sharp(input)
|
||||||
* .trim()
|
* .trim()
|
||||||
* .toFile(output, function(err, info) {
|
* .toFile(output);
|
||||||
* ...
|
*
|
||||||
* });
|
|
||||||
* @example
|
* @example
|
||||||
* // Trim pixels with the exact same colour as that of the top-left pixel.
|
* // Trim pixels with the exact same colour as that of the top-left pixel.
|
||||||
* sharp(input)
|
* await sharp(input)
|
||||||
* .trim(0)
|
* .trim({
|
||||||
* .toFile(output, function(err, info) {
|
* threshold: 0
|
||||||
* ...
|
* })
|
||||||
* });
|
* .toFile(output);
|
||||||
|
*
|
||||||
* @example
|
* @example
|
||||||
* // Trim only pixels with a similar colour to red.
|
* // Assume input is line art and trim only pixels with a similar colour to red.
|
||||||
* sharp(input)
|
* const output = await sharp(input)
|
||||||
* .trim("#FF0000")
|
* .trim({
|
||||||
* .toFile(output, function(err, info) {
|
* background: "#FF0000",
|
||||||
* ...
|
* lineArt: true
|
||||||
* });
|
* })
|
||||||
|
* .toBuffer();
|
||||||
|
*
|
||||||
* @example
|
* @example
|
||||||
* // Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
|
* // Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
|
||||||
* sharp(input)
|
* const output = await sharp(input)
|
||||||
* .trim({
|
* .trim({
|
||||||
* background: "yellow",
|
* background: "yellow",
|
||||||
* threshold: 42,
|
* threshold: 42,
|
||||||
* })
|
* })
|
||||||
* .toFile(output, function(err, info) {
|
* .toBuffer();
|
||||||
* ...
|
|
||||||
* });
|
|
||||||
*
|
*
|
||||||
* @param {string|number|Object} trim - the specific background colour to trim, the threshold for doing so or an Object with both.
|
* @param {Object} [options]
|
||||||
* @param {string|Object} [trim.background='top-left pixel'] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel.
|
* @param {string|Object} [options.background='top-left pixel'] - Background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel.
|
||||||
* @param {number} [trim.threshold=10] - the allowed difference from the above colour, a positive number.
|
* @param {number} [options.threshold=10] - Allowed difference from the above colour, a positive number.
|
||||||
|
* @param {boolean} [options.lineArt=false] - Does the input more closely resemble line art (e.g. vector) rather than being photographic?
|
||||||
* @returns {Sharp}
|
* @returns {Sharp}
|
||||||
* @throws {Error} Invalid parameters
|
* @throws {Error} Invalid parameters
|
||||||
*/
|
*/
|
||||||
function trim (trim) {
|
function trim (options) {
|
||||||
if (!is.defined(trim)) {
|
this.options.trimThreshold = 10;
|
||||||
this.options.trimThreshold = 10;
|
if (is.defined(options)) {
|
||||||
} else if (is.string(trim)) {
|
if (is.object(options)) {
|
||||||
this._setBackgroundColourOption('trimBackground', trim);
|
if (is.defined(options.background)) {
|
||||||
this.options.trimThreshold = 10;
|
this._setBackgroundColourOption('trimBackground', options.background);
|
||||||
} else if (is.number(trim)) {
|
}
|
||||||
if (trim >= 0) {
|
if (is.defined(options.threshold)) {
|
||||||
this.options.trimThreshold = trim;
|
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 {
|
} else {
|
||||||
throw is.invalidParameterError('threshold', 'positive number', trim);
|
throw is.invalidParameterError('trim', 'object', options);
|
||||||
}
|
}
|
||||||
} else if (is.object(trim)) {
|
|
||||||
this._setBackgroundColourOption('trimBackground', trim.background);
|
|
||||||
if (!is.defined(trim.threshold)) {
|
|
||||||
this.options.trimThreshold = 10;
|
|
||||||
} else if (is.number(trim.threshold) && trim.threshold >= 0) {
|
|
||||||
this.options.trimThreshold = trim.threshold;
|
|
||||||
} else {
|
|
||||||
throw is.invalidParameterError('threshold', 'positive number', trim);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
throw is.invalidParameterError('trim', 'string, number or object', trim);
|
|
||||||
}
|
}
|
||||||
if (isRotationExpected(this.options)) {
|
if (isRotationExpected(this.options)) {
|
||||||
this.options.rotateBeforePreExtract = true;
|
this.options.rotateBeforePreExtract = true;
|
||||||
|
|||||||
156
lib/sharp.js
@@ -7,63 +7,109 @@
|
|||||||
|
|
||||||
const { familySync, versionSync } = require('detect-libc');
|
const { familySync, versionSync } = require('detect-libc');
|
||||||
|
|
||||||
const { runtimePlatformArch, prebuiltPlatforms, minimumLibvipsVersion } = require('./libvips');
|
const { runtimePlatformArch, isUnsupportedNodeRuntime, prebuiltPlatforms, minimumLibvipsVersion } = require('./libvips');
|
||||||
const runtimePlatform = runtimePlatformArch();
|
const runtimePlatform = runtimePlatformArch();
|
||||||
const [isLinux, isMacOs, isWindows] = ['linux', 'darwin', 'win32'].map(os => runtimePlatform.startsWith(os));
|
|
||||||
|
|
||||||
/* istanbul ignore next */
|
const paths = [
|
||||||
try {
|
`../src/build/Release/sharp-${runtimePlatform}.node`,
|
||||||
// Check for local build
|
'../src/build/Release/sharp-wasm32.node',
|
||||||
module.exports = require(`../src/build/Release/sharp-${runtimePlatform}.node`);
|
`@img/sharp-${runtimePlatform}/sharp.node`,
|
||||||
} catch (errLocal) {
|
'@img/sharp-wasm32/sharp.node'
|
||||||
|
];
|
||||||
|
|
||||||
|
let sharp;
|
||||||
|
const errors = [];
|
||||||
|
for (const path of paths) {
|
||||||
try {
|
try {
|
||||||
// Check for runtime package
|
sharp = require(path);
|
||||||
module.exports = require(`@sharpen/sharp-${runtimePlatform}/sharp.node`);
|
break;
|
||||||
} catch (errPackage) {
|
} catch (err) {
|
||||||
const help = ['Could not load the "sharp" module at runtime'];
|
/* istanbul ignore next */
|
||||||
if (errLocal.code !== 'MODULE_NOT_FOUND') {
|
errors.push(err);
|
||||||
help.push(`${errLocal.code}: ${errLocal.message}`);
|
|
||||||
}
|
|
||||||
if (errPackage.code !== 'MODULE_NOT_FOUND') {
|
|
||||||
help.push(`${errPackage.code}: ${errPackage.message}`);
|
|
||||||
}
|
|
||||||
help.push('Possible solutions:');
|
|
||||||
// Common error messages
|
|
||||||
if (prebuiltPlatforms.includes(runtimePlatform)) {
|
|
||||||
help.push('- Add an explicit dependency for the runtime platform:');
|
|
||||||
help.push(` npm install --force @sharpen/sharp-${runtimePlatform}"`);
|
|
||||||
} else {
|
|
||||||
help.push(`- The ${runtimePlatform} platform requires manual installation of libvips >= ${minimumLibvipsVersion}`);
|
|
||||||
}
|
|
||||||
if (isLinux && /symbol not found/i.test(errPackage)) {
|
|
||||||
try {
|
|
||||||
const { engines } = require(`@sharpen/sharp-libvips-${runtimePlatform}/package`);
|
|
||||||
const libcFound = `${familySync()} ${versionSync()}`;
|
|
||||||
const libcRequires = `${engines.musl ? 'musl' : 'glibc'} ${engines.musl || engines.glibc}`;
|
|
||||||
help.push('- Update your OS:');
|
|
||||||
help.push(` Found ${libcFound}`);
|
|
||||||
help.push(` Requires ${libcRequires}`);
|
|
||||||
} catch (errEngines) {}
|
|
||||||
}
|
|
||||||
if (isMacOs && /Incompatible library version/.test(errLocal.message)) {
|
|
||||||
help.push('- Update Homebrew:');
|
|
||||||
help.push(' brew update && brew upgrade vips');
|
|
||||||
}
|
|
||||||
if (errPackage.code === 'ERR_DLOPEN_DISABLED') {
|
|
||||||
help.push('- Run Node.js without using the --no-addons flag');
|
|
||||||
}
|
|
||||||
if (process.versions.pnp) {
|
|
||||||
help.push('- Use a supported yarn linker, either pnpm or node-modules:');
|
|
||||||
help.push(' yarn config set nodeLinker node-modules');
|
|
||||||
}
|
|
||||||
// Link to installation docs
|
|
||||||
if (isLinux && /Module did not self-register/.test(errLocal.message + errPackage.message)) {
|
|
||||||
help.push('- Using worker threads on Linux? See https://sharp.pixelplumbing.com/install#worker-threads');
|
|
||||||
} else if (isWindows && /The specified procedure could not be found/.test(errPackage.message)) {
|
|
||||||
help.push('- Using the canvas package on Windows? See https://sharp.pixelplumbing.com/install#canvas-and-windows');
|
|
||||||
} else {
|
|
||||||
help.push('- Consult the installation documentation: https://sharp.pixelplumbing.com/install');
|
|
||||||
}
|
|
||||||
throw new Error(help.join('\n'));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 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'));
|
||||||
|
}
|
||||||
|
|||||||
@@ -59,11 +59,17 @@ let versions = {
|
|||||||
};
|
};
|
||||||
/* istanbul ignore next */
|
/* istanbul ignore next */
|
||||||
if (!libvipsVersion.isGlobal) {
|
if (!libvipsVersion.isGlobal) {
|
||||||
try {
|
if (!libvipsVersion.isWasm) {
|
||||||
versions = require(`@sharpen/sharp-${runtimePlatform}/versions`);
|
|
||||||
} catch (_) {
|
|
||||||
try {
|
try {
|
||||||
versions = require(`@sharpen/sharp-libvips-${runtimePlatform}/versions`);
|
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 (_) {}
|
} catch (_) {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -147,6 +153,9 @@ function concurrency (concurrency) {
|
|||||||
if (detectLibc.familySync() === detectLibc.GLIBC && !sharp._isUsingJemalloc()) {
|
if (detectLibc.familySync() === detectLibc.GLIBC && !sharp._isUsingJemalloc()) {
|
||||||
// Reduce default concurrency to 1 when using glibc memory allocator
|
// Reduce default concurrency to 1 when using glibc memory allocator
|
||||||
sharp.concurrency(1);
|
sharp.concurrency(1);
|
||||||
|
} else if (detectLibc.familySync() === detectLibc.MUSL && sharp.concurrency() === 1024) {
|
||||||
|
// Reduce default concurrency when musl thread over-subscription detected
|
||||||
|
sharp.concurrency(require('node:os').availableParallelism());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -177,17 +186,17 @@ function counters () {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Get and set use of SIMD vector unit instructions.
|
* Get and set use of SIMD vector unit instructions.
|
||||||
* Requires libvips to have been compiled with liborc support.
|
* Requires libvips to have been compiled with highway support.
|
||||||
*
|
*
|
||||||
* Improves the performance of `resize`, `blur` and `sharpen` operations
|
* Improves the performance of `resize`, `blur` and `sharpen` operations
|
||||||
* by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.
|
* by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* const simd = sharp.simd();
|
* const simd = sharp.simd();
|
||||||
* // simd is `true` if the runtime use of liborc is currently enabled
|
* // simd is `true` if the runtime use of highway is currently enabled
|
||||||
* @example
|
* @example
|
||||||
* const simd = sharp.simd(false);
|
* const simd = sharp.simd(false);
|
||||||
* // prevent libvips from using liborc at runtime
|
* // prevent libvips from using highway at runtime
|
||||||
*
|
*
|
||||||
* @param {boolean} [simd=true]
|
* @param {boolean} [simd=true]
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
@@ -195,7 +204,6 @@ function counters () {
|
|||||||
function simd (simd) {
|
function simd (simd) {
|
||||||
return sharp.simd(is.bool(simd) ? simd : null);
|
return sharp.simd(is.bool(simd) ? simd : null);
|
||||||
}
|
}
|
||||||
simd(true);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Block libvips operations at runtime.
|
* Block libvips operations at runtime.
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
{
|
{
|
||||||
"name": "@sharpen/sharp-darwin-arm64",
|
"name": "@img/sharp-darwin-arm64",
|
||||||
"version": "0.0.1-alpha.8",
|
"version": "0.33.4",
|
||||||
"description": "Prebuilt sharp for use with macOS ARM64",
|
"description": "Prebuilt sharp for use with macOS 64-bit ARM",
|
||||||
|
"author": "Lovell Fuller <npm@lovell.info>",
|
||||||
"homepage": "https://sharp.pixelplumbing.com",
|
"homepage": "https://sharp.pixelplumbing.com",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -14,7 +15,7 @@
|
|||||||
},
|
},
|
||||||
"preferUnplugged": true,
|
"preferUnplugged": true,
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@sharpen/sharp-libvips-darwin-arm64": "0.0.1-alpha.2"
|
"@img/sharp-libvips-darwin-arm64": "1.0.2"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"lib"
|
"lib"
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
{
|
{
|
||||||
"name": "@sharpen/sharp-darwin-x64",
|
"name": "@img/sharp-darwin-x64",
|
||||||
"version": "0.0.1-alpha.8",
|
"version": "0.33.4",
|
||||||
"description": "Prebuilt sharp for use with macOS x64",
|
"description": "Prebuilt sharp for use with macOS x64",
|
||||||
|
"author": "Lovell Fuller <npm@lovell.info>",
|
||||||
"homepage": "https://sharp.pixelplumbing.com",
|
"homepage": "https://sharp.pixelplumbing.com",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -14,7 +15,7 @@
|
|||||||
},
|
},
|
||||||
"preferUnplugged": true,
|
"preferUnplugged": true,
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@sharpen/sharp-libvips-darwin-x64": "0.0.1-alpha.2"
|
"@img/sharp-libvips-darwin-x64": "1.0.2"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"lib"
|
"lib"
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
// Populate contents of all packages with the current GitHub release
|
// Populate contents of all packages with the current GitHub release
|
||||||
|
|
||||||
const { writeFile, copyFile, rm } = require('node:fs/promises');
|
const { readFile, writeFile, appendFile, copyFile, rm } = require('node:fs/promises');
|
||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
const { Readable } = require('node:stream');
|
const { Readable } = require('node:stream');
|
||||||
const { pipeline } = require('node:stream/promises');
|
const { pipeline } = require('node:stream/promises');
|
||||||
@@ -38,7 +38,8 @@ limitations under the License.
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
workspaces.map(async platform => {
|
workspaces.map(async platform => {
|
||||||
const url = `https://github.com/lovell/sharp/releases/download/v${version}/sharp-v${version}-napi-v9-${platform}.tar.gz`;
|
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 dir = path.join(__dirname, platform);
|
||||||
const response = await fetch(url);
|
const response = await fetch(url);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
@@ -47,7 +48,7 @@ workspaces.map(async platform => {
|
|||||||
}
|
}
|
||||||
// Extract prebuild tarball
|
// Extract prebuild tarball
|
||||||
const lib = path.join(dir, 'lib');
|
const lib = path.join(dir, 'lib');
|
||||||
await rm(lib, { recursive: true });
|
await rm(lib, { force: true, recursive: true });
|
||||||
await pipeline(
|
await pipeline(
|
||||||
Readable.fromWeb(response.body),
|
Readable.fromWeb(response.body),
|
||||||
createGunzip(),
|
createGunzip(),
|
||||||
@@ -58,13 +59,15 @@ workspaces.map(async platform => {
|
|||||||
await writeFile(path.join(dir, 'README.md'), `# \`${name}\`\n\n${description}.\n${licensing}`);
|
await writeFile(path.join(dir, 'README.md'), `# \`${name}\`\n\n${description}.\n${licensing}`);
|
||||||
// Copy Apache-2.0 LICENSE
|
// Copy Apache-2.0 LICENSE
|
||||||
await copyFile(path.join(__dirname, '..', 'LICENSE'), path.join(dir, 'LICENSE'));
|
await copyFile(path.join(__dirname, '..', 'LICENSE'), path.join(dir, 'LICENSE'));
|
||||||
// Copy Windows-specific files
|
// Copy files for packages without an explicit sharp-libvips dependency (Windows, wasm)
|
||||||
if (platform.startsWith('win32-')) {
|
if (platform.startsWith('win') || platform.startsWith('wasm')) {
|
||||||
const sharpLibvipsDir = path.join(require(`@sharpen/sharp-libvips-${platform}/lib`), '..');
|
const libvipsPlatform = platform === 'wasm32' ? 'dev-wasm32' : platform;
|
||||||
await Promise.all(
|
const sharpLibvipsDir = path.join(require(`@img/sharp-libvips-${libvipsPlatform}/lib`), '..');
|
||||||
['versions.json', 'THIRD-PARTY-NOTICES.md'].map(
|
// Copy versions.json
|
||||||
filename => copyFile(path.join(sharpLibvipsDir, filename), path.join(dir, filename))
|
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);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
{
|
{
|
||||||
"name": "@sharpen/sharp-linux-arm",
|
"name": "@img/sharp-linux-arm",
|
||||||
"version": "0.0.1-alpha.8",
|
"version": "0.33.4",
|
||||||
"description": "Prebuilt sharp for use with Linux (glibc) ARM (32-bit)",
|
"description": "Prebuilt sharp for use with Linux (glibc) ARM (32-bit)",
|
||||||
|
"author": "Lovell Fuller <npm@lovell.info>",
|
||||||
"homepage": "https://sharp.pixelplumbing.com",
|
"homepage": "https://sharp.pixelplumbing.com",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -14,7 +15,7 @@
|
|||||||
},
|
},
|
||||||
"preferUnplugged": true,
|
"preferUnplugged": true,
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@sharpen/sharp-libvips-linux-arm": "0.0.1-alpha.2"
|
"@img/sharp-libvips-linux-arm": "1.0.2"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"lib"
|
"lib"
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
{
|
{
|
||||||
"name": "@sharpen/sharp-linux-arm64",
|
"name": "@img/sharp-linux-arm64",
|
||||||
"version": "0.0.1-alpha.8",
|
"version": "0.33.4",
|
||||||
"description": "Prebuilt sharp for use with Linux (glibc) ARM64",
|
"description": "Prebuilt sharp for use with Linux (glibc) 64-bit ARM",
|
||||||
|
"author": "Lovell Fuller <npm@lovell.info>",
|
||||||
"homepage": "https://sharp.pixelplumbing.com",
|
"homepage": "https://sharp.pixelplumbing.com",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -14,7 +15,7 @@
|
|||||||
},
|
},
|
||||||
"preferUnplugged": true,
|
"preferUnplugged": true,
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@sharpen/sharp-libvips-linux-arm64": "0.0.1-alpha.2"
|
"@img/sharp-libvips-linux-arm64": "1.0.2"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"lib"
|
"lib"
|
||||||
|
|||||||
47
npm/linux-s390x/package.json
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
{
|
||||||
|
"name": "@img/sharp-linux-s390x",
|
||||||
|
"version": "0.33.4",
|
||||||
|
"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.31"
|
||||||
|
},
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"libc": [
|
||||||
|
"glibc"
|
||||||
|
],
|
||||||
|
"cpu": [
|
||||||
|
"s390x"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
{
|
{
|
||||||
"name": "@sharpen/sharp-linux-x64",
|
"name": "@img/sharp-linux-x64",
|
||||||
"version": "0.0.1-alpha.8",
|
"version": "0.33.4",
|
||||||
"description": "Prebuilt sharp for use with Linux (glibc) x64",
|
"description": "Prebuilt sharp for use with Linux (glibc) x64",
|
||||||
|
"author": "Lovell Fuller <npm@lovell.info>",
|
||||||
"homepage": "https://sharp.pixelplumbing.com",
|
"homepage": "https://sharp.pixelplumbing.com",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -14,7 +15,7 @@
|
|||||||
},
|
},
|
||||||
"preferUnplugged": true,
|
"preferUnplugged": true,
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@sharpen/sharp-libvips-linux-x64": "0.0.1-alpha.2"
|
"@img/sharp-libvips-linux-x64": "1.0.2"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"lib"
|
"lib"
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
{
|
{
|
||||||
"name": "@sharpen/sharp-linuxmusl-arm64",
|
"name": "@img/sharp-linuxmusl-arm64",
|
||||||
"version": "0.0.1-alpha.8",
|
"version": "0.33.4",
|
||||||
"description": "Prebuilt sharp for use with Linux (musl) ARM64",
|
"description": "Prebuilt sharp for use with Linux (musl) 64-bit ARM",
|
||||||
|
"author": "Lovell Fuller <npm@lovell.info>",
|
||||||
"homepage": "https://sharp.pixelplumbing.com",
|
"homepage": "https://sharp.pixelplumbing.com",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -14,7 +15,7 @@
|
|||||||
},
|
},
|
||||||
"preferUnplugged": true,
|
"preferUnplugged": true,
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@sharpen/sharp-libvips-linuxmusl-arm64": "0.0.1-alpha.2"
|
"@img/sharp-libvips-linuxmusl-arm64": "1.0.2"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"lib"
|
"lib"
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
{
|
{
|
||||||
"name": "@sharpen/sharp-linuxmusl-x64",
|
"name": "@img/sharp-linuxmusl-x64",
|
||||||
"version": "0.0.1-alpha.8",
|
"version": "0.33.4",
|
||||||
"description": "Prebuilt sharp for use with Linux (musl) x64",
|
"description": "Prebuilt sharp for use with Linux (musl) x64",
|
||||||
|
"author": "Lovell Fuller <npm@lovell.info>",
|
||||||
"homepage": "https://sharp.pixelplumbing.com",
|
"homepage": "https://sharp.pixelplumbing.com",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -14,7 +15,7 @@
|
|||||||
},
|
},
|
||||||
"preferUnplugged": true,
|
"preferUnplugged": true,
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@sharpen/sharp-libvips-linuxmusl-x64": "0.0.1-alpha.2"
|
"@img/sharp-libvips-linuxmusl-x64": "1.0.2"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"lib"
|
"lib"
|
||||||
|
|||||||
@@ -1,15 +1,17 @@
|
|||||||
{
|
{
|
||||||
"name": "@sharpen/sharp",
|
"name": "@img/sharp",
|
||||||
"version": "0.0.1-alpha.8",
|
"version": "0.33.4",
|
||||||
"private": "true",
|
"private": "true",
|
||||||
"workspaces": [
|
"workspaces": [
|
||||||
"darwin-x64",
|
|
||||||
"darwin-arm64",
|
"darwin-arm64",
|
||||||
|
"darwin-x64",
|
||||||
"linux-arm",
|
"linux-arm",
|
||||||
"linux-arm64",
|
"linux-arm64",
|
||||||
|
"linux-s390x",
|
||||||
|
"linux-x64",
|
||||||
"linuxmusl-arm64",
|
"linuxmusl-arm64",
|
||||||
"linuxmusl-x64",
|
"linuxmusl-x64",
|
||||||
"linux-x64",
|
"wasm32",
|
||||||
"win32-ia32",
|
"win32-ia32",
|
||||||
"win32-x64"
|
"win32-x64"
|
||||||
]
|
]
|
||||||
|
|||||||
42
npm/wasm32/package.json
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
{
|
||||||
|
"name": "@img/sharp-wasm32",
|
||||||
|
"version": "0.33.4",
|
||||||
|
"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.1"
|
||||||
|
},
|
||||||
|
"cpu": [
|
||||||
|
"wasm32"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
{
|
{
|
||||||
"name": "@sharpen/sharp-win32-ia32",
|
"name": "@img/sharp-win32-ia32",
|
||||||
"version": "0.0.1-alpha.8",
|
"version": "0.33.4",
|
||||||
"description": "Prebuilt sharp for use with Windows x86 (32-bit)",
|
"description": "Prebuilt sharp for use with Windows x86 (32-bit)",
|
||||||
|
"author": "Lovell Fuller <npm@lovell.info>",
|
||||||
"homepage": "https://sharp.pixelplumbing.com",
|
"homepage": "https://sharp.pixelplumbing.com",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -15,8 +16,7 @@
|
|||||||
"preferUnplugged": true,
|
"preferUnplugged": true,
|
||||||
"files": [
|
"files": [
|
||||||
"lib",
|
"lib",
|
||||||
"versions.json",
|
"versions.json"
|
||||||
"THIRD-PARTY-NOTICES.md"
|
|
||||||
],
|
],
|
||||||
"publishConfig": {
|
"publishConfig": {
|
||||||
"access": "public"
|
"access": "public"
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
{
|
{
|
||||||
"name": "@sharpen/sharp-win32-x64",
|
"name": "@img/sharp-win32-x64",
|
||||||
"version": "0.0.1-alpha.8",
|
"version": "0.33.4",
|
||||||
"description": "Prebuilt sharp for use with Windows x64",
|
"description": "Prebuilt sharp for use with Windows x64",
|
||||||
|
"author": "Lovell Fuller <npm@lovell.info>",
|
||||||
"homepage": "https://sharp.pixelplumbing.com",
|
"homepage": "https://sharp.pixelplumbing.com",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -15,8 +16,7 @@
|
|||||||
"preferUnplugged": true,
|
"preferUnplugged": true,
|
||||||
"files": [
|
"files": [
|
||||||
"lib",
|
"lib",
|
||||||
"versions.json",
|
"versions.json"
|
||||||
"THIRD-PARTY-NOTICES.md"
|
|
||||||
],
|
],
|
||||||
"publishConfig": {
|
"publishConfig": {
|
||||||
"access": "public"
|
"access": "public"
|
||||||
@@ -24,7 +24,8 @@
|
|||||||
"type": "commonjs",
|
"type": "commonjs",
|
||||||
"exports": {
|
"exports": {
|
||||||
"./sharp.node": "./lib/sharp-win32-x64.node",
|
"./sharp.node": "./lib/sharp-win32-x64.node",
|
||||||
"./package": "./package.json"
|
"./package": "./package.json",
|
||||||
|
"./versions": "./versions.json"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0",
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0",
|
||||||
|
|||||||
81
package.json
@@ -1,9 +1,9 @@
|
|||||||
{
|
{
|
||||||
"name": "sharp",
|
"name": "sharp",
|
||||||
"description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images",
|
"description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images",
|
||||||
"version": "0.33.0-alpha.8",
|
"version": "0.33.4",
|
||||||
"author": "Lovell Fuller <npm@lovell.info>",
|
"author": "Lovell Fuller <npm@lovell.info>",
|
||||||
"homepage": "https://github.com/lovell/sharp",
|
"homepage": "https://sharp.pixelplumbing.com",
|
||||||
"contributors": [
|
"contributors": [
|
||||||
"Pierre Inglebert <pierre.inglebert@gmail.com>",
|
"Pierre Inglebert <pierre.inglebert@gmail.com>",
|
||||||
"Jonathan Ong <jonathanrichardong@gmail.com>",
|
"Jonathan Ong <jonathanrichardong@gmail.com>",
|
||||||
@@ -82,11 +82,13 @@
|
|||||||
"Joris Dugué <zaruike10@gmail.com>",
|
"Joris Dugué <zaruike10@gmail.com>",
|
||||||
"Chris Banks <christopher.bradley.banks@gmail.com>",
|
"Chris Banks <christopher.bradley.banks@gmail.com>",
|
||||||
"Ompal Singh <ompal.hitm09@gmail.com>",
|
"Ompal Singh <ompal.hitm09@gmail.com>",
|
||||||
"Brodan <christopher.hranj@gmail.com",
|
"Brodan <christopher.hranj@gmail.com>",
|
||||||
"Ankur Parihar <ankur.github@gmail.com>",
|
"Ankur Parihar <ankur.github@gmail.com>",
|
||||||
"Brahim Ait elhaj <brahima@gmail.com>",
|
"Brahim Ait elhaj <brahima@gmail.com>",
|
||||||
"Mart Jansink <m.jansink@gmail.com>",
|
"Mart Jansink <m.jansink@gmail.com>",
|
||||||
"Lachlan Newman <lachnewman007@gmail.com>"
|
"Lachlan Newman <lachnewman007@gmail.com>",
|
||||||
|
"Dennis Beatty <dennis@dcbeatty.com>",
|
||||||
|
"Ingvar Stepanyan <me@rreverser.com>"
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"install": "node install/check",
|
"install": "node install/check",
|
||||||
@@ -135,51 +137,57 @@
|
|||||||
],
|
],
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"color": "^4.2.3",
|
"color": "^4.2.3",
|
||||||
"detect-libc": "^2.0.2",
|
"detect-libc": "^2.0.3",
|
||||||
"semver": "^7.5.4"
|
"semver": "^7.6.0"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@sharpen/sharp-darwin-arm64": "0.0.1-alpha.8",
|
"@img/sharp-darwin-arm64": "0.33.4",
|
||||||
"@sharpen/sharp-darwin-x64": "0.0.1-alpha.8",
|
"@img/sharp-darwin-x64": "0.33.4",
|
||||||
"@sharpen/sharp-libvips-darwin-arm64": "0.0.1-alpha.2",
|
"@img/sharp-libvips-darwin-arm64": "1.0.2",
|
||||||
"@sharpen/sharp-libvips-darwin-x64": "0.0.1-alpha.2",
|
"@img/sharp-libvips-darwin-x64": "1.0.2",
|
||||||
"@sharpen/sharp-libvips-linux-arm": "0.0.1-alpha.2",
|
"@img/sharp-libvips-linux-arm": "1.0.2",
|
||||||
"@sharpen/sharp-libvips-linux-arm64": "0.0.1-alpha.2",
|
"@img/sharp-libvips-linux-arm64": "1.0.2",
|
||||||
"@sharpen/sharp-libvips-linux-x64": "0.0.1-alpha.2",
|
"@img/sharp-libvips-linux-s390x": "1.0.2",
|
||||||
"@sharpen/sharp-libvips-linuxmusl-arm64": "0.0.1-alpha.2",
|
"@img/sharp-libvips-linux-x64": "1.0.2",
|
||||||
"@sharpen/sharp-libvips-linuxmusl-x64": "0.0.1-alpha.2",
|
"@img/sharp-libvips-linuxmusl-arm64": "1.0.2",
|
||||||
"@sharpen/sharp-linux-arm": "0.0.1-alpha.8",
|
"@img/sharp-libvips-linuxmusl-x64": "1.0.2",
|
||||||
"@sharpen/sharp-linux-arm64": "0.0.1-alpha.8",
|
"@img/sharp-linux-arm": "0.33.4",
|
||||||
"@sharpen/sharp-linux-x64": "0.0.1-alpha.8",
|
"@img/sharp-linux-arm64": "0.33.4",
|
||||||
"@sharpen/sharp-linuxmusl-arm64": "0.0.1-alpha.8",
|
"@img/sharp-linux-s390x": "0.33.4",
|
||||||
"@sharpen/sharp-linuxmusl-x64": "0.0.1-alpha.8",
|
"@img/sharp-linux-x64": "0.33.4",
|
||||||
"@sharpen/sharp-win32-ia32": "0.0.1-alpha.8",
|
"@img/sharp-linuxmusl-arm64": "0.33.4",
|
||||||
"@sharpen/sharp-win32-x64": "0.0.1-alpha.8"
|
"@img/sharp-linuxmusl-x64": "0.33.4",
|
||||||
|
"@img/sharp-wasm32": "0.33.4",
|
||||||
|
"@img/sharp-win32-ia32": "0.33.4",
|
||||||
|
"@img/sharp-win32-x64": "0.33.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@sharpen/sharp-libvips-dev": "0.0.1-alpha.2",
|
"@emnapi/runtime": "^1.1.1",
|
||||||
"@sharpen/sharp-libvips-win32-ia32": "0.0.1-alpha.2",
|
"@img/sharp-libvips-dev": "1.0.2",
|
||||||
"@sharpen/sharp-libvips-win32-x64": "0.0.1-alpha.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": "*",
|
"@types/node": "*",
|
||||||
"async": "^3.2.4",
|
"async": "^3.2.5",
|
||||||
"cc": "^3.0.1",
|
"cc": "^3.0.1",
|
||||||
"exif-reader": "^2.0.0",
|
"emnapi": "^1.1.1",
|
||||||
|
"exif-reader": "^2.0.1",
|
||||||
"extract-zip": "^2.0.1",
|
"extract-zip": "^2.0.1",
|
||||||
"icc": "^3.0.0",
|
"icc": "^3.0.0",
|
||||||
"jsdoc-to-markdown": "^8.0.0",
|
"jsdoc-to-markdown": "^8.0.1",
|
||||||
"license-checker": "^25.0.1",
|
"license-checker": "^25.0.1",
|
||||||
"mocha": "^10.2.0",
|
"mocha": "^10.4.0",
|
||||||
"node-addon-api": "^7.0.0",
|
"node-addon-api": "^8.0.0",
|
||||||
"nyc": "^15.1.0",
|
"nyc": "^15.1.0",
|
||||||
"prebuild": "^12.1.0",
|
"prebuild": "^13.0.1",
|
||||||
"semistandard": "^17.0.0",
|
"semistandard": "^17.0.0",
|
||||||
"tar-fs": "^3.0.4",
|
"tar-fs": "^3.0.6",
|
||||||
"tsd": "^0.29.0"
|
"tsd": "^0.31.0"
|
||||||
},
|
},
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0",
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0",
|
||||||
"libvips": ">=8.14.5"
|
"libvips": ">=8.15.2"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
@@ -200,6 +208,11 @@
|
|||||||
"build/include"
|
"build/include"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
"nyc": {
|
||||||
|
"include": [
|
||||||
|
"lib"
|
||||||
|
]
|
||||||
|
},
|
||||||
"tsd": {
|
"tsd": {
|
||||||
"directory": "test/types/"
|
"directory": "test/types/"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,8 @@
|
|||||||
'variables': {
|
'variables': {
|
||||||
'vips_version': '<!(node -p "require(\'../lib/libvips\').minimumLibvipsVersion")',
|
'vips_version': '<!(node -p "require(\'../lib/libvips\').minimumLibvipsVersion")',
|
||||||
'platform_and_arch': '<!(node -p "require(\'../lib/libvips\').buildPlatformArch()")',
|
'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_include_dir': '<!(node -p "require(\'../lib/libvips\').buildSharpLibvipsIncludeDir()")',
|
||||||
'sharp_libvips_cplusplus_dir': '<!(node -p "require(\'../lib/libvips\').buildSharpLibvipsCPlusPlusDir()")',
|
'sharp_libvips_cplusplus_dir': '<!(node -p "require(\'../lib/libvips\').buildSharpLibvipsCPlusPlusDir()")',
|
||||||
'sharp_libvips_lib_dir': '<!(node -p "require(\'../lib/libvips\').buildSharpLibvipsLibDir()")'
|
'sharp_libvips_lib_dir': '<!(node -p "require(\'../lib/libvips\').buildSharpLibvipsLibDir()")'
|
||||||
@@ -32,11 +34,11 @@
|
|||||||
'<(sharp_libvips_lib_dir)/glib-2.0/include'
|
'<(sharp_libvips_lib_dir)/glib-2.0/include'
|
||||||
],
|
],
|
||||||
'link_settings': {
|
'link_settings': {
|
||||||
'library_dirs': ['<(sharp_libvips_lib_dir)'],
|
'library_dirs': [
|
||||||
|
'<(sharp_libvips_lib_dir)'
|
||||||
|
],
|
||||||
'libraries': [
|
'libraries': [
|
||||||
'libvips.lib',
|
'libvips.lib'
|
||||||
'libglib-2.0.lib',
|
|
||||||
'libgobject-2.0.lib'
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
'configurations': {
|
'configurations': {
|
||||||
@@ -129,6 +131,9 @@
|
|||||||
'<(sharp_libvips_include_dir)/glib-2.0',
|
'<(sharp_libvips_include_dir)/glib-2.0',
|
||||||
'<(sharp_libvips_lib_dir)/glib-2.0/include'
|
'<(sharp_libvips_lib_dir)/glib-2.0/include'
|
||||||
],
|
],
|
||||||
|
'library_dirs': [
|
||||||
|
'<(sharp_libvips_lib_dir)'
|
||||||
|
],
|
||||||
'conditions': [
|
'conditions': [
|
||||||
['OS == "win"', {
|
['OS == "win"', {
|
||||||
'defines': [
|
'defines': [
|
||||||
@@ -136,19 +141,13 @@
|
|||||||
'_FILE_OFFSET_BITS=64'
|
'_FILE_OFFSET_BITS=64'
|
||||||
],
|
],
|
||||||
'link_settings': {
|
'link_settings': {
|
||||||
'library_dirs': ['<(sharp_libvips_lib_dir)'],
|
|
||||||
'libraries': [
|
'libraries': [
|
||||||
'libvips.lib',
|
'libvips.lib'
|
||||||
'libglib-2.0.lib',
|
|
||||||
'libgobject-2.0.lib'
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}],
|
}],
|
||||||
['OS == "mac"', {
|
['OS == "mac"', {
|
||||||
'link_settings': {
|
'link_settings': {
|
||||||
'library_dirs': [
|
|
||||||
'<(sharp_libvips_lib_dir)'
|
|
||||||
],
|
|
||||||
'libraries': [
|
'libraries': [
|
||||||
'libvips-cpp.42.dylib'
|
'libvips-cpp.42.dylib'
|
||||||
]
|
]
|
||||||
@@ -157,8 +156,10 @@
|
|||||||
'OTHER_LDFLAGS': [
|
'OTHER_LDFLAGS': [
|
||||||
# Ensure runtime linking is relative to sharp.node
|
# Ensure runtime linking is relative to sharp.node
|
||||||
'-Wl,-rpath,\'@loader_path/../../sharp-libvips-<(platform_and_arch)/lib\'',
|
'-Wl,-rpath,\'@loader_path/../../sharp-libvips-<(platform_and_arch)/lib\'',
|
||||||
'-Wl,-rpath,\'@loader_path/../../node_modules/@sharpen/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/@sharpen/sharp-libvips-<(platform_and_arch)/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\''
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}],
|
}],
|
||||||
@@ -167,21 +168,40 @@
|
|||||||
'_GLIBCXX_USE_CXX11_ABI=1'
|
'_GLIBCXX_USE_CXX11_ABI=1'
|
||||||
],
|
],
|
||||||
'link_settings': {
|
'link_settings': {
|
||||||
'library_dirs': [
|
|
||||||
'<(sharp_libvips_lib_dir)'
|
|
||||||
],
|
|
||||||
'libraries': [
|
'libraries': [
|
||||||
'-l:libvips-cpp.so.42'
|
'-l:libvips-cpp.so.42'
|
||||||
],
|
],
|
||||||
'ldflags': [
|
'ldflags': [
|
||||||
# Ensure runtime linking is relative to sharp.node
|
|
||||||
'-Wl,-s',
|
'-Wl,-s',
|
||||||
'-Wl,--disable-new-dtags',
|
'-Wl,--disable-new-dtags',
|
||||||
|
'-Wl,-z,nodelete',
|
||||||
'-Wl,-rpath=\'$$ORIGIN/../../sharp-libvips-<(platform_and_arch)/lib\'',
|
'-Wl,-rpath=\'$$ORIGIN/../../sharp-libvips-<(platform_and_arch)/lib\'',
|
||||||
'-Wl,-rpath=\'$$ORIGIN/../../node_modules/@sharpen/sharp-libvips-<(platform_and_arch)/lib\'',
|
'-Wl,-rpath=\'$$ORIGIN/../../../sharp-libvips-<(platform_and_arch)/<(sharp_libvips_version)/lib\'',
|
||||||
'-Wl,-rpath=\'$$ORIGIN/../../../node_modules/@sharpen/sharp-libvips-<(platform_and_arch)/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)'
|
||||||
|
],
|
||||||
|
}
|
||||||
}]
|
}]
|
||||||
]
|
]
|
||||||
}]
|
}]
|
||||||
@@ -206,11 +226,6 @@
|
|||||||
'configurations': {
|
'configurations': {
|
||||||
'Release': {
|
'Release': {
|
||||||
'conditions': [
|
'conditions': [
|
||||||
['OS == "linux"', {
|
|
||||||
'cflags_cc': [
|
|
||||||
'-Wno-cast-function-type'
|
|
||||||
]
|
|
||||||
}],
|
|
||||||
['target_arch == "arm"', {
|
['target_arch == "arm"', {
|
||||||
'cflags_cc': [
|
'cflags_cc': [
|
||||||
'-Wno-psabi'
|
'-Wno-psabi'
|
||||||
@@ -256,9 +271,7 @@
|
|||||||
'copies': [{
|
'copies': [{
|
||||||
'destination': 'build/Release',
|
'destination': 'build/Release',
|
||||||
'files': [
|
'files': [
|
||||||
'<(sharp_libvips_lib_dir)/libvips-42.dll',
|
'<(sharp_libvips_lib_dir)/libvips-42.dll'
|
||||||
'<(sharp_libvips_lib_dir)/libglib-2.0-0.dll',
|
|
||||||
'<(sharp_libvips_lib_dir)/libgobject-2.0-0.dll'
|
|
||||||
]
|
]
|
||||||
}]
|
}]
|
||||||
}]
|
}]
|
||||||
|
|||||||
@@ -75,7 +75,7 @@ namespace sharp {
|
|||||||
Napi::Buffer<char> buffer = input.Get("buffer").As<Napi::Buffer<char>>();
|
Napi::Buffer<char> buffer = input.Get("buffer").As<Napi::Buffer<char>>();
|
||||||
descriptor->bufferLength = buffer.Length();
|
descriptor->bufferLength = buffer.Length();
|
||||||
descriptor->buffer = buffer.Data();
|
descriptor->buffer = buffer.Data();
|
||||||
descriptor->isBuffer = TRUE;
|
descriptor->isBuffer = true;
|
||||||
}
|
}
|
||||||
descriptor->failOn = AttrAsEnum<VipsFailOn>(input, "failOn", VIPS_TYPE_FAIL_ON);
|
descriptor->failOn = AttrAsEnum<VipsFailOn>(input, "failOn", VIPS_TYPE_FAIL_ON);
|
||||||
// Density for vector-based input
|
// Density for vector-based input
|
||||||
@@ -384,7 +384,7 @@ namespace sharp {
|
|||||||
->set("access", descriptor->access)
|
->set("access", descriptor->access)
|
||||||
->set("fail_on", descriptor->failOn);
|
->set("fail_on", descriptor->failOn);
|
||||||
if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {
|
if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {
|
||||||
option->set("unlimited", TRUE);
|
option->set("unlimited", true);
|
||||||
}
|
}
|
||||||
if (imageType == ImageType::SVG || imageType == ImageType::PDF) {
|
if (imageType == ImageType::SVG || imageType == ImageType::PDF) {
|
||||||
option->set("dpi", descriptor->density);
|
option->set("dpi", descriptor->density);
|
||||||
@@ -488,7 +488,7 @@ namespace sharp {
|
|||||||
->set("access", descriptor->access)
|
->set("access", descriptor->access)
|
||||||
->set("fail_on", descriptor->failOn);
|
->set("fail_on", descriptor->failOn);
|
||||||
if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {
|
if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {
|
||||||
option->set("unlimited", TRUE);
|
option->set("unlimited", true);
|
||||||
}
|
}
|
||||||
if (imageType == ImageType::SVG || imageType == ImageType::PDF) {
|
if (imageType == ImageType::SVG || imageType == ImageType::PDF) {
|
||||||
option->set("dpi", descriptor->density);
|
option->set("dpi", descriptor->density);
|
||||||
@@ -531,7 +531,33 @@ namespace sharp {
|
|||||||
Does this image have an embedded profile?
|
Does this image have an embedded profile?
|
||||||
*/
|
*/
|
||||||
bool HasProfile(VImage image) {
|
bool HasProfile(VImage image) {
|
||||||
return (image.get_typeof(VIPS_META_ICC_NAME) != 0) ? TRUE : FALSE;
|
return image.get_typeof(VIPS_META_ICC_NAME) == VIPS_TYPE_BLOB;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -542,6 +568,27 @@ namespace sharp {
|
|||||||
return image.has_alpha();
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Get EXIF Orientation of image, if any.
|
Get EXIF Orientation of image, if any.
|
||||||
*/
|
*/
|
||||||
@@ -721,7 +768,7 @@ namespace sharp {
|
|||||||
int *timeout = VIPS_NEW(im, int);
|
int *timeout = VIPS_NEW(im, int);
|
||||||
*timeout = seconds;
|
*timeout = seconds;
|
||||||
g_signal_connect(im, "eval", G_CALLBACK(VipsProgressCallBack), timeout);
|
g_signal_connect(im, "eval", G_CALLBACK(VipsProgressCallBack), timeout);
|
||||||
vips_image_set_progress(im, TRUE);
|
vips_image_set_progress(im, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -731,7 +778,7 @@ namespace sharp {
|
|||||||
*/
|
*/
|
||||||
void VipsProgressCallBack(VipsImage *im, VipsProgress *progress, int *timeout) {
|
void VipsProgressCallBack(VipsImage *im, VipsProgress *progress, int *timeout) {
|
||||||
if (*timeout > 0 && progress->run >= *timeout) {
|
if (*timeout > 0 && progress->run >= *timeout) {
|
||||||
vips_image_set_kill(im, TRUE);
|
vips_image_set_kill(im, true);
|
||||||
vips_error("timeout", "%d%% complete", progress->percent);
|
vips_error("timeout", "%d%% complete", progress->percent);
|
||||||
*timeout = 0;
|
*timeout = 0;
|
||||||
}
|
}
|
||||||
@@ -1034,9 +1081,10 @@ namespace sharp {
|
|||||||
/*
|
/*
|
||||||
Ensure decoding remains sequential.
|
Ensure decoding remains sequential.
|
||||||
*/
|
*/
|
||||||
VImage StaySequential(VImage image, VipsAccess access, bool condition) {
|
VImage StaySequential(VImage image, bool condition) {
|
||||||
if (access == VIPS_ACCESS_SEQUENTIAL && condition) {
|
if (vips_image_is_sequential(image.get_image()) && condition) {
|
||||||
return image.copy_memory();
|
image = image.copy_memory().copy();
|
||||||
|
image.remove(VIPS_META_SEQUENTIAL);
|
||||||
}
|
}
|
||||||
return image;
|
return image;
|
||||||
}
|
}
|
||||||
|
|||||||
33
src/common.h
@@ -15,9 +15,9 @@
|
|||||||
// Verify platform and compiler compatibility
|
// Verify platform and compiler compatibility
|
||||||
|
|
||||||
#if (VIPS_MAJOR_VERSION < 8) || \
|
#if (VIPS_MAJOR_VERSION < 8) || \
|
||||||
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION < 14) || \
|
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION < 15) || \
|
||||||
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION == 14 && VIPS_MICRO_VERSION < 5)
|
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION == 15 && VIPS_MICRO_VERSION < 2)
|
||||||
#error "libvips version 8.14.5+ is required - please see https://sharp.pixelplumbing.com/install"
|
#error "libvips version 8.15.2+ is required - please see https://sharp.pixelplumbing.com/install"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if ((!defined(__clang__)) && defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 6)))
|
#if ((!defined(__clang__)) && defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 6)))
|
||||||
@@ -79,12 +79,12 @@ namespace sharp {
|
|||||||
buffer(nullptr),
|
buffer(nullptr),
|
||||||
failOn(VIPS_FAIL_ON_WARNING),
|
failOn(VIPS_FAIL_ON_WARNING),
|
||||||
limitInputPixels(0x3FFF * 0x3FFF),
|
limitInputPixels(0x3FFF * 0x3FFF),
|
||||||
unlimited(FALSE),
|
unlimited(false),
|
||||||
access(VIPS_ACCESS_RANDOM),
|
access(VIPS_ACCESS_RANDOM),
|
||||||
bufferLength(0),
|
bufferLength(0),
|
||||||
isBuffer(FALSE),
|
isBuffer(false),
|
||||||
density(72.0),
|
density(72.0),
|
||||||
ignoreIcc(FALSE),
|
ignoreIcc(false),
|
||||||
rawDepth(VIPS_FORMAT_UCHAR),
|
rawDepth(VIPS_FORMAT_UCHAR),
|
||||||
rawChannels(0),
|
rawChannels(0),
|
||||||
rawWidth(0),
|
rawWidth(0),
|
||||||
@@ -103,9 +103,9 @@ namespace sharp {
|
|||||||
textWidth(0),
|
textWidth(0),
|
||||||
textHeight(0),
|
textHeight(0),
|
||||||
textAlign(VIPS_ALIGN_LOW),
|
textAlign(VIPS_ALIGN_LOW),
|
||||||
textJustify(FALSE),
|
textJustify(false),
|
||||||
textDpi(72),
|
textDpi(72),
|
||||||
textRgba(FALSE),
|
textRgba(false),
|
||||||
textSpacing(0),
|
textSpacing(0),
|
||||||
textWrap(VIPS_TEXT_WRAP_WORD),
|
textWrap(VIPS_TEXT_WRAP_WORD),
|
||||||
textAutofitDpi(0) {}
|
textAutofitDpi(0) {}
|
||||||
@@ -222,12 +222,27 @@ namespace sharp {
|
|||||||
*/
|
*/
|
||||||
bool HasProfile(VImage image);
|
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?
|
Does this image have an alpha channel?
|
||||||
Uses colour space interpretation with number of channels to guess this.
|
Uses colour space interpretation with number of channels to guess this.
|
||||||
*/
|
*/
|
||||||
bool HasAlpha(VImage image);
|
bool HasAlpha(VImage image);
|
||||||
|
|
||||||
|
/*
|
||||||
|
Remove all EXIF-related image fields.
|
||||||
|
*/
|
||||||
|
VImage RemoveExif(VImage image);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Get EXIF Orientation of image, if any.
|
Get EXIF Orientation of image, if any.
|
||||||
*/
|
*/
|
||||||
@@ -371,7 +386,7 @@ namespace sharp {
|
|||||||
/*
|
/*
|
||||||
Ensure decoding remains sequential.
|
Ensure decoding remains sequential.
|
||||||
*/
|
*/
|
||||||
VImage StaySequential(VImage image, VipsAccess access, bool condition = TRUE);
|
VImage StaySequential(VImage image, bool condition = true);
|
||||||
|
|
||||||
} // namespace sharp
|
} // namespace sharp
|
||||||
|
|
||||||
|
|||||||
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
@@ -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();
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -145,7 +145,7 @@ class MetadataWorker : public Napi::AsyncWorker {
|
|||||||
// Handle warnings
|
// Handle warnings
|
||||||
std::string warning = sharp::VipsWarningPop();
|
std::string warning = sharp::VipsWarningPop();
|
||||||
while (!warning.empty()) {
|
while (!warning.empty()) {
|
||||||
debuglog.MakeCallback(Receiver().Value(), { Napi::String::New(env, warning) });
|
debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) });
|
||||||
warning = sharp::VipsWarningPop();
|
warning = sharp::VipsWarningPop();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -246,9 +246,9 @@ class MetadataWorker : public Napi::AsyncWorker {
|
|||||||
Napi::Buffer<char>::NewOrCopy(env, baton->tifftagPhotoshop,
|
Napi::Buffer<char>::NewOrCopy(env, baton->tifftagPhotoshop,
|
||||||
baton->tifftagPhotoshopLength, sharp::FreeCallback));
|
baton->tifftagPhotoshopLength, sharp::FreeCallback));
|
||||||
}
|
}
|
||||||
Callback().MakeCallback(Receiver().Value(), { env.Null(), info });
|
Callback().Call(Receiver().Value(), { env.Null(), info });
|
||||||
} else {
|
} else {
|
||||||
Callback().MakeCallback(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() });
|
Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() });
|
||||||
}
|
}
|
||||||
|
|
||||||
delete baton->input;
|
delete baton->input;
|
||||||
|
|||||||
@@ -16,30 +16,44 @@ using vips::VError;
|
|||||||
|
|
||||||
namespace sharp {
|
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) {
|
||||||
// Get original colourspace
|
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();
|
VipsInterpretation typeBeforeTint = image.interpretation();
|
||||||
if (typeBeforeTint == VIPS_INTERPRETATION_RGB) {
|
if (typeBeforeTint == VIPS_INTERPRETATION_RGB) {
|
||||||
typeBeforeTint = VIPS_INTERPRETATION_sRGB;
|
typeBeforeTint = VIPS_INTERPRETATION_sRGB;
|
||||||
}
|
}
|
||||||
// Extract luminance
|
// Apply lookup table
|
||||||
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
|
|
||||||
if (HasAlpha(image)) {
|
if (HasAlpha(image)) {
|
||||||
// Extract original alpha channel
|
|
||||||
VImage alpha = image[image.bands() - 1];
|
VImage alpha = image[image.bands() - 1];
|
||||||
// Join alpha channel to normalised image
|
image = RemoveAlpha(image)
|
||||||
tinted = tinted.bandjoin(alpha);
|
.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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -141,7 +155,7 @@ namespace sharp {
|
|||||||
return image.conv(blur);
|
return image.conv(blur);
|
||||||
} else {
|
} else {
|
||||||
// Slower, accurate Gaussian blur
|
// Slower, accurate Gaussian blur
|
||||||
return image.gaussblur(sigma);
|
return StaySequential(image).gaussblur(sigma);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -265,7 +279,7 @@ namespace sharp {
|
|||||||
/*
|
/*
|
||||||
Trim an image
|
Trim an image
|
||||||
*/
|
*/
|
||||||
VImage Trim(VImage image, std::vector<double> background, double threshold) {
|
VImage Trim(VImage image, std::vector<double> background, double threshold, bool const lineArt) {
|
||||||
if (image.width() < 3 && image.height() < 3) {
|
if (image.width() < 3 && image.height() < 3) {
|
||||||
throw VError("Image to trim must be at least 3x3 pixels");
|
throw VError("Image to trim must be at least 3x3 pixels");
|
||||||
}
|
}
|
||||||
@@ -287,6 +301,7 @@ namespace sharp {
|
|||||||
int left, top, width, height;
|
int left, top, width, height;
|
||||||
left = image.find_trim(&top, &width, &height, VImage::option()
|
left = image.find_trim(&top, &width, &height, VImage::option()
|
||||||
->set("background", background)
|
->set("background", background)
|
||||||
|
->set("line_art", lineArt)
|
||||||
->set("threshold", threshold));
|
->set("threshold", threshold));
|
||||||
if (HasAlpha(image)) {
|
if (HasAlpha(image)) {
|
||||||
// Search alpha channel (A)
|
// Search alpha channel (A)
|
||||||
@@ -294,6 +309,7 @@ namespace sharp {
|
|||||||
VImage alpha = image[image.bands() - 1];
|
VImage alpha = image[image.bands() - 1];
|
||||||
leftA = alpha.find_trim(&topA, &widthA, &heightA, VImage::option()
|
leftA = alpha.find_trim(&topA, &widthA, &heightA, VImage::option()
|
||||||
->set("background", backgroundAlpha)
|
->set("background", backgroundAlpha)
|
||||||
|
->set("line_art", lineArt)
|
||||||
->set("threshold", threshold));
|
->set("threshold", threshold));
|
||||||
if (widthA > 0 && heightA > 0) {
|
if (widthA > 0 && heightA > 0) {
|
||||||
if (width > 0 && height > 0) {
|
if (width > 0 && height > 0) {
|
||||||
@@ -370,6 +386,7 @@ namespace sharp {
|
|||||||
pages.reserve(nPages);
|
pages.reserve(nPages);
|
||||||
|
|
||||||
// Split the image into cropped frames
|
// Split the image into cropped frames
|
||||||
|
image = StaySequential(image);
|
||||||
for (int i = 0; i < nPages; i++) {
|
for (int i = 0; i < nPages; i++) {
|
||||||
pages.push_back(
|
pages.push_back(
|
||||||
image.extract_area(left, *pageHeight * i + top, width, height));
|
image.extract_area(left, *pageHeight * i + top, width, height));
|
||||||
|
|||||||
@@ -15,9 +15,9 @@ using vips::VImage;
|
|||||||
namespace sharp {
|
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.
|
* Stretch luminance to cover full dynamic range.
|
||||||
@@ -79,7 +79,7 @@ namespace sharp {
|
|||||||
/*
|
/*
|
||||||
Trim an image
|
Trim an image
|
||||||
*/
|
*/
|
||||||
VImage Trim(VImage image, std::vector<double> background, double const threshold);
|
VImage Trim(VImage image, std::vector<double> background, double threshold, bool const lineArt);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Linear adjustment (a * in + b)
|
* Linear adjustment (a * in + b)
|
||||||
|
|||||||
243
src/pipeline.cc
@@ -54,7 +54,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
sharp::ImageType inputImageType;
|
sharp::ImageType inputImageType;
|
||||||
std::tie(image, inputImageType) = sharp::OpenInput(baton->input);
|
std::tie(image, inputImageType) = sharp::OpenInput(baton->input);
|
||||||
VipsAccess access = baton->input->access;
|
VipsAccess access = baton->input->access;
|
||||||
image = sharp::EnsureColourspace(image, baton->colourspaceInput);
|
image = sharp::EnsureColourspace(image, baton->colourspacePipeline);
|
||||||
|
|
||||||
int nPages = baton->input->pages;
|
int nPages = baton->input->pages;
|
||||||
if (nPages == -1) {
|
if (nPages == -1) {
|
||||||
@@ -70,8 +70,8 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// Calculate angle of rotation
|
// Calculate angle of rotation
|
||||||
VipsAngle rotation = VIPS_ANGLE_D0;
|
VipsAngle rotation = VIPS_ANGLE_D0;
|
||||||
VipsAngle autoRotation = VIPS_ANGLE_D0;
|
VipsAngle autoRotation = VIPS_ANGLE_D0;
|
||||||
bool autoFlip = FALSE;
|
bool autoFlip = false;
|
||||||
bool autoFlop = FALSE;
|
bool autoFlop = false;
|
||||||
|
|
||||||
if (baton->useExifOrientation) {
|
if (baton->useExifOrientation) {
|
||||||
// Rotate and flip image according to Exif orientation
|
// Rotate and flip image according to Exif orientation
|
||||||
@@ -88,7 +88,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
baton->rotationAngle != 0.0);
|
baton->rotationAngle != 0.0);
|
||||||
|
|
||||||
if (shouldRotateBefore) {
|
if (shouldRotateBefore) {
|
||||||
image = sharp::StaySequential(image, access,
|
image = sharp::StaySequential(image,
|
||||||
rotation != VIPS_ANGLE_D0 ||
|
rotation != VIPS_ANGLE_D0 ||
|
||||||
autoRotation != VIPS_ANGLE_D0 ||
|
autoRotation != VIPS_ANGLE_D0 ||
|
||||||
autoFlip ||
|
autoFlip ||
|
||||||
@@ -96,40 +96,46 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
baton->rotationAngle != 0.0);
|
baton->rotationAngle != 0.0);
|
||||||
|
|
||||||
if (autoRotation != VIPS_ANGLE_D0) {
|
if (autoRotation != VIPS_ANGLE_D0) {
|
||||||
|
if (autoRotation != VIPS_ANGLE_D180) {
|
||||||
|
MultiPageUnsupported(nPages, "Rotate");
|
||||||
|
}
|
||||||
image = image.rot(autoRotation);
|
image = image.rot(autoRotation);
|
||||||
autoRotation = VIPS_ANGLE_D0;
|
autoRotation = VIPS_ANGLE_D0;
|
||||||
}
|
}
|
||||||
if (autoFlip) {
|
if (autoFlip) {
|
||||||
image = image.flip(VIPS_DIRECTION_VERTICAL);
|
image = image.flip(VIPS_DIRECTION_VERTICAL);
|
||||||
autoFlip = FALSE;
|
autoFlip = false;
|
||||||
} else if (baton->flip) {
|
} else if (baton->flip) {
|
||||||
image = image.flip(VIPS_DIRECTION_VERTICAL);
|
image = image.flip(VIPS_DIRECTION_VERTICAL);
|
||||||
baton->flip = FALSE;
|
baton->flip = false;
|
||||||
}
|
}
|
||||||
if (autoFlop) {
|
if (autoFlop) {
|
||||||
image = image.flip(VIPS_DIRECTION_HORIZONTAL);
|
image = image.flip(VIPS_DIRECTION_HORIZONTAL);
|
||||||
autoFlop = FALSE;
|
autoFlop = false;
|
||||||
} else if (baton->flop) {
|
} else if (baton->flop) {
|
||||||
image = image.flip(VIPS_DIRECTION_HORIZONTAL);
|
image = image.flip(VIPS_DIRECTION_HORIZONTAL);
|
||||||
baton->flop = FALSE;
|
baton->flop = false;
|
||||||
}
|
}
|
||||||
if (rotation != VIPS_ANGLE_D0) {
|
if (rotation != VIPS_ANGLE_D0) {
|
||||||
|
if (rotation != VIPS_ANGLE_D180) {
|
||||||
|
MultiPageUnsupported(nPages, "Rotate");
|
||||||
|
}
|
||||||
image = image.rot(rotation);
|
image = image.rot(rotation);
|
||||||
rotation = VIPS_ANGLE_D0;
|
rotation = VIPS_ANGLE_D0;
|
||||||
}
|
}
|
||||||
if (baton->rotationAngle != 0.0) {
|
if (baton->rotationAngle != 0.0) {
|
||||||
MultiPageUnsupported(nPages, "Rotate");
|
MultiPageUnsupported(nPages, "Rotate");
|
||||||
std::vector<double> background;
|
std::vector<double> background;
|
||||||
std::tie(image, background) = sharp::ApplyAlpha(image, baton->rotationBackground, FALSE);
|
std::tie(image, background) = sharp::ApplyAlpha(image, baton->rotationBackground, false);
|
||||||
image = image.rotate(baton->rotationAngle, VImage::option()->set("background", background)).copy_memory();
|
image = image.rotate(baton->rotationAngle, VImage::option()->set("background", background)).copy_memory();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Trim
|
// Trim
|
||||||
if (baton->trimThreshold > 0.0) {
|
if (baton->trimThreshold >= 0.0) {
|
||||||
MultiPageUnsupported(nPages, "Trim");
|
MultiPageUnsupported(nPages, "Trim");
|
||||||
image = sharp::StaySequential(image, access);
|
image = sharp::StaySequential(image);
|
||||||
image = sharp::Trim(image, baton->trimBackground, baton->trimThreshold);
|
image = sharp::Trim(image, baton->trimBackground, baton->trimThreshold, baton->trimLineArt);
|
||||||
baton->trimOffsetLeft = image.xoffset();
|
baton->trimOffsetLeft = image.xoffset();
|
||||||
baton->trimOffsetTop = image.yoffset();
|
baton->trimOffsetTop = image.yoffset();
|
||||||
}
|
}
|
||||||
@@ -182,8 +188,8 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// - trimming or pre-resize extract isn't required;
|
// - trimming or pre-resize extract isn't required;
|
||||||
// - input colourspace is not specified;
|
// - input colourspace is not specified;
|
||||||
bool const shouldPreShrink = (targetResizeWidth > 0 || targetResizeHeight > 0) &&
|
bool const shouldPreShrink = (targetResizeWidth > 0 || targetResizeHeight > 0) &&
|
||||||
baton->gamma == 0 && baton->topOffsetPre == -1 && baton->trimThreshold == 0.0 &&
|
baton->gamma == 0 && baton->topOffsetPre == -1 && baton->trimThreshold < 0.0 &&
|
||||||
baton->colourspaceInput == VIPS_INTERPRETATION_LAST && !shouldRotateBefore;
|
baton->colourspacePipeline == VIPS_INTERPRETATION_LAST && !shouldRotateBefore;
|
||||||
|
|
||||||
if (shouldPreShrink) {
|
if (shouldPreShrink) {
|
||||||
// The common part of the shrink: the bit by which both axes must be shrunk
|
// The common part of the shrink: the bit by which both axes must be shrunk
|
||||||
@@ -315,17 +321,23 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Ensure we're using a device-independent colour space
|
// Ensure we're using a device-independent colour space
|
||||||
|
std::pair<char*, size_t> inputProfile(nullptr, 0);
|
||||||
|
if ((baton->keepMetadata & VIPS_FOREIGN_KEEP_ICC) && baton->withIccProfile.empty()) {
|
||||||
|
// Cache input profile for use with output
|
||||||
|
inputProfile = sharp::GetProfile(image);
|
||||||
|
}
|
||||||
char const *processingProfile = image.interpretation() == VIPS_INTERPRETATION_RGB16 ? "p3" : "srgb";
|
char const *processingProfile = image.interpretation() == VIPS_INTERPRETATION_RGB16 ? "p3" : "srgb";
|
||||||
if (
|
if (
|
||||||
sharp::HasProfile(image) &&
|
sharp::HasProfile(image) &&
|
||||||
image.interpretation() != VIPS_INTERPRETATION_LABS &&
|
image.interpretation() != VIPS_INTERPRETATION_LABS &&
|
||||||
image.interpretation() != VIPS_INTERPRETATION_GREY16 &&
|
image.interpretation() != VIPS_INTERPRETATION_GREY16 &&
|
||||||
|
baton->colourspacePipeline != VIPS_INTERPRETATION_CMYK &&
|
||||||
!baton->input->ignoreIcc
|
!baton->input->ignoreIcc
|
||||||
) {
|
) {
|
||||||
// Convert to sRGB/P3 using embedded profile
|
// Convert to sRGB/P3 using embedded profile
|
||||||
try {
|
try {
|
||||||
image = image.icc_transform(processingProfile, VImage::option()
|
image = image.icc_transform(processingProfile, VImage::option()
|
||||||
->set("embedded", TRUE)
|
->set("embedded", true)
|
||||||
->set("depth", sharp::Is16Bit(image.interpretation()) ? 16 : 8)
|
->set("depth", sharp::Is16Bit(image.interpretation()) ? 16 : 8)
|
||||||
->set("intent", VIPS_INTENT_PERCEPTUAL));
|
->set("intent", VIPS_INTENT_PERCEPTUAL));
|
||||||
} catch(...) {
|
} catch(...) {
|
||||||
@@ -333,7 +345,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
}
|
}
|
||||||
} else if (
|
} else if (
|
||||||
image.interpretation() == VIPS_INTERPRETATION_CMYK &&
|
image.interpretation() == VIPS_INTERPRETATION_CMYK &&
|
||||||
baton->colourspaceInput != VIPS_INTERPRETATION_CMYK
|
baton->colourspacePipeline != VIPS_INTERPRETATION_CMYK
|
||||||
) {
|
) {
|
||||||
image = image.icc_transform(processingProfile, VImage::option()
|
image = image.icc_transform(processingProfile, VImage::option()
|
||||||
->set("input_profile", "cmyk")
|
->set("input_profile", "cmyk")
|
||||||
@@ -345,11 +357,6 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
image = sharp::Flatten(image, baton->flattenBackground);
|
image = sharp::Flatten(image, baton->flattenBackground);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Negate the colours in the image
|
|
||||||
if (baton->negate) {
|
|
||||||
image = sharp::Negate(image, baton->negateAlpha);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gamma encoding (darken)
|
// Gamma encoding (darken)
|
||||||
if (baton->gamma >= 1 && baton->gamma <= 3) {
|
if (baton->gamma >= 1 && baton->gamma <= 3) {
|
||||||
image = sharp::Gamma(image, 1.0 / baton->gamma);
|
image = sharp::Gamma(image, 1.0 / baton->gamma);
|
||||||
@@ -385,13 +392,16 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
->set("kernel", baton->kernel));
|
->set("kernel", baton->kernel));
|
||||||
}
|
}
|
||||||
|
|
||||||
image = sharp::StaySequential(image, access,
|
image = sharp::StaySequential(image,
|
||||||
autoRotation != VIPS_ANGLE_D0 ||
|
autoRotation != VIPS_ANGLE_D0 ||
|
||||||
baton->flip ||
|
baton->flip ||
|
||||||
autoFlip ||
|
autoFlip ||
|
||||||
rotation != VIPS_ANGLE_D0);
|
rotation != VIPS_ANGLE_D0);
|
||||||
// Auto-rotate post-extract
|
// Auto-rotate post-extract
|
||||||
if (autoRotation != VIPS_ANGLE_D0) {
|
if (autoRotation != VIPS_ANGLE_D0) {
|
||||||
|
if (autoRotation != VIPS_ANGLE_D180) {
|
||||||
|
MultiPageUnsupported(nPages, "Rotate");
|
||||||
|
}
|
||||||
image = image.rot(autoRotation);
|
image = image.rot(autoRotation);
|
||||||
}
|
}
|
||||||
// Mirror vertically (up-down) about the x-axis
|
// Mirror vertically (up-down) about the x-axis
|
||||||
@@ -404,6 +414,9 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
}
|
}
|
||||||
// Rotate post-extract 90-angle
|
// Rotate post-extract 90-angle
|
||||||
if (rotation != VIPS_ANGLE_D0) {
|
if (rotation != VIPS_ANGLE_D0) {
|
||||||
|
if (rotation != VIPS_ANGLE_D180) {
|
||||||
|
MultiPageUnsupported(nPages, "Rotate");
|
||||||
|
}
|
||||||
image = image.rot(rotation);
|
image = image.rot(rotation);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -415,7 +428,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
for (unsigned int i = 0; i < baton->joinChannelIn.size(); i++) {
|
for (unsigned int i = 0; i < baton->joinChannelIn.size(); i++) {
|
||||||
baton->joinChannelIn[i]->access = access;
|
baton->joinChannelIn[i]->access = access;
|
||||||
std::tie(joinImage, joinImageType) = sharp::OpenInput(baton->joinChannelIn[i]);
|
std::tie(joinImage, joinImageType) = sharp::OpenInput(baton->joinChannelIn[i]);
|
||||||
joinImage = sharp::EnsureColourspace(joinImage, baton->colourspaceInput);
|
joinImage = sharp::EnsureColourspace(joinImage, baton->colourspacePipeline);
|
||||||
image = image.bandjoin(joinImage);
|
image = image.bandjoin(joinImage);
|
||||||
}
|
}
|
||||||
image = image.copy(VImage::option()->set("interpretation", baton->colourspace));
|
image = image.copy(VImage::option()->set("interpretation", baton->colourspace));
|
||||||
@@ -482,12 +495,10 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
|
|
||||||
// Attention-based or Entropy-based crop
|
// Attention-based or Entropy-based crop
|
||||||
MultiPageUnsupported(nPages, "Resize strategy");
|
MultiPageUnsupported(nPages, "Resize strategy");
|
||||||
image = sharp::StaySequential(image, access);
|
image = sharp::StaySequential(image);
|
||||||
image = image.smartcrop(baton->width, baton->height, VImage::option()
|
image = image.smartcrop(baton->width, baton->height, VImage::option()
|
||||||
->set("interesting", baton->position == 16 ? VIPS_INTERESTING_ENTROPY : VIPS_INTERESTING_ATTENTION)
|
->set("interesting", baton->position == 16 ? VIPS_INTERESTING_ENTROPY : VIPS_INTERESTING_ATTENTION)
|
||||||
#if (VIPS_MAJOR_VERSION >= 8 && VIPS_MINOR_VERSION >= 15)
|
|
||||||
->set("premultiplied", shouldPremultiplyAlpha)
|
->set("premultiplied", shouldPremultiplyAlpha)
|
||||||
#endif
|
|
||||||
->set("attention_x", &attention_x)
|
->set("attention_x", &attention_x)
|
||||||
->set("attention_y", &attention_y));
|
->set("attention_y", &attention_y));
|
||||||
baton->hasCropOffset = true;
|
baton->hasCropOffset = true;
|
||||||
@@ -503,7 +514,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// Rotate post-extract non-90 angle
|
// Rotate post-extract non-90 angle
|
||||||
if (!baton->rotateBeforePreExtract && baton->rotationAngle != 0.0) {
|
if (!baton->rotateBeforePreExtract && baton->rotationAngle != 0.0) {
|
||||||
MultiPageUnsupported(nPages, "Rotate");
|
MultiPageUnsupported(nPages, "Rotate");
|
||||||
image = sharp::StaySequential(image, access);
|
image = sharp::StaySequential(image);
|
||||||
std::vector<double> background;
|
std::vector<double> background;
|
||||||
std::tie(image, background) = sharp::ApplyAlpha(image, baton->rotationBackground, shouldPremultiplyAlpha);
|
std::tie(image, background) = sharp::ApplyAlpha(image, baton->rotationBackground, shouldPremultiplyAlpha);
|
||||||
image = image.rotate(baton->rotationAngle, VImage::option()->set("background", background));
|
image = image.rotate(baton->rotationAngle, VImage::option()->set("background", background));
|
||||||
@@ -527,7 +538,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// Affine transform
|
// Affine transform
|
||||||
if (!baton->affineMatrix.empty()) {
|
if (!baton->affineMatrix.empty()) {
|
||||||
MultiPageUnsupported(nPages, "Affine");
|
MultiPageUnsupported(nPages, "Affine");
|
||||||
image = sharp::StaySequential(image, access);
|
image = sharp::StaySequential(image);
|
||||||
std::vector<double> background;
|
std::vector<double> background;
|
||||||
std::tie(image, background) = sharp::ApplyAlpha(image, baton->affineBackground, shouldPremultiplyAlpha);
|
std::tie(image, background) = sharp::ApplyAlpha(image, baton->affineBackground, shouldPremultiplyAlpha);
|
||||||
vips::VInterpolate interp = vips::VInterpolate::new_from_name(
|
vips::VInterpolate interp = vips::VInterpolate::new_from_name(
|
||||||
@@ -550,6 +561,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
std::vector<double> background;
|
std::vector<double> background;
|
||||||
std::tie(image, background) = sharp::ApplyAlpha(image, baton->extendBackground, shouldPremultiplyAlpha);
|
std::tie(image, background) = sharp::ApplyAlpha(image, baton->extendBackground, shouldPremultiplyAlpha);
|
||||||
|
|
||||||
|
image = sharp::StaySequential(image, nPages > 1);
|
||||||
image = nPages > 1
|
image = nPages > 1
|
||||||
? sharp::EmbedMultiPage(image,
|
? sharp::EmbedMultiPage(image,
|
||||||
baton->extendLeft, baton->extendTop, baton->width, baton->height,
|
baton->extendLeft, baton->extendTop, baton->width, baton->height,
|
||||||
@@ -558,6 +570,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
VImage::option()->set("extend", baton->extendWith)->set("background", background));
|
VImage::option()->set("extend", baton->extendWith)->set("background", background));
|
||||||
} else {
|
} else {
|
||||||
std::vector<double> ignoredBackground(1);
|
std::vector<double> ignoredBackground(1);
|
||||||
|
image = sharp::StaySequential(image);
|
||||||
image = nPages > 1
|
image = nPages > 1
|
||||||
? sharp::EmbedMultiPage(image,
|
? sharp::EmbedMultiPage(image,
|
||||||
baton->extendLeft, baton->extendTop, baton->width, baton->height,
|
baton->extendLeft, baton->extendTop, baton->width, baton->height,
|
||||||
@@ -626,7 +639,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
sharp::ImageType compositeImageType = sharp::ImageType::UNKNOWN;
|
sharp::ImageType compositeImageType = sharp::ImageType::UNKNOWN;
|
||||||
composite->input->access = access;
|
composite->input->access = access;
|
||||||
std::tie(compositeImage, compositeImageType) = sharp::OpenInput(composite->input);
|
std::tie(compositeImage, compositeImageType) = sharp::OpenInput(composite->input);
|
||||||
compositeImage = sharp::EnsureColourspace(compositeImage, baton->colourspaceInput);
|
compositeImage = sharp::EnsureColourspace(compositeImage, baton->colourspacePipeline);
|
||||||
// Verify within current dimensions
|
// Verify within current dimensions
|
||||||
if (compositeImage.width() > image.width() || compositeImage.height() > image.height()) {
|
if (compositeImage.width() > image.width() || compositeImage.height() > image.height()) {
|
||||||
throw vips::VError("Image to composite must have same dimensions or smaller");
|
throw vips::VError("Image to composite must have same dimensions or smaller");
|
||||||
@@ -653,7 +666,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
if (across != 0 || down != 0) {
|
if (across != 0 || down != 0) {
|
||||||
int left;
|
int left;
|
||||||
int top;
|
int top;
|
||||||
compositeImage = sharp::StaySequential(compositeImage, access).replicate(across, down);
|
compositeImage = sharp::StaySequential(compositeImage).replicate(across, down);
|
||||||
if (composite->hasOffset) {
|
if (composite->hasOffset) {
|
||||||
std::tie(left, top) = sharp::CalculateCrop(
|
std::tie(left, top) = sharp::CalculateCrop(
|
||||||
compositeImage.width(), compositeImage.height(), image.width(), image.height(),
|
compositeImage.width(), compositeImage.height(), image.width(), image.height(),
|
||||||
@@ -711,13 +724,13 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
|
|
||||||
// Apply normalisation - stretch luminance to cover full dynamic range
|
// Apply normalisation - stretch luminance to cover full dynamic range
|
||||||
if (baton->normalise) {
|
if (baton->normalise) {
|
||||||
image = sharp::StaySequential(image, access);
|
image = sharp::StaySequential(image);
|
||||||
image = sharp::Normalise(image, baton->normaliseLower, baton->normaliseUpper);
|
image = sharp::Normalise(image, baton->normaliseLower, baton->normaliseUpper);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Apply contrast limiting adaptive histogram equalization (CLAHE)
|
// Apply contrast limiting adaptive histogram equalization (CLAHE)
|
||||||
if (baton->claheWidth != 0 && baton->claheHeight != 0) {
|
if (baton->claheWidth != 0 && baton->claheHeight != 0) {
|
||||||
image = sharp::StaySequential(image, access);
|
image = sharp::StaySequential(image);
|
||||||
image = sharp::Clahe(image, baton->claheWidth, baton->claheHeight, baton->claheMaxSlope);
|
image = sharp::Clahe(image, baton->claheWidth, baton->claheHeight, baton->claheMaxSlope);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -727,7 +740,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
sharp::ImageType booleanImageType = sharp::ImageType::UNKNOWN;
|
sharp::ImageType booleanImageType = sharp::ImageType::UNKNOWN;
|
||||||
baton->boolean->access = access;
|
baton->boolean->access = access;
|
||||||
std::tie(booleanImage, booleanImageType) = sharp::OpenInput(baton->boolean);
|
std::tie(booleanImage, booleanImageType) = sharp::OpenInput(baton->boolean);
|
||||||
booleanImage = sharp::EnsureColourspace(booleanImage, baton->colourspaceInput);
|
booleanImage = sharp::EnsureColourspace(booleanImage, baton->colourspacePipeline);
|
||||||
image = sharp::Boolean(image, booleanImage, baton->booleanOp);
|
image = sharp::Boolean(image, booleanImage, baton->booleanOp);
|
||||||
image = sharp::RemoveGifPalette(image);
|
image = sharp::RemoveGifPalette(image);
|
||||||
}
|
}
|
||||||
@@ -738,8 +751,8 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Tint the image
|
// Tint the image
|
||||||
if (baton->tintA < 128.0 || baton->tintB < 128.0) {
|
if (baton->tint[0] >= 0.0) {
|
||||||
image = sharp::Tint(image, baton->tintA, baton->tintB);
|
image = sharp::Tint(image, baton->tint);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove alpha channel, if any
|
// Remove alpha channel, if any
|
||||||
@@ -760,9 +773,10 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// Convert colourspace, pass the current known interpretation so libvips doesn't have to guess
|
// Convert colourspace, pass the current known interpretation so libvips doesn't have to guess
|
||||||
image = image.colourspace(baton->colourspace, VImage::option()->set("source_space", image.interpretation()));
|
image = image.colourspace(baton->colourspace, VImage::option()->set("source_space", image.interpretation()));
|
||||||
// Transform colours from embedded profile to output profile
|
// Transform colours from embedded profile to output profile
|
||||||
if (baton->withMetadata && sharp::HasProfile(image) && baton->withMetadataIcc.empty()) {
|
if ((baton->keepMetadata & VIPS_FOREIGN_KEEP_ICC) && baton->colourspacePipeline != VIPS_INTERPRETATION_CMYK &&
|
||||||
image = image.icc_transform("srgb", VImage::option()
|
baton->withIccProfile.empty() && sharp::HasProfile(image)) {
|
||||||
->set("embedded", TRUE)
|
image = image.icc_transform(processingProfile, VImage::option()
|
||||||
|
->set("embedded", true)
|
||||||
->set("depth", sharp::Is16Bit(image.interpretation()) ? 16 : 8)
|
->set("depth", sharp::Is16Bit(image.interpretation()) ? 16 : 8)
|
||||||
->set("intent", VIPS_INTENT_PERCEPTUAL));
|
->set("intent", VIPS_INTENT_PERCEPTUAL));
|
||||||
}
|
}
|
||||||
@@ -789,27 +803,40 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Apply output ICC profile
|
// Apply output ICC profile
|
||||||
if (baton->withMetadata) {
|
if (!baton->withIccProfile.empty()) {
|
||||||
image = image.icc_transform(
|
try {
|
||||||
baton->withMetadataIcc.empty() ? "srgb" : const_cast<char*>(baton->withMetadataIcc.data()),
|
image = image.icc_transform(const_cast<char*>(baton->withIccProfile.data()), VImage::option()
|
||||||
VImage::option()
|
|
||||||
->set("input_profile", processingProfile)
|
->set("input_profile", processingProfile)
|
||||||
->set("embedded", TRUE)
|
->set("embedded", true)
|
||||||
->set("depth", sharp::Is16Bit(image.interpretation()) ? 16 : 8)
|
->set("depth", sharp::Is16Bit(image.interpretation()) ? 16 : 8)
|
||||||
->set("intent", VIPS_INTENT_PERCEPTUAL));
|
->set("intent", VIPS_INTENT_PERCEPTUAL));
|
||||||
|
} catch(...) {
|
||||||
|
sharp::VipsWarningCallback(nullptr, G_LOG_LEVEL_WARNING, "Invalid profile", nullptr);
|
||||||
|
}
|
||||||
|
} else if (baton->keepMetadata & VIPS_FOREIGN_KEEP_ICC) {
|
||||||
|
image = sharp::SetProfile(image, inputProfile);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Negate the colours in the image
|
||||||
|
if (baton->negate) {
|
||||||
|
image = sharp::Negate(image, baton->negateAlpha);
|
||||||
|
}
|
||||||
|
|
||||||
// Override EXIF Orientation tag
|
// Override EXIF Orientation tag
|
||||||
if (baton->withMetadata && baton->withMetadataOrientation != -1) {
|
if (baton->withMetadataOrientation != -1) {
|
||||||
image = sharp::SetExifOrientation(image, baton->withMetadataOrientation);
|
image = sharp::SetExifOrientation(image, baton->withMetadataOrientation);
|
||||||
}
|
}
|
||||||
// Override pixel density
|
// Override pixel density
|
||||||
if (baton->withMetadataDensity > 0) {
|
if (baton->withMetadataDensity > 0) {
|
||||||
image = sharp::SetDensity(image, baton->withMetadataDensity);
|
image = sharp::SetDensity(image, baton->withMetadataDensity);
|
||||||
}
|
}
|
||||||
// Metadata key/value pairs, e.g. EXIF
|
// EXIF key/value pairs
|
||||||
if (!baton->withMetadataStrs.empty()) {
|
if (baton->keepMetadata & VIPS_FOREIGN_KEEP_EXIF) {
|
||||||
image = image.copy();
|
image = image.copy();
|
||||||
for (const auto& s : baton->withMetadataStrs) {
|
if (!baton->withExifMerge) {
|
||||||
|
image = sharp::RemoveExif(image);
|
||||||
|
}
|
||||||
|
for (const auto& s : baton->withExif) {
|
||||||
image.set(s.first.data(), s.second.data());
|
image.set(s.first.data(), s.second.data());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -830,7 +857,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// Write JPEG to buffer
|
// Write JPEG to buffer
|
||||||
sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG);
|
sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG);
|
||||||
VipsArea *area = reinterpret_cast<VipsArea*>(image.jpegsave_buffer(VImage::option()
|
VipsArea *area = reinterpret_cast<VipsArea*>(image.jpegsave_buffer(VImage::option()
|
||||||
->set("strip", !baton->withMetadata)
|
->set("keep", baton->keepMetadata)
|
||||||
->set("Q", baton->jpegQuality)
|
->set("Q", baton->jpegQuality)
|
||||||
->set("interlace", baton->jpegProgressive)
|
->set("interlace", baton->jpegProgressive)
|
||||||
->set("subsample_mode", baton->jpegChromaSubsampling == "4:4:4"
|
->set("subsample_mode", baton->jpegChromaSubsampling == "4:4:4"
|
||||||
@@ -872,7 +899,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// Write PNG to buffer
|
// Write PNG to buffer
|
||||||
sharp::AssertImageTypeDimensions(image, sharp::ImageType::PNG);
|
sharp::AssertImageTypeDimensions(image, sharp::ImageType::PNG);
|
||||||
VipsArea *area = reinterpret_cast<VipsArea*>(image.pngsave_buffer(VImage::option()
|
VipsArea *area = reinterpret_cast<VipsArea*>(image.pngsave_buffer(VImage::option()
|
||||||
->set("strip", !baton->withMetadata)
|
->set("keep", baton->keepMetadata)
|
||||||
->set("interlace", baton->pngProgressive)
|
->set("interlace", baton->pngProgressive)
|
||||||
->set("compression", baton->pngCompressionLevel)
|
->set("compression", baton->pngCompressionLevel)
|
||||||
->set("filter", baton->pngAdaptiveFiltering ? VIPS_FOREIGN_PNG_FILTER_ALL : VIPS_FOREIGN_PNG_FILTER_NONE)
|
->set("filter", baton->pngAdaptiveFiltering ? VIPS_FOREIGN_PNG_FILTER_ALL : VIPS_FOREIGN_PNG_FILTER_NONE)
|
||||||
@@ -891,7 +918,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// Write WEBP to buffer
|
// Write WEBP to buffer
|
||||||
sharp::AssertImageTypeDimensions(image, sharp::ImageType::WEBP);
|
sharp::AssertImageTypeDimensions(image, sharp::ImageType::WEBP);
|
||||||
VipsArea *area = reinterpret_cast<VipsArea*>(image.webpsave_buffer(VImage::option()
|
VipsArea *area = reinterpret_cast<VipsArea*>(image.webpsave_buffer(VImage::option()
|
||||||
->set("strip", !baton->withMetadata)
|
->set("keep", baton->keepMetadata)
|
||||||
->set("Q", baton->webpQuality)
|
->set("Q", baton->webpQuality)
|
||||||
->set("lossless", baton->webpLossless)
|
->set("lossless", baton->webpLossless)
|
||||||
->set("near_lossless", baton->webpNearLossless)
|
->set("near_lossless", baton->webpNearLossless)
|
||||||
@@ -911,7 +938,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// Write GIF to buffer
|
// Write GIF to buffer
|
||||||
sharp::AssertImageTypeDimensions(image, sharp::ImageType::GIF);
|
sharp::AssertImageTypeDimensions(image, sharp::ImageType::GIF);
|
||||||
VipsArea *area = reinterpret_cast<VipsArea*>(image.gifsave_buffer(VImage::option()
|
VipsArea *area = reinterpret_cast<VipsArea*>(image.gifsave_buffer(VImage::option()
|
||||||
->set("strip", !baton->withMetadata)
|
->set("keep", baton->keepMetadata)
|
||||||
->set("bitdepth", baton->gifBitdepth)
|
->set("bitdepth", baton->gifBitdepth)
|
||||||
->set("effort", baton->gifEffort)
|
->set("effort", baton->gifEffort)
|
||||||
->set("reuse", baton->gifReuse)
|
->set("reuse", baton->gifReuse)
|
||||||
@@ -936,10 +963,11 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
image = image.cast(VIPS_FORMAT_FLOAT);
|
image = image.cast(VIPS_FORMAT_FLOAT);
|
||||||
}
|
}
|
||||||
VipsArea *area = reinterpret_cast<VipsArea*>(image.tiffsave_buffer(VImage::option()
|
VipsArea *area = reinterpret_cast<VipsArea*>(image.tiffsave_buffer(VImage::option()
|
||||||
->set("strip", !baton->withMetadata)
|
->set("keep", baton->keepMetadata)
|
||||||
->set("Q", baton->tiffQuality)
|
->set("Q", baton->tiffQuality)
|
||||||
->set("bitdepth", baton->tiffBitdepth)
|
->set("bitdepth", baton->tiffBitdepth)
|
||||||
->set("compression", baton->tiffCompression)
|
->set("compression", baton->tiffCompression)
|
||||||
|
->set("miniswhite", baton->tiffMiniswhite)
|
||||||
->set("predictor", baton->tiffPredictor)
|
->set("predictor", baton->tiffPredictor)
|
||||||
->set("pyramid", baton->tiffPyramid)
|
->set("pyramid", baton->tiffPyramid)
|
||||||
->set("tile", baton->tiffTile)
|
->set("tile", baton->tiffTile)
|
||||||
@@ -959,11 +987,11 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF);
|
sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF);
|
||||||
image = sharp::RemoveAnimationProperties(image).cast(VIPS_FORMAT_UCHAR);
|
image = sharp::RemoveAnimationProperties(image).cast(VIPS_FORMAT_UCHAR);
|
||||||
VipsArea *area = reinterpret_cast<VipsArea*>(image.heifsave_buffer(VImage::option()
|
VipsArea *area = reinterpret_cast<VipsArea*>(image.heifsave_buffer(VImage::option()
|
||||||
->set("strip", !baton->withMetadata)
|
->set("keep", baton->keepMetadata)
|
||||||
->set("Q", baton->heifQuality)
|
->set("Q", baton->heifQuality)
|
||||||
->set("compression", baton->heifCompression)
|
->set("compression", baton->heifCompression)
|
||||||
->set("effort", baton->heifEffort)
|
->set("effort", baton->heifEffort)
|
||||||
->set("bitdepth", 8)
|
->set("bitdepth", baton->heifBitdepth)
|
||||||
->set("subsample_mode", baton->heifChromaSubsampling == "4:4:4"
|
->set("subsample_mode", baton->heifChromaSubsampling == "4:4:4"
|
||||||
? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON)
|
? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON)
|
||||||
->set("lossless", baton->heifLossless)));
|
->set("lossless", baton->heifLossless)));
|
||||||
@@ -978,7 +1006,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
if (!sharp::HasAlpha(image)) {
|
if (!sharp::HasAlpha(image)) {
|
||||||
baton->tileBackground.pop_back();
|
baton->tileBackground.pop_back();
|
||||||
}
|
}
|
||||||
image = sharp::StaySequential(image, access, baton->tileAngle != 0);
|
image = sharp::StaySequential(image, baton->tileAngle != 0);
|
||||||
vips::VOption *options = BuildOptionsDZ(baton);
|
vips::VOption *options = BuildOptionsDZ(baton);
|
||||||
VipsArea *area = reinterpret_cast<VipsArea*>(image.dzsave_buffer(options));
|
VipsArea *area = reinterpret_cast<VipsArea*>(image.dzsave_buffer(options));
|
||||||
baton->bufferOut = static_cast<char*>(area->data);
|
baton->bufferOut = static_cast<char*>(area->data);
|
||||||
@@ -991,7 +1019,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// Write JXL to buffer
|
// Write JXL to buffer
|
||||||
image = sharp::RemoveAnimationProperties(image);
|
image = sharp::RemoveAnimationProperties(image);
|
||||||
VipsArea *area = reinterpret_cast<VipsArea*>(image.jxlsave_buffer(VImage::option()
|
VipsArea *area = reinterpret_cast<VipsArea*>(image.jxlsave_buffer(VImage::option()
|
||||||
->set("strip", !baton->withMetadata)
|
->set("keep", baton->keepMetadata)
|
||||||
->set("distance", baton->jxlDistance)
|
->set("distance", baton->jxlDistance)
|
||||||
->set("tier", baton->jxlDecodingTier)
|
->set("tier", baton->jxlDecodingTier)
|
||||||
->set("effort", baton->jxlEffort)
|
->set("effort", baton->jxlEffort)
|
||||||
@@ -1052,7 +1080,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// Write JPEG to file
|
// Write JPEG to file
|
||||||
sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG);
|
sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG);
|
||||||
image.jpegsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
|
image.jpegsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
|
||||||
->set("strip", !baton->withMetadata)
|
->set("keep", baton->keepMetadata)
|
||||||
->set("Q", baton->jpegQuality)
|
->set("Q", baton->jpegQuality)
|
||||||
->set("interlace", baton->jpegProgressive)
|
->set("interlace", baton->jpegProgressive)
|
||||||
->set("subsample_mode", baton->jpegChromaSubsampling == "4:4:4"
|
->set("subsample_mode", baton->jpegChromaSubsampling == "4:4:4"
|
||||||
@@ -1082,7 +1110,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// Write PNG to file
|
// Write PNG to file
|
||||||
sharp::AssertImageTypeDimensions(image, sharp::ImageType::PNG);
|
sharp::AssertImageTypeDimensions(image, sharp::ImageType::PNG);
|
||||||
image.pngsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
|
image.pngsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
|
||||||
->set("strip", !baton->withMetadata)
|
->set("keep", baton->keepMetadata)
|
||||||
->set("interlace", baton->pngProgressive)
|
->set("interlace", baton->pngProgressive)
|
||||||
->set("compression", baton->pngCompressionLevel)
|
->set("compression", baton->pngCompressionLevel)
|
||||||
->set("filter", baton->pngAdaptiveFiltering ? VIPS_FOREIGN_PNG_FILTER_ALL : VIPS_FOREIGN_PNG_FILTER_NONE)
|
->set("filter", baton->pngAdaptiveFiltering ? VIPS_FOREIGN_PNG_FILTER_ALL : VIPS_FOREIGN_PNG_FILTER_NONE)
|
||||||
@@ -1097,7 +1125,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// Write WEBP to file
|
// Write WEBP to file
|
||||||
sharp::AssertImageTypeDimensions(image, sharp::ImageType::WEBP);
|
sharp::AssertImageTypeDimensions(image, sharp::ImageType::WEBP);
|
||||||
image.webpsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
|
image.webpsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
|
||||||
->set("strip", !baton->withMetadata)
|
->set("keep", baton->keepMetadata)
|
||||||
->set("Q", baton->webpQuality)
|
->set("Q", baton->webpQuality)
|
||||||
->set("lossless", baton->webpLossless)
|
->set("lossless", baton->webpLossless)
|
||||||
->set("near_lossless", baton->webpNearLossless)
|
->set("near_lossless", baton->webpNearLossless)
|
||||||
@@ -1113,7 +1141,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// Write GIF to file
|
// Write GIF to file
|
||||||
sharp::AssertImageTypeDimensions(image, sharp::ImageType::GIF);
|
sharp::AssertImageTypeDimensions(image, sharp::ImageType::GIF);
|
||||||
image.gifsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
|
image.gifsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
|
||||||
->set("strip", !baton->withMetadata)
|
->set("keep", baton->keepMetadata)
|
||||||
->set("bitdepth", baton->gifBitdepth)
|
->set("bitdepth", baton->gifBitdepth)
|
||||||
->set("effort", baton->gifEffort)
|
->set("effort", baton->gifEffort)
|
||||||
->set("reuse", baton->gifReuse)
|
->set("reuse", baton->gifReuse)
|
||||||
@@ -1132,10 +1160,11 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
image = image.cast(VIPS_FORMAT_FLOAT);
|
image = image.cast(VIPS_FORMAT_FLOAT);
|
||||||
}
|
}
|
||||||
image.tiffsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
|
image.tiffsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
|
||||||
->set("strip", !baton->withMetadata)
|
->set("keep", baton->keepMetadata)
|
||||||
->set("Q", baton->tiffQuality)
|
->set("Q", baton->tiffQuality)
|
||||||
->set("bitdepth", baton->tiffBitdepth)
|
->set("bitdepth", baton->tiffBitdepth)
|
||||||
->set("compression", baton->tiffCompression)
|
->set("compression", baton->tiffCompression)
|
||||||
|
->set("miniswhite", baton->tiffMiniswhite)
|
||||||
->set("predictor", baton->tiffPredictor)
|
->set("predictor", baton->tiffPredictor)
|
||||||
->set("pyramid", baton->tiffPyramid)
|
->set("pyramid", baton->tiffPyramid)
|
||||||
->set("tile", baton->tiffTile)
|
->set("tile", baton->tiffTile)
|
||||||
@@ -1151,11 +1180,11 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF);
|
sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF);
|
||||||
image = sharp::RemoveAnimationProperties(image).cast(VIPS_FORMAT_UCHAR);
|
image = sharp::RemoveAnimationProperties(image).cast(VIPS_FORMAT_UCHAR);
|
||||||
image.heifsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
|
image.heifsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
|
||||||
->set("strip", !baton->withMetadata)
|
->set("keep", baton->keepMetadata)
|
||||||
->set("Q", baton->heifQuality)
|
->set("Q", baton->heifQuality)
|
||||||
->set("compression", baton->heifCompression)
|
->set("compression", baton->heifCompression)
|
||||||
->set("effort", baton->heifEffort)
|
->set("effort", baton->heifEffort)
|
||||||
->set("bitdepth", 8)
|
->set("bitdepth", baton->heifBitdepth)
|
||||||
->set("subsample_mode", baton->heifChromaSubsampling == "4:4:4"
|
->set("subsample_mode", baton->heifChromaSubsampling == "4:4:4"
|
||||||
? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON)
|
? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON)
|
||||||
->set("lossless", baton->heifLossless));
|
->set("lossless", baton->heifLossless));
|
||||||
@@ -1165,7 +1194,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// Write JXL to file
|
// Write JXL to file
|
||||||
image = sharp::RemoveAnimationProperties(image);
|
image = sharp::RemoveAnimationProperties(image);
|
||||||
image.jxlsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
|
image.jxlsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
|
||||||
->set("strip", !baton->withMetadata)
|
->set("keep", baton->keepMetadata)
|
||||||
->set("distance", baton->jxlDistance)
|
->set("distance", baton->jxlDistance)
|
||||||
->set("tier", baton->jxlDecodingTier)
|
->set("tier", baton->jxlDecodingTier)
|
||||||
->set("effort", baton->jxlEffort)
|
->set("effort", baton->jxlEffort)
|
||||||
@@ -1179,7 +1208,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
if (!sharp::HasAlpha(image)) {
|
if (!sharp::HasAlpha(image)) {
|
||||||
baton->tileBackground.pop_back();
|
baton->tileBackground.pop_back();
|
||||||
}
|
}
|
||||||
image = sharp::StaySequential(image, access, baton->tileAngle != 0);
|
image = sharp::StaySequential(image, baton->tileAngle != 0);
|
||||||
vips::VOption *options = BuildOptionsDZ(baton);
|
vips::VOption *options = BuildOptionsDZ(baton);
|
||||||
image.dzsave(const_cast<char*>(baton->fileOut.data()), options);
|
image.dzsave(const_cast<char*>(baton->fileOut.data()), options);
|
||||||
baton->formatOut = "dz";
|
baton->formatOut = "dz";
|
||||||
@@ -1187,7 +1216,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
(willMatchInput && inputImageType == sharp::ImageType::VIPS)) {
|
(willMatchInput && inputImageType == sharp::ImageType::VIPS)) {
|
||||||
// Write V to file
|
// Write V to file
|
||||||
image.vipssave(const_cast<char*>(baton->fileOut.data()), VImage::option()
|
image.vipssave(const_cast<char*>(baton->fileOut.data()), VImage::option()
|
||||||
->set("strip", !baton->withMetadata));
|
->set("keep", baton->keepMetadata));
|
||||||
baton->formatOut = "v";
|
baton->formatOut = "v";
|
||||||
} else {
|
} else {
|
||||||
// Unsupported output format
|
// Unsupported output format
|
||||||
@@ -1215,7 +1244,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// Handle warnings
|
// Handle warnings
|
||||||
std::string warning = sharp::VipsWarningPop();
|
std::string warning = sharp::VipsWarningPop();
|
||||||
while (!warning.empty()) {
|
while (!warning.empty()) {
|
||||||
debuglog.MakeCallback(Receiver().Value(), { Napi::String::New(env, warning) });
|
debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) });
|
||||||
warning = sharp::VipsWarningPop();
|
warning = sharp::VipsWarningPop();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1248,11 +1277,10 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
info.Set("attentionX", static_cast<int32_t>(baton->attentionX));
|
info.Set("attentionX", static_cast<int32_t>(baton->attentionX));
|
||||||
info.Set("attentionY", static_cast<int32_t>(baton->attentionY));
|
info.Set("attentionY", static_cast<int32_t>(baton->attentionY));
|
||||||
}
|
}
|
||||||
if (baton->trimThreshold > 0.0) {
|
if (baton->trimThreshold >= 0.0) {
|
||||||
info.Set("trimOffsetLeft", static_cast<int32_t>(baton->trimOffsetLeft));
|
info.Set("trimOffsetLeft", static_cast<int32_t>(baton->trimOffsetLeft));
|
||||||
info.Set("trimOffsetTop", static_cast<int32_t>(baton->trimOffsetTop));
|
info.Set("trimOffsetTop", static_cast<int32_t>(baton->trimOffsetTop));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (baton->input->textAutofitDpi) {
|
if (baton->input->textAutofitDpi) {
|
||||||
info.Set("textAutofitDpi", static_cast<uint32_t>(baton->input->textAutofitDpi));
|
info.Set("textAutofitDpi", static_cast<uint32_t>(baton->input->textAutofitDpi));
|
||||||
}
|
}
|
||||||
@@ -1263,17 +1291,17 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// Pass ownership of output data to Buffer instance
|
// Pass ownership of output data to Buffer instance
|
||||||
Napi::Buffer<char> data = Napi::Buffer<char>::NewOrCopy(env, static_cast<char*>(baton->bufferOut),
|
Napi::Buffer<char> data = Napi::Buffer<char>::NewOrCopy(env, static_cast<char*>(baton->bufferOut),
|
||||||
baton->bufferOutLength, sharp::FreeCallback);
|
baton->bufferOutLength, sharp::FreeCallback);
|
||||||
Callback().MakeCallback(Receiver().Value(), { env.Null(), data, info });
|
Callback().Call(Receiver().Value(), { env.Null(), data, info });
|
||||||
} else {
|
} else {
|
||||||
// Add file size to info
|
// Add file size to info
|
||||||
struct STAT64_STRUCT st;
|
struct STAT64_STRUCT st;
|
||||||
if (STAT64_FUNCTION(baton->fileOut.data(), &st) == 0) {
|
if (STAT64_FUNCTION(baton->fileOut.data(), &st) == 0) {
|
||||||
info.Set("size", static_cast<uint32_t>(st.st_size));
|
info.Set("size", static_cast<uint32_t>(st.st_size));
|
||||||
}
|
}
|
||||||
Callback().MakeCallback(Receiver().Value(), { env.Null(), info });
|
Callback().Call(Receiver().Value(), { env.Null(), info });
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Callback().MakeCallback(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() });
|
Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete baton
|
// Delete baton
|
||||||
@@ -1291,7 +1319,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
// Decrement processing task counter
|
// Decrement processing task counter
|
||||||
sharp::counterProcess--;
|
sharp::counterProcess--;
|
||||||
Napi::Number queueLength = Napi::Number::New(env, static_cast<int>(sharp::counterQueue));
|
Napi::Number queueLength = Napi::Number::New(env, static_cast<int>(sharp::counterQueue));
|
||||||
queueListener.MakeCallback(Receiver().Value(), { queueLength });
|
queueListener.Call(Receiver().Value(), { queueLength });
|
||||||
}
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -1312,16 +1340,16 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
std::tuple<VipsAngle, bool, bool>
|
std::tuple<VipsAngle, bool, bool>
|
||||||
CalculateExifRotationAndFlip(int const exifOrientation) {
|
CalculateExifRotationAndFlip(int const exifOrientation) {
|
||||||
VipsAngle rotate = VIPS_ANGLE_D0;
|
VipsAngle rotate = VIPS_ANGLE_D0;
|
||||||
bool flip = FALSE;
|
bool flip = false;
|
||||||
bool flop = FALSE;
|
bool flop = false;
|
||||||
switch (exifOrientation) {
|
switch (exifOrientation) {
|
||||||
case 6: rotate = VIPS_ANGLE_D90; break;
|
case 6: rotate = VIPS_ANGLE_D90; break;
|
||||||
case 3: rotate = VIPS_ANGLE_D180; break;
|
case 3: rotate = VIPS_ANGLE_D180; break;
|
||||||
case 8: rotate = VIPS_ANGLE_D270; break;
|
case 8: rotate = VIPS_ANGLE_D270; break;
|
||||||
case 2: flop = TRUE; break; // flop 1
|
case 2: flop = true; break; // flop 1
|
||||||
case 7: flip = TRUE; rotate = VIPS_ANGLE_D90; break; // flip 6
|
case 7: flip = true; rotate = VIPS_ANGLE_D90; break; // flip 6
|
||||||
case 4: flop = TRUE; rotate = VIPS_ANGLE_D180; break; // flop 3
|
case 4: flop = true; rotate = VIPS_ANGLE_D180; break; // flop 3
|
||||||
case 5: flip = TRUE; rotate = VIPS_ANGLE_D270; break; // flip 8
|
case 5: flip = true; rotate = VIPS_ANGLE_D270; break; // flip 8
|
||||||
}
|
}
|
||||||
return std::make_tuple(rotate, flip, flop);
|
return std::make_tuple(rotate, flip, flop);
|
||||||
}
|
}
|
||||||
@@ -1369,7 +1397,7 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
std::string suffix;
|
std::string suffix;
|
||||||
if (baton->tileFormat == "png") {
|
if (baton->tileFormat == "png") {
|
||||||
std::vector<std::pair<std::string, std::string>> options {
|
std::vector<std::pair<std::string, std::string>> options {
|
||||||
{"interlace", baton->pngProgressive ? "TRUE" : "FALSE"},
|
{"interlace", baton->pngProgressive ? "true" : "false"},
|
||||||
{"compression", std::to_string(baton->pngCompressionLevel)},
|
{"compression", std::to_string(baton->pngCompressionLevel)},
|
||||||
{"filter", baton->pngAdaptiveFiltering ? "all" : "none"}
|
{"filter", baton->pngAdaptiveFiltering ? "all" : "none"}
|
||||||
};
|
};
|
||||||
@@ -1378,31 +1406,31 @@ class PipelineWorker : public Napi::AsyncWorker {
|
|||||||
std::vector<std::pair<std::string, std::string>> options {
|
std::vector<std::pair<std::string, std::string>> options {
|
||||||
{"Q", std::to_string(baton->webpQuality)},
|
{"Q", std::to_string(baton->webpQuality)},
|
||||||
{"alpha_q", std::to_string(baton->webpAlphaQuality)},
|
{"alpha_q", std::to_string(baton->webpAlphaQuality)},
|
||||||
{"lossless", baton->webpLossless ? "TRUE" : "FALSE"},
|
{"lossless", baton->webpLossless ? "true" : "false"},
|
||||||
{"near_lossless", baton->webpNearLossless ? "TRUE" : "FALSE"},
|
{"near_lossless", baton->webpNearLossless ? "true" : "false"},
|
||||||
{"smart_subsample", baton->webpSmartSubsample ? "TRUE" : "FALSE"},
|
{"smart_subsample", baton->webpSmartSubsample ? "true" : "false"},
|
||||||
{"preset", vips_enum_nick(VIPS_TYPE_FOREIGN_WEBP_PRESET, baton->webpPreset)},
|
{"preset", vips_enum_nick(VIPS_TYPE_FOREIGN_WEBP_PRESET, baton->webpPreset)},
|
||||||
{"min_size", baton->webpMinSize ? "TRUE" : "FALSE"},
|
{"min_size", baton->webpMinSize ? "true" : "false"},
|
||||||
{"mixed", baton->webpMixed ? "TRUE" : "FALSE"},
|
{"mixed", baton->webpMixed ? "true" : "false"},
|
||||||
{"effort", std::to_string(baton->webpEffort)}
|
{"effort", std::to_string(baton->webpEffort)}
|
||||||
};
|
};
|
||||||
suffix = AssembleSuffixString(".webp", options);
|
suffix = AssembleSuffixString(".webp", options);
|
||||||
} else {
|
} else {
|
||||||
std::vector<std::pair<std::string, std::string>> options {
|
std::vector<std::pair<std::string, std::string>> options {
|
||||||
{"Q", std::to_string(baton->jpegQuality)},
|
{"Q", std::to_string(baton->jpegQuality)},
|
||||||
{"interlace", baton->jpegProgressive ? "TRUE" : "FALSE"},
|
{"interlace", baton->jpegProgressive ? "true" : "false"},
|
||||||
{"subsample_mode", baton->jpegChromaSubsampling == "4:4:4" ? "off" : "on"},
|
{"subsample_mode", baton->jpegChromaSubsampling == "4:4:4" ? "off" : "on"},
|
||||||
{"trellis_quant", baton->jpegTrellisQuantisation ? "TRUE" : "FALSE"},
|
{"trellis_quant", baton->jpegTrellisQuantisation ? "true" : "false"},
|
||||||
{"quant_table", std::to_string(baton->jpegQuantisationTable)},
|
{"quant_table", std::to_string(baton->jpegQuantisationTable)},
|
||||||
{"overshoot_deringing", baton->jpegOvershootDeringing ? "TRUE": "FALSE"},
|
{"overshoot_deringing", baton->jpegOvershootDeringing ? "true": "false"},
|
||||||
{"optimize_scans", baton->jpegOptimiseScans ? "TRUE": "FALSE"},
|
{"optimize_scans", baton->jpegOptimiseScans ? "true": "false"},
|
||||||
{"optimize_coding", baton->jpegOptimiseCoding ? "TRUE": "FALSE"}
|
{"optimize_coding", baton->jpegOptimiseCoding ? "true": "false"}
|
||||||
};
|
};
|
||||||
std::string extname = baton->tileLayout == VIPS_FOREIGN_DZ_LAYOUT_DZ ? ".jpeg" : ".jpg";
|
std::string extname = baton->tileLayout == VIPS_FOREIGN_DZ_LAYOUT_DZ ? ".jpeg" : ".jpg";
|
||||||
suffix = AssembleSuffixString(extname, options);
|
suffix = AssembleSuffixString(extname, options);
|
||||||
}
|
}
|
||||||
vips::VOption *options = VImage::option()
|
vips::VOption *options = VImage::option()
|
||||||
->set("strip", !baton->withMetadata)
|
->set("keep", baton->keepMetadata)
|
||||||
->set("tile_size", baton->tileSize)
|
->set("tile_size", baton->tileSize)
|
||||||
->set("overlap", baton->tileOverlap)
|
->set("overlap", baton->tileOverlap)
|
||||||
->set("container", baton->tileContainer)
|
->set("container", baton->tileContainer)
|
||||||
@@ -1519,6 +1547,7 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
|
|||||||
baton->thresholdGrayscale = sharp::AttrAsBool(options, "thresholdGrayscale");
|
baton->thresholdGrayscale = sharp::AttrAsBool(options, "thresholdGrayscale");
|
||||||
baton->trimBackground = sharp::AttrAsVectorOfDouble(options, "trimBackground");
|
baton->trimBackground = sharp::AttrAsVectorOfDouble(options, "trimBackground");
|
||||||
baton->trimThreshold = sharp::AttrAsDouble(options, "trimThreshold");
|
baton->trimThreshold = sharp::AttrAsDouble(options, "trimThreshold");
|
||||||
|
baton->trimLineArt = sharp::AttrAsBool(options, "trimLineArt");
|
||||||
baton->gamma = sharp::AttrAsDouble(options, "gamma");
|
baton->gamma = sharp::AttrAsDouble(options, "gamma");
|
||||||
baton->gammaOut = sharp::AttrAsDouble(options, "gammaOut");
|
baton->gammaOut = sharp::AttrAsDouble(options, "gammaOut");
|
||||||
baton->linearA = sharp::AttrAsVectorOfDouble(options, "linearA");
|
baton->linearA = sharp::AttrAsVectorOfDouble(options, "linearA");
|
||||||
@@ -1527,8 +1556,7 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
|
|||||||
baton->normalise = sharp::AttrAsBool(options, "normalise");
|
baton->normalise = sharp::AttrAsBool(options, "normalise");
|
||||||
baton->normaliseLower = sharp::AttrAsUint32(options, "normaliseLower");
|
baton->normaliseLower = sharp::AttrAsUint32(options, "normaliseLower");
|
||||||
baton->normaliseUpper = sharp::AttrAsUint32(options, "normaliseUpper");
|
baton->normaliseUpper = sharp::AttrAsUint32(options, "normaliseUpper");
|
||||||
baton->tintA = sharp::AttrAsDouble(options, "tintA");
|
baton->tint = sharp::AttrAsVectorOfDouble(options, "tint");
|
||||||
baton->tintB = sharp::AttrAsDouble(options, "tintB");
|
|
||||||
baton->claheWidth = sharp::AttrAsUint32(options, "claheWidth");
|
baton->claheWidth = sharp::AttrAsUint32(options, "claheWidth");
|
||||||
baton->claheHeight = sharp::AttrAsUint32(options, "claheHeight");
|
baton->claheHeight = sharp::AttrAsUint32(options, "claheHeight");
|
||||||
baton->claheMaxSlope = sharp::AttrAsUint32(options, "claheMaxSlope");
|
baton->claheMaxSlope = sharp::AttrAsUint32(options, "claheMaxSlope");
|
||||||
@@ -1582,10 +1610,10 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
|
|||||||
baton->recombMatrix[i] = sharp::AttrAsDouble(recombMatrix, i);
|
baton->recombMatrix[i] = sharp::AttrAsDouble(recombMatrix, i);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
baton->colourspaceInput = sharp::AttrAsEnum<VipsInterpretation>(
|
baton->colourspacePipeline = sharp::AttrAsEnum<VipsInterpretation>(
|
||||||
options, "colourspaceInput", VIPS_TYPE_INTERPRETATION);
|
options, "colourspacePipeline", VIPS_TYPE_INTERPRETATION);
|
||||||
if (baton->colourspaceInput == VIPS_INTERPRETATION_ERROR) {
|
if (baton->colourspacePipeline == VIPS_INTERPRETATION_ERROR) {
|
||||||
baton->colourspaceInput = VIPS_INTERPRETATION_LAST;
|
baton->colourspacePipeline = VIPS_INTERPRETATION_LAST;
|
||||||
}
|
}
|
||||||
baton->colourspace = sharp::AttrAsEnum<VipsInterpretation>(options, "colourspace", VIPS_TYPE_INTERPRETATION);
|
baton->colourspace = sharp::AttrAsEnum<VipsInterpretation>(options, "colourspace", VIPS_TYPE_INTERPRETATION);
|
||||||
if (baton->colourspace == VIPS_INTERPRETATION_ERROR) {
|
if (baton->colourspace == VIPS_INTERPRETATION_ERROR) {
|
||||||
@@ -1594,18 +1622,19 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
|
|||||||
// Output
|
// Output
|
||||||
baton->formatOut = sharp::AttrAsStr(options, "formatOut");
|
baton->formatOut = sharp::AttrAsStr(options, "formatOut");
|
||||||
baton->fileOut = sharp::AttrAsStr(options, "fileOut");
|
baton->fileOut = sharp::AttrAsStr(options, "fileOut");
|
||||||
baton->withMetadata = sharp::AttrAsBool(options, "withMetadata");
|
baton->keepMetadata = sharp::AttrAsUint32(options, "keepMetadata");
|
||||||
baton->withMetadataOrientation = sharp::AttrAsUint32(options, "withMetadataOrientation");
|
baton->withMetadataOrientation = sharp::AttrAsUint32(options, "withMetadataOrientation");
|
||||||
baton->withMetadataDensity = sharp::AttrAsDouble(options, "withMetadataDensity");
|
baton->withMetadataDensity = sharp::AttrAsDouble(options, "withMetadataDensity");
|
||||||
baton->withMetadataIcc = sharp::AttrAsStr(options, "withMetadataIcc");
|
baton->withIccProfile = sharp::AttrAsStr(options, "withIccProfile");
|
||||||
Napi::Object mdStrs = options.Get("withMetadataStrs").As<Napi::Object>();
|
Napi::Object withExif = options.Get("withExif").As<Napi::Object>();
|
||||||
Napi::Array mdStrKeys = mdStrs.GetPropertyNames();
|
Napi::Array withExifKeys = withExif.GetPropertyNames();
|
||||||
for (unsigned int i = 0; i < mdStrKeys.Length(); i++) {
|
for (unsigned int i = 0; i < withExifKeys.Length(); i++) {
|
||||||
std::string k = sharp::AttrAsStr(mdStrKeys, i);
|
std::string k = sharp::AttrAsStr(withExifKeys, i);
|
||||||
if (mdStrs.HasOwnProperty(k)) {
|
if (withExif.HasOwnProperty(k)) {
|
||||||
baton->withMetadataStrs.insert(std::make_pair(k, sharp::AttrAsStr(mdStrs, k)));
|
baton->withExif.insert(std::make_pair(k, sharp::AttrAsStr(withExif, k)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
baton->withExifMerge = sharp::AttrAsBool(options, "withExifMerge");
|
||||||
baton->timeoutSeconds = sharp::AttrAsUint32(options, "timeoutSeconds");
|
baton->timeoutSeconds = sharp::AttrAsUint32(options, "timeoutSeconds");
|
||||||
// Format-specific
|
// Format-specific
|
||||||
baton->jpegQuality = sharp::AttrAsUint32(options, "jpegQuality");
|
baton->jpegQuality = sharp::AttrAsUint32(options, "jpegQuality");
|
||||||
@@ -1647,6 +1676,7 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
|
|||||||
baton->gifProgressive = sharp::AttrAsBool(options, "gifProgressive");
|
baton->gifProgressive = sharp::AttrAsBool(options, "gifProgressive");
|
||||||
baton->tiffQuality = sharp::AttrAsUint32(options, "tiffQuality");
|
baton->tiffQuality = sharp::AttrAsUint32(options, "tiffQuality");
|
||||||
baton->tiffPyramid = sharp::AttrAsBool(options, "tiffPyramid");
|
baton->tiffPyramid = sharp::AttrAsBool(options, "tiffPyramid");
|
||||||
|
baton->tiffMiniswhite = sharp::AttrAsBool(options, "tiffMiniswhite");
|
||||||
baton->tiffBitdepth = sharp::AttrAsUint32(options, "tiffBitdepth");
|
baton->tiffBitdepth = sharp::AttrAsUint32(options, "tiffBitdepth");
|
||||||
baton->tiffTile = sharp::AttrAsBool(options, "tiffTile");
|
baton->tiffTile = sharp::AttrAsBool(options, "tiffTile");
|
||||||
baton->tiffTileWidth = sharp::AttrAsUint32(options, "tiffTileWidth");
|
baton->tiffTileWidth = sharp::AttrAsUint32(options, "tiffTileWidth");
|
||||||
@@ -1668,6 +1698,7 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
|
|||||||
options, "heifCompression", VIPS_TYPE_FOREIGN_HEIF_COMPRESSION);
|
options, "heifCompression", VIPS_TYPE_FOREIGN_HEIF_COMPRESSION);
|
||||||
baton->heifEffort = sharp::AttrAsUint32(options, "heifEffort");
|
baton->heifEffort = sharp::AttrAsUint32(options, "heifEffort");
|
||||||
baton->heifChromaSubsampling = sharp::AttrAsStr(options, "heifChromaSubsampling");
|
baton->heifChromaSubsampling = sharp::AttrAsStr(options, "heifChromaSubsampling");
|
||||||
|
baton->heifBitdepth = sharp::AttrAsUint32(options, "heifBitdepth");
|
||||||
baton->jxlDistance = sharp::AttrAsDouble(options, "jxlDistance");
|
baton->jxlDistance = sharp::AttrAsDouble(options, "jxlDistance");
|
||||||
baton->jxlDecodingTier = sharp::AttrAsUint32(options, "jxlDecodingTier");
|
baton->jxlDecodingTier = sharp::AttrAsUint32(options, "jxlDecodingTier");
|
||||||
baton->jxlEffort = sharp::AttrAsUint32(options, "jxlEffort");
|
baton->jxlEffort = sharp::AttrAsUint32(options, "jxlEffort");
|
||||||
@@ -1708,7 +1739,7 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) {
|
|||||||
|
|
||||||
// Increment queued task counter
|
// Increment queued task counter
|
||||||
Napi::Number queueLength = Napi::Number::New(info.Env(), static_cast<int>(++sharp::counterQueue));
|
Napi::Number queueLength = Napi::Number::New(info.Env(), static_cast<int>(++sharp::counterQueue));
|
||||||
queueListener.MakeCallback(info.This(), { queueLength });
|
queueListener.Call(info.This(), { queueLength });
|
||||||
|
|
||||||
return info.Env().Undefined();
|
return info.Env().Undefined();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -69,8 +69,7 @@ struct PipelineBaton {
|
|||||||
bool premultiplied;
|
bool premultiplied;
|
||||||
bool tileCentre;
|
bool tileCentre;
|
||||||
bool fastShrinkOnLoad;
|
bool fastShrinkOnLoad;
|
||||||
double tintA;
|
std::vector<double> tint;
|
||||||
double tintB;
|
|
||||||
bool flatten;
|
bool flatten;
|
||||||
std::vector<double> flattenBackground;
|
std::vector<double> flattenBackground;
|
||||||
bool unflatten;
|
bool unflatten;
|
||||||
@@ -92,6 +91,7 @@ struct PipelineBaton {
|
|||||||
bool thresholdGrayscale;
|
bool thresholdGrayscale;
|
||||||
std::vector<double> trimBackground;
|
std::vector<double> trimBackground;
|
||||||
double trimThreshold;
|
double trimThreshold;
|
||||||
|
bool trimLineArt;
|
||||||
int trimOffsetLeft;
|
int trimOffsetLeft;
|
||||||
int trimOffsetTop;
|
int trimOffsetTop;
|
||||||
std::vector<double> linearA;
|
std::vector<double> linearA;
|
||||||
@@ -169,6 +169,7 @@ struct PipelineBaton {
|
|||||||
VipsForeignTiffPredictor tiffPredictor;
|
VipsForeignTiffPredictor tiffPredictor;
|
||||||
bool tiffPyramid;
|
bool tiffPyramid;
|
||||||
int tiffBitdepth;
|
int tiffBitdepth;
|
||||||
|
bool tiffMiniswhite;
|
||||||
bool tiffTile;
|
bool tiffTile;
|
||||||
int tiffTileHeight;
|
int tiffTileHeight;
|
||||||
int tiffTileWidth;
|
int tiffTileWidth;
|
||||||
@@ -180,17 +181,19 @@ struct PipelineBaton {
|
|||||||
int heifEffort;
|
int heifEffort;
|
||||||
std::string heifChromaSubsampling;
|
std::string heifChromaSubsampling;
|
||||||
bool heifLossless;
|
bool heifLossless;
|
||||||
|
int heifBitdepth;
|
||||||
double jxlDistance;
|
double jxlDistance;
|
||||||
int jxlDecodingTier;
|
int jxlDecodingTier;
|
||||||
int jxlEffort;
|
int jxlEffort;
|
||||||
bool jxlLossless;
|
bool jxlLossless;
|
||||||
VipsBandFormat rawDepth;
|
VipsBandFormat rawDepth;
|
||||||
std::string err;
|
std::string err;
|
||||||
bool withMetadata;
|
int keepMetadata;
|
||||||
int withMetadataOrientation;
|
int withMetadataOrientation;
|
||||||
double withMetadataDensity;
|
double withMetadataDensity;
|
||||||
std::string withMetadataIcc;
|
std::string withIccProfile;
|
||||||
std::unordered_map<std::string, std::string> withMetadataStrs;
|
std::unordered_map<std::string, std::string> withExif;
|
||||||
|
bool withExifMerge;
|
||||||
int timeoutSeconds;
|
int timeoutSeconds;
|
||||||
std::unique_ptr<double[]> convKernel;
|
std::unique_ptr<double[]> convKernel;
|
||||||
int convKernelWidth;
|
int convKernelWidth;
|
||||||
@@ -203,7 +206,7 @@ struct PipelineBaton {
|
|||||||
int extractChannel;
|
int extractChannel;
|
||||||
bool removeAlpha;
|
bool removeAlpha;
|
||||||
double ensureAlpha;
|
double ensureAlpha;
|
||||||
VipsInterpretation colourspaceInput;
|
VipsInterpretation colourspacePipeline;
|
||||||
VipsInterpretation colourspace;
|
VipsInterpretation colourspace;
|
||||||
std::vector<int> delay;
|
std::vector<int> delay;
|
||||||
int loop;
|
int loop;
|
||||||
@@ -237,8 +240,7 @@ struct PipelineBaton {
|
|||||||
attentionX(0),
|
attentionX(0),
|
||||||
attentionY(0),
|
attentionY(0),
|
||||||
premultiplied(false),
|
premultiplied(false),
|
||||||
tintA(128.0),
|
tint{ -1.0, 0.0, 0.0, 0.0 },
|
||||||
tintB(128.0),
|
|
||||||
flatten(false),
|
flatten(false),
|
||||||
flattenBackground{ 0.0, 0.0, 0.0 },
|
flattenBackground{ 0.0, 0.0, 0.0 },
|
||||||
unflatten(false),
|
unflatten(false),
|
||||||
@@ -259,7 +261,8 @@ struct PipelineBaton {
|
|||||||
threshold(0),
|
threshold(0),
|
||||||
thresholdGrayscale(true),
|
thresholdGrayscale(true),
|
||||||
trimBackground{},
|
trimBackground{},
|
||||||
trimThreshold(0.0),
|
trimThreshold(-1.0),
|
||||||
|
trimLineArt(false),
|
||||||
trimOffsetLeft(0),
|
trimOffsetLeft(0),
|
||||||
trimOffsetTop(0),
|
trimOffsetTop(0),
|
||||||
linearA{},
|
linearA{},
|
||||||
@@ -335,6 +338,7 @@ struct PipelineBaton {
|
|||||||
tiffPredictor(VIPS_FOREIGN_TIFF_PREDICTOR_HORIZONTAL),
|
tiffPredictor(VIPS_FOREIGN_TIFF_PREDICTOR_HORIZONTAL),
|
||||||
tiffPyramid(false),
|
tiffPyramid(false),
|
||||||
tiffBitdepth(8),
|
tiffBitdepth(8),
|
||||||
|
tiffMiniswhite(false),
|
||||||
tiffTile(false),
|
tiffTile(false),
|
||||||
tiffTileHeight(256),
|
tiffTileHeight(256),
|
||||||
tiffTileWidth(256),
|
tiffTileWidth(256),
|
||||||
@@ -346,14 +350,16 @@ struct PipelineBaton {
|
|||||||
heifEffort(4),
|
heifEffort(4),
|
||||||
heifChromaSubsampling("4:4:4"),
|
heifChromaSubsampling("4:4:4"),
|
||||||
heifLossless(false),
|
heifLossless(false),
|
||||||
|
heifBitdepth(8),
|
||||||
jxlDistance(1.0),
|
jxlDistance(1.0),
|
||||||
jxlDecodingTier(0),
|
jxlDecodingTier(0),
|
||||||
jxlEffort(7),
|
jxlEffort(7),
|
||||||
jxlLossless(false),
|
jxlLossless(false),
|
||||||
rawDepth(VIPS_FORMAT_UCHAR),
|
rawDepth(VIPS_FORMAT_UCHAR),
|
||||||
withMetadata(false),
|
keepMetadata(0),
|
||||||
withMetadataOrientation(-1),
|
withMetadataOrientation(-1),
|
||||||
withMetadataDensity(0.0),
|
withMetadataDensity(0.0),
|
||||||
|
withExifMerge(true),
|
||||||
timeoutSeconds(0),
|
timeoutSeconds(0),
|
||||||
convKernelWidth(0),
|
convKernelWidth(0),
|
||||||
convKernelHeight(0),
|
convKernelHeight(0),
|
||||||
@@ -365,7 +371,7 @@ struct PipelineBaton {
|
|||||||
extractChannel(-1),
|
extractChannel(-1),
|
||||||
removeAlpha(false),
|
removeAlpha(false),
|
||||||
ensureAlpha(-1.0),
|
ensureAlpha(-1.0),
|
||||||
colourspaceInput(VIPS_INTERPRETATION_LAST),
|
colourspacePipeline(VIPS_INTERPRETATION_LAST),
|
||||||
colourspace(VIPS_INTERPRETATION_LAST),
|
colourspace(VIPS_INTERPRETATION_LAST),
|
||||||
loop(-1),
|
loop(-1),
|
||||||
tileSize(256),
|
tileSize(256),
|
||||||
|
|||||||
@@ -106,7 +106,7 @@ class StatsWorker : public Napi::AsyncWorker {
|
|||||||
// Handle warnings
|
// Handle warnings
|
||||||
std::string warning = sharp::VipsWarningPop();
|
std::string warning = sharp::VipsWarningPop();
|
||||||
while (!warning.empty()) {
|
while (!warning.empty()) {
|
||||||
debuglog.MakeCallback(Receiver().Value(), { Napi::String::New(env, warning) });
|
debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) });
|
||||||
warning = sharp::VipsWarningPop();
|
warning = sharp::VipsWarningPop();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,9 +141,9 @@ class StatsWorker : public Napi::AsyncWorker {
|
|||||||
dominant.Set("g", baton->dominantGreen);
|
dominant.Set("g", baton->dominantGreen);
|
||||||
dominant.Set("b", baton->dominantBlue);
|
dominant.Set("b", baton->dominantBlue);
|
||||||
info.Set("dominant", dominant);
|
info.Set("dominant", dominant);
|
||||||
Callback().MakeCallback(Receiver().Value(), { env.Null(), info });
|
Callback().Call(Receiver().Value(), { env.Null(), info });
|
||||||
} else {
|
} else {
|
||||||
Callback().MakeCallback(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() });
|
Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() });
|
||||||
}
|
}
|
||||||
|
|
||||||
delete baton->input;
|
delete baton->input;
|
||||||
|
|||||||
@@ -102,6 +102,11 @@ Napi::Value libvipsVersion(const Napi::CallbackInfo& info) {
|
|||||||
version.Set("isGlobal", Napi::Boolean::New(env, true));
|
version.Set("isGlobal", Napi::Boolean::New(env, true));
|
||||||
#else
|
#else
|
||||||
version.Set("isGlobal", Napi::Boolean::New(env, false));
|
version.Set("isGlobal", Napi::Boolean::New(env, false));
|
||||||
|
#endif
|
||||||
|
#ifdef __EMSCRIPTEN__
|
||||||
|
version.Set("isWasm", Napi::Boolean::New(env, true));
|
||||||
|
#else
|
||||||
|
version.Set("isWasm", Napi::Boolean::New(env, false));
|
||||||
#endif
|
#endif
|
||||||
return version;
|
return version;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
FROM ubuntu:22.04
|
FROM ubuntu:23.10
|
||||||
ARG BRANCH=main
|
ARG BRANCH=main
|
||||||
|
|
||||||
# Install basic dependencies
|
# Install basic dependencies
|
||||||
RUN apt-get -y update && apt-get install -y build-essential curl git
|
RUN apt-get -y update && apt-get install -y build-essential curl git ca-certificates gnupg
|
||||||
|
|
||||||
# Install latest Node.js LTS
|
# Install latest Node.js LTS
|
||||||
RUN curl -fsSL https://deb.nodesource.com/setup_18.x | bash -
|
RUN mkdir -p /etc/apt/keyrings
|
||||||
RUN apt-get install -y nodejs
|
RUN curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
|
||||||
|
RUN echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_20.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list
|
||||||
|
RUN apt-get -y update && apt-get install -y nodejs
|
||||||
|
|
||||||
# Install benchmark dependencies
|
# Install benchmark dependencies
|
||||||
RUN apt-get install -y imagemagick libmagick++-dev graphicsmagick
|
RUN apt-get install -y imagemagick libmagick++-dev graphicsmagick
|
||||||
|
|||||||
@@ -10,14 +10,14 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@squoosh/cli": "0.7.3",
|
"@squoosh/cli": "0.7.3",
|
||||||
"@squoosh/lib": "0.5.3",
|
"@squoosh/lib": "0.5.3",
|
||||||
"async": "3.2.4",
|
"async": "3.2.5",
|
||||||
"benchmark": "2.1.4",
|
"benchmark": "2.1.4",
|
||||||
"gm": "1.25.0",
|
"gm": "1.25.0",
|
||||||
"imagemagick": "0.1.3",
|
"imagemagick": "0.1.3",
|
||||||
"jimp": "0.22.10"
|
"jimp": "0.22.10"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@tensorflow/tfjs-node": "4.11.0",
|
"@tensorflow/tfjs-node": "4.13.0",
|
||||||
"mapnik": "4.5.9"
|
"mapnik": "4.5.9"
|
||||||
},
|
},
|
||||||
"license": "Apache-2.0"
|
"license": "Apache-2.0"
|
||||||
|
|||||||
BIN
test/fixtures/XCMYK 2017.icc
vendored
Normal file
BIN
test/fixtures/expected/colourspace.cmyk-to-cmyk-negated.tif
vendored
Normal file
BIN
test/fixtures/expected/negate-trans.png
vendored
|
Before Width: | Height: | Size: 8.0 KiB After Width: | Height: | Size: 5.3 KiB |
BIN
test/fixtures/expected/tint-alpha.png
vendored
|
Before Width: | Height: | Size: 142 KiB After Width: | Height: | Size: 135 KiB |
BIN
test/fixtures/expected/tint-blue.jpg
vendored
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
BIN
test/fixtures/expected/tint-cmyk.jpg
vendored
|
Before Width: | Height: | Size: 26 KiB After Width: | Height: | Size: 30 KiB |
BIN
test/fixtures/expected/tint-green.jpg
vendored
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 14 KiB |
BIN
test/fixtures/expected/tint-red.jpg
vendored
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 15 KiB |
BIN
test/fixtures/expected/tint-sepia.jpg
vendored
|
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 15 KiB |
BIN
test/fixtures/fogra-0-100-100-0.tif
vendored
Normal file
1
test/fixtures/index.js
vendored
@@ -114,6 +114,7 @@ module.exports = {
|
|||||||
inputTiffUncompressed: getPath('uncompressed_tiff.tiff'), // https://code.google.com/archive/p/imagetestsuite/wikis/TIFFTestSuite.wiki file: 0c84d07e1b22b76f24cccc70d8788e4a.tif
|
inputTiffUncompressed: getPath('uncompressed_tiff.tiff'), // https://code.google.com/archive/p/imagetestsuite/wikis/TIFFTestSuite.wiki file: 0c84d07e1b22b76f24cccc70d8788e4a.tif
|
||||||
inputTiff8BitDepth: getPath('8bit_depth.tiff'),
|
inputTiff8BitDepth: getPath('8bit_depth.tiff'),
|
||||||
inputTifftagPhotoshop: getPath('tifftag-photoshop.tiff'), // https://github.com/lovell/sharp/issues/1600
|
inputTifftagPhotoshop: getPath('tifftag-photoshop.tiff'), // https://github.com/lovell/sharp/issues/1600
|
||||||
|
inputTiffFogra: getPath('fogra-0-100-100-0.tif'), // https://github.com/lovell/sharp/issues/4045
|
||||||
|
|
||||||
inputJp2: getPath('relax.jp2'), // https://www.fnordware.com/j2k/relax.jp2
|
inputJp2: getPath('relax.jp2'), // https://www.fnordware.com/j2k/relax.jp2
|
||||||
inputGif: getPath('Crash_test.gif'), // http://upload.wikimedia.org/wikipedia/commons/e/e3/Crash_test.gif
|
inputGif: getPath('Crash_test.gif'), // http://upload.wikimedia.org/wikipedia/commons/e/e3/Crash_test.gif
|
||||||
|
|||||||
BIN
test/fixtures/invalid-illuminant.icc
vendored
Normal file
@@ -1,4 +1,5 @@
|
|||||||
#!/bin/sh
|
#!/usr/bin/env bash
|
||||||
|
set -e
|
||||||
|
|
||||||
if ! type valgrind >/dev/null; then
|
if ! type valgrind >/dev/null; then
|
||||||
echo "Please install valgrind before running memory leak tests"
|
echo "Please install valgrind before running memory leak tests"
|
||||||
@@ -7,14 +8,15 @@ fi
|
|||||||
|
|
||||||
curl -s -o ./test/leak/libvips.supp https://raw.githubusercontent.com/libvips/libvips/master/suppressions/valgrind.supp
|
curl -s -o ./test/leak/libvips.supp https://raw.githubusercontent.com/libvips/libvips/master/suppressions/valgrind.supp
|
||||||
|
|
||||||
for test in ./test/unit/*.js; do
|
TESTS=$(ls test/unit --ignore=svg.js --ignore=text.js)
|
||||||
|
for test in $TESTS; do
|
||||||
G_SLICE=always-malloc G_DEBUG=gc-friendly VIPS_LEAK=1 VIPS_NOVECTOR=1 valgrind \
|
G_SLICE=always-malloc G_DEBUG=gc-friendly VIPS_LEAK=1 VIPS_NOVECTOR=1 valgrind \
|
||||||
--suppressions=test/leak/libvips.supp \
|
--suppressions=test/leak/libvips.supp \
|
||||||
--suppressions=test/leak/sharp.supp \
|
--suppressions=test/leak/sharp.supp \
|
||||||
--gen-suppressions=yes \
|
--gen-suppressions=yes \
|
||||||
--leak-check=full \
|
--leak-check=full \
|
||||||
--show-leak-kinds=definite,indirect,possible \
|
--show-leak-kinds=definite,indirect \
|
||||||
--num-callers=20 \
|
--num-callers=20 \
|
||||||
--trace-children=yes \
|
--trace-children=yes \
|
||||||
node --expose-gc node_modules/.bin/mocha --no-config --slow=60000 --timeout=120000 --require test/beforeEach.js "$test";
|
node --expose-gc --zero-fill-buffers node_modules/.bin/mocha --no-config --slow=60000 --timeout=120000 --require test/beforeEach.js "test/unit/$test";
|
||||||
done
|
done
|
||||||
|
|||||||
@@ -173,41 +173,6 @@
|
|||||||
fun:TIFFWriteEncodedTile
|
fun:TIFFWriteEncodedTile
|
||||||
}
|
}
|
||||||
|
|
||||||
# gsf
|
|
||||||
{
|
|
||||||
param_gsf_output_write
|
|
||||||
Memcheck:Param
|
|
||||||
write(buf)
|
|
||||||
fun:write
|
|
||||||
...
|
|
||||||
fun:gsf_output_write
|
|
||||||
}
|
|
||||||
{
|
|
||||||
value_gsf_output_write_crc32_little
|
|
||||||
Memcheck:Value8
|
|
||||||
fun:crc32_little
|
|
||||||
...
|
|
||||||
fun:gsf_output_write
|
|
||||||
}
|
|
||||||
{
|
|
||||||
param_gsf_new_do_write
|
|
||||||
Memcheck:Param
|
|
||||||
write(buf)
|
|
||||||
...
|
|
||||||
fun:new_do_write
|
|
||||||
...
|
|
||||||
fun:gsf_output_close
|
|
||||||
}
|
|
||||||
{
|
|
||||||
param_gsf_output_write
|
|
||||||
Memcheck:Param
|
|
||||||
write(buf)
|
|
||||||
...
|
|
||||||
fun:new_do_write
|
|
||||||
...
|
|
||||||
fun:gsf_output_write
|
|
||||||
}
|
|
||||||
|
|
||||||
# fontconfig
|
# fontconfig
|
||||||
{
|
{
|
||||||
leak_fontconfig_FcConfigSubstituteWithPat
|
leak_fontconfig_FcConfigSubstituteWithPat
|
||||||
@@ -349,11 +314,39 @@
|
|||||||
fun:heif_context_read_from_reader
|
fun:heif_context_read_from_reader
|
||||||
}
|
}
|
||||||
|
|
||||||
# orc
|
# glib
|
||||||
{
|
{
|
||||||
addr_orcexec
|
leak_glib__tls_get_addr
|
||||||
Memcheck:Addr1
|
Memcheck:Leak
|
||||||
obj:*/orcexec.*
|
match-leak-kinds: possible
|
||||||
|
...
|
||||||
|
fun:malloc
|
||||||
|
fun:allocate_dtv_entry
|
||||||
|
fun:allocate_and_init
|
||||||
|
fun:tls_get_addr_tail
|
||||||
|
fun:__tls_get_addr
|
||||||
|
}
|
||||||
|
{
|
||||||
|
value_g_utf8_make_valid_strlen
|
||||||
|
Memcheck:Value8
|
||||||
|
fun:strlen
|
||||||
|
fun:g_utf8_make_valid
|
||||||
|
}
|
||||||
|
{
|
||||||
|
value_g_utf8_make_valid_strncpy
|
||||||
|
Memcheck:Value8
|
||||||
|
fun:strncpy
|
||||||
|
fun:g_strndup
|
||||||
|
...
|
||||||
|
fun:g_utf8_make_valid
|
||||||
|
}
|
||||||
|
{
|
||||||
|
cond_g_utf8_make_valid_strncpy
|
||||||
|
Memcheck:Cond
|
||||||
|
fun:strncpy
|
||||||
|
fun:g_strndup
|
||||||
|
...
|
||||||
|
fun:g_utf8_make_valid
|
||||||
}
|
}
|
||||||
|
|
||||||
# libvips
|
# libvips
|
||||||
@@ -943,6 +936,79 @@
|
|||||||
...
|
...
|
||||||
fun:_ZN2v88internal18ArrayBufferSweeper10ReleaseAllEv
|
fun:_ZN2v88internal18ArrayBufferSweeper10ReleaseAllEv
|
||||||
}
|
}
|
||||||
|
{
|
||||||
|
cond_node_Builtins_JSEntry
|
||||||
|
Memcheck:Cond
|
||||||
|
...
|
||||||
|
fun:Builtins_JSEntry
|
||||||
|
...
|
||||||
|
fun:uv__poll_io_uring
|
||||||
|
}
|
||||||
|
{
|
||||||
|
cond_node_Builtins_TestEqualStrictHandler
|
||||||
|
Memcheck:Cond
|
||||||
|
fun:Builtins_TestEqualStrictHandler
|
||||||
|
...
|
||||||
|
fun:uv__poll_io_uring
|
||||||
|
}
|
||||||
|
{
|
||||||
|
cond_node_Builtins_TestGreaterThanHandler
|
||||||
|
Memcheck:Cond
|
||||||
|
fun:Builtins_TestGreaterThanHandler
|
||||||
|
...
|
||||||
|
fun:uv__poll_io_uring
|
||||||
|
}
|
||||||
|
{
|
||||||
|
cond_node_AfterStat
|
||||||
|
Memcheck:Cond
|
||||||
|
...
|
||||||
|
fun:_ZN4node2fs9AfterStatEP7uv_fs_s
|
||||||
|
...
|
||||||
|
fun:uv__poll_io_uring
|
||||||
|
}
|
||||||
|
{
|
||||||
|
cond_node_AfterMkdirp
|
||||||
|
Memcheck:Cond
|
||||||
|
fun:_ZN4node2fs11AfterMkdirpEP7uv_fs_s
|
||||||
|
fun:_ZN4node24MakeLibuvRequestCallbackI7uv_fs_sPFvPS1_EE7WrapperES2_
|
||||||
|
fun:_ZZZN4node2fs11MKDirpAsyncEP9uv_loop_sP7uv_fs_sPKciPFvS4_EENKUlS4_E_clES4_ENUlS4_E_4_FUNES4_
|
||||||
|
fun:uv__poll_io_uring
|
||||||
|
}
|
||||||
|
{
|
||||||
|
cond_v8_ArrayBufferSweeper_Finalize
|
||||||
|
Memcheck:Cond
|
||||||
|
fun:_ZN2v88internal18ArrayBufferSweeper8FinalizeEv
|
||||||
|
}
|
||||||
|
{
|
||||||
|
cond_v8_AdjustAmountOfExternalAllocatedMemory
|
||||||
|
Memcheck:Cond
|
||||||
|
fun:_ZN2v87Isolate37AdjustAmountOfExternalAllocatedMemoryEl
|
||||||
|
}
|
||||||
|
{
|
||||||
|
cond_v8_IncrementalMarkingLimitReached
|
||||||
|
Memcheck:Cond
|
||||||
|
fun:_ZN2v88internal4Heap30IncrementalMarkingLimitReachedEv
|
||||||
|
}
|
||||||
|
{
|
||||||
|
cond_v8_ShouldExpandOldGenerationOnSlowAllocation
|
||||||
|
Memcheck:Cond
|
||||||
|
fun:_ZN2v88internal4Heap41ShouldExpandOldGenerationOnSlowAllocationEPNS0_9LocalHeapENS0_16AllocationOriginE
|
||||||
|
}
|
||||||
|
{
|
||||||
|
cond_v8_ArrayBufferSweeper_SweepingJob_SweepListFull
|
||||||
|
Memcheck:Cond
|
||||||
|
fun:_ZN2v88internal18ArrayBufferSweeper11SweepingJob13SweepListFullEPNS0_15ArrayBufferListE
|
||||||
|
}
|
||||||
|
{
|
||||||
|
cond_v8_ArrayBufferSweeper_SweepingJob_SweepYoung
|
||||||
|
Memcheck:Cond
|
||||||
|
fun:_ZN2v88internal18ArrayBufferSweeper11SweepingJob10SweepYoungEv
|
||||||
|
}
|
||||||
|
{
|
||||||
|
cond_v8_StartIncrementalMarkingIfAllocationLimitIsReachedBackground
|
||||||
|
Memcheck:Cond
|
||||||
|
fun:_ZN2v88internal4Heap59StartIncrementalMarkingIfAllocationLimitIsReachedBackgroundEv
|
||||||
|
}
|
||||||
{
|
{
|
||||||
addr_v8_ZN2v88internal12_GLOBAL__N_119HandleApiCallHelperILb0EEENS0
|
addr_v8_ZN2v88internal12_GLOBAL__N_119HandleApiCallHelperILb0EEENS0
|
||||||
Memcheck:Addr8
|
Memcheck:Addr8
|
||||||
|
|||||||
@@ -44,6 +44,12 @@ sharp('input.png')
|
|||||||
// sharpened, with metadata, 90% quality WebP image data. Phew!
|
// sharpened, with metadata, 90% quality WebP image data. Phew!
|
||||||
});
|
});
|
||||||
|
|
||||||
|
sharp('input.png')
|
||||||
|
.keepMetadata()
|
||||||
|
.toFile('output.png', (err, info) => {
|
||||||
|
// output.png is an image containing input.png along with all metadata(EXIF, ICC, XMP, IPTC) from input.png
|
||||||
|
})
|
||||||
|
|
||||||
sharp('input.jpg')
|
sharp('input.jpg')
|
||||||
.resize(300, 200)
|
.resize(300, 200)
|
||||||
.toFile('output.jpg', (err: Error) => {
|
.toFile('output.jpg', (err: Error) => {
|
||||||
@@ -404,7 +410,7 @@ sharp({
|
|||||||
|
|
||||||
// Taken from API documentation at
|
// Taken from API documentation at
|
||||||
// https://sharp.pixelplumbing.com/api-operation#clahe
|
// https://sharp.pixelplumbing.com/api-operation#clahe
|
||||||
// introducted
|
// introduced
|
||||||
sharp('input.jpg').clahe({ width: 10, height: 10 }).toFile('output.jpg');
|
sharp('input.jpg').clahe({ width: 10, height: 10 }).toFile('output.jpg');
|
||||||
|
|
||||||
sharp('input.jpg').clahe({ width: 10, height: 10, maxSlope: 5 }).toFile('outfile.jpg');
|
sharp('input.jpg').clahe({ width: 10, height: 10, maxSlope: 5 }).toFile('outfile.jpg');
|
||||||
@@ -572,8 +578,8 @@ const nohalo: string = sharp.interpolators.nohalo;
|
|||||||
const vertexSplitQuadraticBasisSpline: string = sharp.interpolators.vertexSplitQuadraticBasisSpline;
|
const vertexSplitQuadraticBasisSpline: string = sharp.interpolators.vertexSplitQuadraticBasisSpline;
|
||||||
|
|
||||||
// Triming
|
// Triming
|
||||||
sharp(input).trim('#000').toBuffer();
|
sharp(input).trim({ background: '#000' }).toBuffer();
|
||||||
sharp(input).trim(10).toBuffer();
|
sharp(input).trim({ threshold: 10, lineArt: true }).toBuffer();
|
||||||
sharp(input).trim({ background: '#bf1942', threshold: 30 }).toBuffer();
|
sharp(input).trim({ background: '#bf1942', threshold: 30 }).toBuffer();
|
||||||
|
|
||||||
// Text input
|
// Text input
|
||||||
@@ -589,7 +595,7 @@ sharp({
|
|||||||
rgba: true,
|
rgba: true,
|
||||||
justify: true,
|
justify: true,
|
||||||
spacing: 10,
|
spacing: 10,
|
||||||
wrap: 'charWord',
|
wrap: 'word-char',
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
.png()
|
.png()
|
||||||
@@ -659,3 +665,39 @@ sharp('input.tiff').webp({ preset: 'drawing' }).toFile('out.webp');
|
|||||||
sharp('input.tiff').webp({ preset: 'text' }).toFile('out.webp');
|
sharp('input.tiff').webp({ preset: 'text' }).toFile('out.webp');
|
||||||
sharp('input.tiff').webp({ preset: 'default' }).toFile('out.webp');
|
sharp('input.tiff').webp({ preset: 'default' }).toFile('out.webp');
|
||||||
|
|
||||||
|
sharp(input)
|
||||||
|
.keepExif()
|
||||||
|
.withExif({
|
||||||
|
IFD0: {
|
||||||
|
k1: 'v1'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.withExifMerge({
|
||||||
|
IFD1: {
|
||||||
|
k2: 'v2'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.keepIccProfile()
|
||||||
|
.withIccProfile('filename')
|
||||||
|
.withIccProfile('filename', { attach: false });
|
||||||
|
|
||||||
|
// Added missing types for OverlayOptions
|
||||||
|
// https://github.com/lovell/sharp/pull/4048
|
||||||
|
sharp(input).composite([
|
||||||
|
{
|
||||||
|
input: 'image.gif',
|
||||||
|
animated: true,
|
||||||
|
limitInputPixels: 536805378,
|
||||||
|
density: 144,
|
||||||
|
failOn: "warning"
|
||||||
|
}
|
||||||
|
])
|
||||||
|
sharp(input).composite([
|
||||||
|
{
|
||||||
|
input: 'image.png',
|
||||||
|
animated: false,
|
||||||
|
limitInputPixels: 178935126,
|
||||||
|
density: 72,
|
||||||
|
failOn: "truncated"
|
||||||
|
}
|
||||||
|
])
|
||||||
@@ -144,4 +144,10 @@ describe('AVIF', () => {
|
|||||||
/Processed image is too large for the HEIF format/
|
/Processed image is too large for the HEIF format/
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
it('Invalid bitdepth value throws error', async () => {
|
||||||
|
assert.rejects(
|
||||||
|
() => sharp().avif({ bitdepth: 11 }),
|
||||||
|
/Error: Expected 8, 10 or 12 for bitdepth but received 11 of type number/);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -77,4 +77,26 @@ describe('Clone', function () {
|
|||||||
assert.strictEqual(0, original.listenerCount('finish'));
|
assert.strictEqual(0, original.listenerCount('finish'));
|
||||||
assert.strictEqual(0, clone.listenerCount('finish'));
|
assert.strictEqual(0, clone.listenerCount('finish'));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('Ensure deep clone of properties, including arrays', async () => {
|
||||||
|
const alpha = await sharp({
|
||||||
|
create: { width: 320, height: 240, channels: 3, background: 'red' }
|
||||||
|
}).toColourspace('b-w').png().toBuffer();
|
||||||
|
|
||||||
|
const original = sharp();
|
||||||
|
const joiner = original.clone().joinChannel(alpha);
|
||||||
|
const negater = original.clone().negate();
|
||||||
|
|
||||||
|
fs.createReadStream(fixtures.inputJpg320x240).pipe(original);
|
||||||
|
const joined = await joiner.png({ effort: 1 }).toBuffer();
|
||||||
|
const negated = await negater.png({ effort: 1 }).toBuffer();
|
||||||
|
|
||||||
|
const joinedMetadata = await sharp(joined).metadata();
|
||||||
|
assert.strictEqual(joinedMetadata.channels, 4);
|
||||||
|
assert.strictEqual(joinedMetadata.hasAlpha, true);
|
||||||
|
|
||||||
|
const negatedMetadata = await sharp(negated).metadata();
|
||||||
|
assert.strictEqual(negatedMetadata.channels, 3);
|
||||||
|
assert.strictEqual(negatedMetadata.hasAlpha, false);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -106,6 +106,43 @@ describe('Colour space conversion', function () {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('CMYK profile to CMYK profile conversion using perceptual intent', async () => {
|
||||||
|
const data = await sharp(fixtures.inputTiffFogra)
|
||||||
|
.resize(320, 240)
|
||||||
|
.toColourspace('cmyk')
|
||||||
|
.pipelineColourspace('cmyk')
|
||||||
|
.withIccProfile(fixtures.path('XCMYK 2017.icc'))
|
||||||
|
.raw()
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const [c, m, y, k] = data;
|
||||||
|
assert.deepStrictEqual(
|
||||||
|
{ c, m, y, k },
|
||||||
|
{ c: 1, m: 239, y: 227, k: 5 }
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('CMYK profile to CMYK profile with negate', (done) => {
|
||||||
|
sharp(fixtures.inputTiffFogra)
|
||||||
|
.resize(320, 240)
|
||||||
|
.toColourspace('cmyk')
|
||||||
|
.pipelineColourspace('cmyk')
|
||||||
|
.withIccProfile(fixtures.path('XCMYK 2017.icc'))
|
||||||
|
.negate()
|
||||||
|
.toBuffer(function (err, data, info) {
|
||||||
|
if (err) throw err;
|
||||||
|
assert.strictEqual('tiff', info.format);
|
||||||
|
assert.strictEqual(320, info.width);
|
||||||
|
assert.strictEqual(240, info.height);
|
||||||
|
fixtures.assertSimilar(
|
||||||
|
fixtures.expected('colourspace.cmyk-to-cmyk-negated.tif'),
|
||||||
|
data,
|
||||||
|
{ threshold: 0 },
|
||||||
|
done
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it('From sRGB with RGB16 pipeline, resize with gamma, to sRGB', function (done) {
|
it('From sRGB with RGB16 pipeline, resize with gamma, to sRGB', function (done) {
|
||||||
sharp(fixtures.inputPngGradients)
|
sharp(fixtures.inputPngGradients)
|
||||||
.pipelineColourspace('rgb16')
|
.pipelineColourspace('rgb16')
|
||||||
|
|||||||
@@ -246,7 +246,7 @@ describe('composite', () => {
|
|||||||
sharp(fixtures.inputJpg)
|
sharp(fixtures.inputJpg)
|
||||||
.resize(300, 300)
|
.resize(300, 300)
|
||||||
.composite([{
|
.composite([{
|
||||||
input: Buffer.from('<svg width="200" height="200"><rect x="0" y="0" width="200" height="200" rx="50" ry="50"/></svg>'),
|
input: Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><rect x="0" y="0" width="200" height="200" rx="50" ry="50"/></svg>'),
|
||||||
density: 96,
|
density: 96,
|
||||||
blend: 'dest-in',
|
blend: 'dest-in',
|
||||||
cutout: true
|
cutout: true
|
||||||
@@ -451,7 +451,7 @@ describe('composite', () => {
|
|||||||
assert.strictEqual(info.height, 40);
|
assert.strictEqual(info.height, 40);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Ensure implict unpremultiply after resize but before composite', async () => {
|
it('Ensure implicit unpremultiply after resize but before composite', async () => {
|
||||||
const [r, g, b, a] = await sharp({
|
const [r, g, b, a] = await sharp({
|
||||||
create: {
|
create: {
|
||||||
width: 1, height: 1, channels: 4, background: 'saddlebrown'
|
width: 1, height: 1, channels: 4, background: 'saddlebrown'
|
||||||
|
|||||||
@@ -113,6 +113,39 @@ describe('Extend', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('extend top with mirroring uses ordered read', async () => {
|
||||||
|
const data = await sharp(fixtures.inputJpg)
|
||||||
|
.extend({
|
||||||
|
extendWith: 'mirror',
|
||||||
|
top: 1
|
||||||
|
})
|
||||||
|
.png({ compressionLevel: 0 })
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const { width, height } = await sharp(data).metadata();
|
||||||
|
assert.strictEqual(2725, width);
|
||||||
|
assert.strictEqual(2226, height);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('multi-page extend uses ordered read', async () => {
|
||||||
|
const multiPageTiff = await sharp(fixtures.inputGifAnimated, { animated: true })
|
||||||
|
.resize({ width: 8, height: 48 })
|
||||||
|
.tiff()
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const data = await sharp(multiPageTiff, { pages: -1 })
|
||||||
|
.extend({
|
||||||
|
background: 'red',
|
||||||
|
top: 1
|
||||||
|
})
|
||||||
|
.png({ compressionLevel: 0 })
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const { width, height } = await sharp(data).metadata();
|
||||||
|
assert.strictEqual(8, width);
|
||||||
|
assert.strictEqual(1470, height);
|
||||||
|
});
|
||||||
|
|
||||||
it('missing parameter fails', function () {
|
it('missing parameter fails', function () {
|
||||||
assert.throws(function () {
|
assert.throws(function () {
|
||||||
sharp().extend();
|
sharp().extend();
|
||||||
|
|||||||
@@ -78,4 +78,21 @@ describe('HEIF', () => {
|
|||||||
sharp().heif({ compression: 'av1', chromaSubsampling: '4:4:4' });
|
sharp().heif({ compression: 'av1', chromaSubsampling: '4:4:4' });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
it('valid bitdepth value does not throw an error', () => {
|
||||||
|
const { heif } = sharp.versions;
|
||||||
|
delete sharp.versions.heif;
|
||||||
|
assert.doesNotThrow(() => {
|
||||||
|
sharp().heif({ compression: 'av1', bitdepth: 12 });
|
||||||
|
});
|
||||||
|
sharp.versions.heif = '1.2.3';
|
||||||
|
assert.throws(() => {
|
||||||
|
sharp().heif({ compression: 'av1', bitdepth: 10 });
|
||||||
|
}, /Error: Expected 8 for bitdepth when using prebuilt binaries but received 10 of type number/);
|
||||||
|
sharp.versions.heif = heif;
|
||||||
|
});
|
||||||
|
it('invalid bitdepth value should throw an error', () => {
|
||||||
|
assert.throws(() => {
|
||||||
|
sharp().heif({ compression: 'av1', bitdepth: 11 });
|
||||||
|
}, /Error: Expected 8, 10 or 12 for bitdepth but received 11 of type number/);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -459,27 +459,29 @@ describe('Input/output', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Fail when input is invalid Buffer', function (done) {
|
it('Fail when input is invalid Buffer', async () =>
|
||||||
sharp(Buffer.from([0x1, 0x2, 0x3, 0x4])).toBuffer().then(function () {
|
assert.rejects(
|
||||||
assert(false);
|
() => sharp(Buffer.from([0x1, 0x2, 0x3, 0x4])).toBuffer(),
|
||||||
done();
|
(err) => {
|
||||||
}).catch(function (err) {
|
assert.strictEqual(err.message, 'Input buffer contains unsupported image format');
|
||||||
assert(err instanceof Error);
|
assert(err.stack.includes('at Sharp.toBuffer'));
|
||||||
assert.strictEqual('Input buffer contains unsupported image format', err.message);
|
assert(err.stack.includes(__filename));
|
||||||
done();
|
return true;
|
||||||
});
|
}
|
||||||
});
|
)
|
||||||
|
);
|
||||||
|
|
||||||
it('Fail when input file path is missing', function (done) {
|
it('Fail when input file path is missing', async () =>
|
||||||
sharp('does-not-exist').toBuffer().then(function () {
|
assert.rejects(
|
||||||
assert(false);
|
() => sharp('does-not-exist').toFile('fail'),
|
||||||
done();
|
(err) => {
|
||||||
}).catch(function (err) {
|
assert.strictEqual(err.message, 'Input file is missing: does-not-exist');
|
||||||
assert(err instanceof Error);
|
assert(err.stack.includes('at Sharp.toFile'));
|
||||||
assert.strictEqual('Input file is missing: does-not-exist', err.message);
|
assert(err.stack.includes(__filename));
|
||||||
done();
|
return true;
|
||||||
});
|
}
|
||||||
});
|
)
|
||||||
|
);
|
||||||
|
|
||||||
describe('Fail for unsupported input', function () {
|
describe('Fail for unsupported input', function () {
|
||||||
it('Undefined', function () {
|
it('Undefined', function () {
|
||||||
|
|||||||
@@ -66,20 +66,36 @@ describe('libvips binaries', function () {
|
|||||||
|
|
||||||
delete process.env.SHARP_IGNORE_GLOBAL_LIBVIPS;
|
delete process.env.SHARP_IGNORE_GLOBAL_LIBVIPS;
|
||||||
});
|
});
|
||||||
|
it('useGlobalLibvips can be forced via an env var', function () {
|
||||||
|
process.env.SHARP_FORCE_GLOBAL_LIBVIPS = 1;
|
||||||
|
|
||||||
|
const useGlobalLibvips = libvips.useGlobalLibvips();
|
||||||
|
assert.strictEqual(true, useGlobalLibvips);
|
||||||
|
|
||||||
|
delete process.env.SHARP_FORCE_GLOBAL_LIBVIPS;
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('Build time platform detection', () => {
|
describe('Build time platform detection', () => {
|
||||||
it('Can override platform with npm_config_platform and npm_config_libc', () => {
|
it('Can override platform with npm_config_platform and npm_config_libc', function () {
|
||||||
process.env.npm_config_platform = 'testplatform';
|
process.env.npm_config_platform = 'testplatform';
|
||||||
process.env.npm_config_libc = 'testlibc';
|
process.env.npm_config_libc = 'testlibc';
|
||||||
const [platform] = libvips.buildPlatformArch().split('-');
|
const platformArch = libvips.buildPlatformArch();
|
||||||
|
if (platformArch === 'wasm32') {
|
||||||
|
return this.skip();
|
||||||
|
}
|
||||||
|
const [platform] = platformArch.split('-');
|
||||||
assert.strictEqual(platform, 'testplatformtestlibc');
|
assert.strictEqual(platform, 'testplatformtestlibc');
|
||||||
delete process.env.npm_config_platform;
|
delete process.env.npm_config_platform;
|
||||||
delete process.env.npm_config_libc;
|
delete process.env.npm_config_libc;
|
||||||
});
|
});
|
||||||
it('Can override arch with npm_config_arch', () => {
|
it('Can override arch with npm_config_arch', function () {
|
||||||
process.env.npm_config_arch = 'test';
|
process.env.npm_config_arch = 'test';
|
||||||
const [, arch] = libvips.buildPlatformArch().split('-');
|
const platformArch = libvips.buildPlatformArch();
|
||||||
|
if (platformArch === 'wasm32') {
|
||||||
|
return this.skip();
|
||||||
|
}
|
||||||
|
const [, arch] = platformArch.split('-');
|
||||||
assert.strictEqual(arch, 'test');
|
assert.strictEqual(arch, 'test');
|
||||||
delete process.env.npm_config_arch;
|
delete process.env.npm_config_arch;
|
||||||
});
|
});
|
||||||
@@ -88,27 +104,36 @@ describe('libvips binaries', function () {
|
|||||||
describe('Build time directories', () => {
|
describe('Build time directories', () => {
|
||||||
it('sharp-libvips include', () => {
|
it('sharp-libvips include', () => {
|
||||||
const dir = libvips.buildSharpLibvipsIncludeDir();
|
const dir = libvips.buildSharpLibvipsIncludeDir();
|
||||||
assert.strictEqual(fs.statSync(dir).isDirectory(), true);
|
if (dir) {
|
||||||
|
assert.strictEqual(fs.statSync(dir).isDirectory(), true);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
it('sharp-libvips cplusplus', () => {
|
it('sharp-libvips cplusplus', () => {
|
||||||
const dir = libvips.buildSharpLibvipsCPlusPlusDir();
|
const dir = libvips.buildSharpLibvipsCPlusPlusDir();
|
||||||
assert.strictEqual(fs.statSync(dir).isDirectory(), true);
|
if (dir) {
|
||||||
|
assert.strictEqual(fs.statSync(dir).isDirectory(), true);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
it('sharp-libvips lib', () => {
|
it('sharp-libvips lib', () => {
|
||||||
const dir = libvips.buildSharpLibvipsLibDir();
|
const dir = libvips.buildSharpLibvipsLibDir();
|
||||||
assert.strictEqual(fs.statSync(dir).isDirectory(), true);
|
if (dir) {
|
||||||
|
assert.strictEqual(fs.statSync(dir).isDirectory(), true);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('Runtime detection', () => {
|
describe('Runtime detection', () => {
|
||||||
it('platform', () => {
|
it('platform', () => {
|
||||||
const [platform] = libvips.runtimePlatformArch().split('-');
|
const [platform] = libvips.runtimePlatformArch().split('-');
|
||||||
assert.strict(['darwin', 'linux', 'linuxmusl', 'win32'].includes(platform));
|
assert.strict(['darwin', 'freebsd', 'linux', 'linuxmusl', 'win32'].includes(platform));
|
||||||
});
|
});
|
||||||
it('arch', () => {
|
it('arch', () => {
|
||||||
const [, arch] = libvips.runtimePlatformArch().split('-');
|
const [, arch] = libvips.runtimePlatformArch().split('-');
|
||||||
assert.strict(['arm', 'arm64', 'ia32', 'x64'].includes(arch));
|
assert.strict(['arm', 'arm64', 'ia32', 'x64'].includes(arch));
|
||||||
});
|
});
|
||||||
|
it('isUnsupportedNodeRuntime', () => {
|
||||||
|
assert.strictEqual(libvips.isUnsupportedNodeRuntime(), undefined);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('logger', function () {
|
describe('logger', function () {
|
||||||
@@ -136,4 +161,26 @@ describe('libvips binaries', function () {
|
|||||||
libvips.log(new Error('problem'));
|
libvips.log(new Error('problem'));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('yarn locator hash', () => {
|
||||||
|
it('known platform', () => {
|
||||||
|
const cc = process.env.CC;
|
||||||
|
delete process.env.CC;
|
||||||
|
process.env.npm_config_platform = 'linux';
|
||||||
|
process.env.npm_config_arch = 's390x';
|
||||||
|
process.env.npm_config_libc = '';
|
||||||
|
const locatorHash = libvips.yarnLocator();
|
||||||
|
assert.strictEqual(locatorHash, '45978c229d');
|
||||||
|
delete process.env.npm_config_platform;
|
||||||
|
delete process.env.npm_config_arch;
|
||||||
|
delete process.env.npm_config_libc;
|
||||||
|
process.env.CC = cc;
|
||||||
|
});
|
||||||
|
it('unknown platform', () => {
|
||||||
|
process.env.npm_config_platform = 'unknown-platform';
|
||||||
|
const locatorHash = libvips.yarnLocator();
|
||||||
|
assert.strictEqual(locatorHash, '');
|
||||||
|
delete process.env.npm_config_platform;
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,43 +6,44 @@
|
|||||||
const assert = require('assert');
|
const assert = require('assert');
|
||||||
|
|
||||||
const sharp = require('../../');
|
const sharp = require('../../');
|
||||||
const fixtures = require('../fixtures');
|
|
||||||
|
|
||||||
describe('Median filter', () => {
|
const row = [0, 3, 15, 63, 127, 255];
|
||||||
it('1x1 window', async () => {
|
const input = Buffer.from(Array.from(row, () => row).flat());
|
||||||
const [r, g, b] = await sharp(fixtures.inputSvgSmallViewBox)
|
const raw = {
|
||||||
.median(1)
|
width: 6,
|
||||||
|
height: 6,
|
||||||
|
channels: 1
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('Median filter', function () {
|
||||||
|
it('default window (3x3)', async () => {
|
||||||
|
const data = await sharp(input, { raw })
|
||||||
|
.median()
|
||||||
|
.toColourspace('b-w')
|
||||||
.raw()
|
.raw()
|
||||||
.toBuffer();
|
.toBuffer();
|
||||||
|
|
||||||
assert.deepStrictEqual({ r: 0, g: 0, b: 0 }, { r, g, b });
|
assert.deepStrictEqual(data.subarray(0, 6), Buffer.from(row));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('3x3 window', async () => {
|
it('3x3 window', async () => {
|
||||||
const [r, g, b] = await sharp(fixtures.inputSvgSmallViewBox)
|
const data = await sharp(input, { raw })
|
||||||
.median(3)
|
.median(3)
|
||||||
|
.toColourspace('b-w')
|
||||||
.raw()
|
.raw()
|
||||||
.toBuffer();
|
.toBuffer();
|
||||||
|
|
||||||
assert.deepStrictEqual({ r: 255, g: 0, b: 127 }, { r, g, b });
|
assert.deepStrictEqual(data.subarray(0, 6), Buffer.from(row));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('7x7 window', async () => {
|
it('5x5 window', async () => {
|
||||||
const [r, g, b] = await sharp(fixtures.inputSvgSmallViewBox)
|
const data = await sharp(input, { raw })
|
||||||
.median(7)
|
.median(5)
|
||||||
|
.toColourspace('b-w')
|
||||||
.raw()
|
.raw()
|
||||||
.toBuffer();
|
.toBuffer();
|
||||||
|
|
||||||
assert.deepStrictEqual({ r: 255, g: 19, b: 146 }, { r, g, b });
|
assert.deepStrictEqual(data.subarray(0, 6), Buffer.from([0, 3, 15, 15, 63, 127]));
|
||||||
});
|
|
||||||
|
|
||||||
it('default window (3x3)', async () => {
|
|
||||||
const [r, g, b] = await sharp(fixtures.inputSvgSmallViewBox)
|
|
||||||
.median()
|
|
||||||
.raw()
|
|
||||||
.toBuffer();
|
|
||||||
|
|
||||||
assert.deepStrictEqual({ r: 255, g: 0, b: 127 }, { r, g, b });
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('invalid radius', () => {
|
it('invalid radius', () => {
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ const icc = require('icc');
|
|||||||
const sharp = require('../../');
|
const sharp = require('../../');
|
||||||
const fixtures = require('../fixtures');
|
const fixtures = require('../fixtures');
|
||||||
|
|
||||||
|
const create = { width: 1, height: 1, channels: 3, background: 'red' };
|
||||||
|
|
||||||
describe('Image metadata', function () {
|
describe('Image metadata', function () {
|
||||||
it('JPEG', function (done) {
|
it('JPEG', function (done) {
|
||||||
sharp(fixtures.inputJpg).metadata(function (err, metadata) {
|
sharp(fixtures.inputJpg).metadata(function (err, metadata) {
|
||||||
@@ -395,13 +397,27 @@ describe('Image metadata', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Non-existent file in, Promise out', function (done) {
|
it('Non-existent file in, Promise out', async () =>
|
||||||
sharp('fail').metadata().then(function (metadata) {
|
assert.rejects(
|
||||||
throw new Error('Non-existent file');
|
() => sharp('fail').metadata(),
|
||||||
}, function (err) {
|
(err) => {
|
||||||
assert.ok(!!err);
|
assert.strictEqual(err.message, 'Input file is missing: fail');
|
||||||
done();
|
assert(err.stack.includes('at Sharp.metadata'));
|
||||||
});
|
assert(err.stack.includes(__filename));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
it('Invalid stream in, callback out', (done) => {
|
||||||
|
fs.createReadStream(__filename).pipe(
|
||||||
|
sharp().metadata((err) => {
|
||||||
|
assert.strictEqual(err.message, 'Input buffer contains unsupported image format');
|
||||||
|
assert(err.stack.includes('at Sharp.metadata'));
|
||||||
|
assert(err.stack.includes(__filename));
|
||||||
|
done();
|
||||||
|
})
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Stream in, Promise out', function (done) {
|
it('Stream in, Promise out', function (done) {
|
||||||
@@ -538,11 +554,86 @@ describe('Image metadata', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('keep existing ICC profile', async () => {
|
||||||
|
const data = await sharp(fixtures.inputJpgWithExif)
|
||||||
|
.keepIccProfile()
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const metadata = await sharp(data).metadata();
|
||||||
|
const { description } = icc.parse(metadata.icc);
|
||||||
|
assert.strictEqual(description, 'Generic RGB Profile');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keep existing ICC profile, ignore colourspace conversion', async () => {
|
||||||
|
const data = await sharp(fixtures.inputJpgWithExif)
|
||||||
|
.keepIccProfile()
|
||||||
|
.toColourspace('cmyk')
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const metadata = await sharp(data).metadata();
|
||||||
|
assert.strictEqual(metadata.channels, 3);
|
||||||
|
const { description } = icc.parse(metadata.icc);
|
||||||
|
assert.strictEqual(description, 'Generic RGB Profile');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keep existing CMYK ICC profile', async () => {
|
||||||
|
const data = await sharp(fixtures.inputJpgWithCmykProfile)
|
||||||
|
.pipelineColourspace('cmyk')
|
||||||
|
.toColourspace('cmyk')
|
||||||
|
.keepIccProfile()
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const metadata = await sharp(data).metadata();
|
||||||
|
assert.strictEqual(metadata.channels, 4);
|
||||||
|
const { description } = icc.parse(metadata.icc);
|
||||||
|
assert.strictEqual(description, 'U.S. Web Coated (SWOP) v2');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('transform to ICC profile and attach', async () => {
|
||||||
|
const data = await sharp({ create })
|
||||||
|
.png()
|
||||||
|
.withIccProfile('p3', { attach: true })
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const metadata = await sharp(data).metadata();
|
||||||
|
const { description } = icc.parse(metadata.icc);
|
||||||
|
assert.strictEqual(description, 'sP3C');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('transform to ICC profile but do not attach', async () => {
|
||||||
|
const data = await sharp({ create })
|
||||||
|
.png()
|
||||||
|
.withIccProfile('p3', { attach: false })
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const metadata = await sharp(data).metadata();
|
||||||
|
assert.strictEqual(3, metadata.channels);
|
||||||
|
assert.strictEqual(undefined, metadata.icc);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('transform to invalid ICC profile emits warning', async () => {
|
||||||
|
const img = sharp({ create })
|
||||||
|
.png()
|
||||||
|
.withIccProfile(fixtures.path('invalid-illuminant.icc'));
|
||||||
|
|
||||||
|
let warningEmitted = '';
|
||||||
|
img.on('warning', (warning) => {
|
||||||
|
warningEmitted = warning;
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await img.toBuffer();
|
||||||
|
assert.strictEqual('Invalid profile', warningEmitted);
|
||||||
|
|
||||||
|
const metadata = await sharp(data).metadata();
|
||||||
|
assert.strictEqual(3, metadata.channels);
|
||||||
|
assert.strictEqual(undefined, metadata.icc);
|
||||||
|
});
|
||||||
|
|
||||||
it('Apply CMYK output ICC profile', function (done) {
|
it('Apply CMYK output ICC profile', function (done) {
|
||||||
const output = fixtures.path('output.icc-cmyk.jpg');
|
const output = fixtures.path('output.icc-cmyk.jpg');
|
||||||
sharp(fixtures.inputJpg)
|
sharp(fixtures.inputJpg)
|
||||||
.resize(64)
|
.resize(64)
|
||||||
.withMetadata({ icc: 'cmyk' })
|
.withIccProfile('cmyk')
|
||||||
.toFile(output, function (err) {
|
.toFile(output, function (err) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
sharp(output).metadata(function (err, metadata) {
|
sharp(output).metadata(function (err, metadata) {
|
||||||
@@ -567,7 +658,7 @@ describe('Image metadata', function () {
|
|||||||
const output = fixtures.path('output.hilutite.jpg');
|
const output = fixtures.path('output.hilutite.jpg');
|
||||||
sharp(fixtures.inputJpg)
|
sharp(fixtures.inputJpg)
|
||||||
.resize(64)
|
.resize(64)
|
||||||
.withMetadata({ icc: fixtures.path('hilutite.icm') })
|
.withIccProfile(fixtures.path('hilutite.icm'))
|
||||||
.toFile(output, function (err, info) {
|
.toFile(output, function (err, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
fixtures.assertMaxColourDistance(output, fixtures.expected('hilutite.jpg'), 9);
|
fixtures.assertMaxColourDistance(output, fixtures.expected('hilutite.jpg'), 9);
|
||||||
@@ -606,7 +697,6 @@ describe('Image metadata', function () {
|
|||||||
it('Remove EXIF metadata after a resize', function (done) {
|
it('Remove EXIF metadata after a resize', function (done) {
|
||||||
sharp(fixtures.inputJpgWithExif)
|
sharp(fixtures.inputJpgWithExif)
|
||||||
.resize(320, 240)
|
.resize(320, 240)
|
||||||
.withMetadata(false)
|
|
||||||
.toBuffer(function (err, buffer) {
|
.toBuffer(function (err, buffer) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
sharp(buffer).metadata(function (err, metadata) {
|
sharp(buffer).metadata(function (err, metadata) {
|
||||||
@@ -637,14 +727,7 @@ describe('Image metadata', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Add EXIF metadata to JPEG', async () => {
|
it('Add EXIF metadata to JPEG', async () => {
|
||||||
const data = await sharp({
|
const data = await sharp({ create })
|
||||||
create: {
|
|
||||||
width: 8,
|
|
||||||
height: 8,
|
|
||||||
channels: 3,
|
|
||||||
background: 'red'
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.jpeg()
|
.jpeg()
|
||||||
.withMetadata({
|
.withMetadata({
|
||||||
exif: {
|
exif: {
|
||||||
@@ -661,14 +744,7 @@ describe('Image metadata', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Set density of JPEG', async () => {
|
it('Set density of JPEG', async () => {
|
||||||
const data = await sharp({
|
const data = await sharp({ create })
|
||||||
create: {
|
|
||||||
width: 8,
|
|
||||||
height: 8,
|
|
||||||
channels: 3,
|
|
||||||
background: 'red'
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.withMetadata({
|
.withMetadata({
|
||||||
density: 300
|
density: 300
|
||||||
})
|
})
|
||||||
@@ -680,14 +756,7 @@ describe('Image metadata', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Set density of PNG', async () => {
|
it('Set density of PNG', async () => {
|
||||||
const data = await sharp({
|
const data = await sharp({ create })
|
||||||
create: {
|
|
||||||
width: 8,
|
|
||||||
height: 8,
|
|
||||||
channels: 3,
|
|
||||||
background: 'red'
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.withMetadata({
|
.withMetadata({
|
||||||
density: 96
|
density: 96
|
||||||
})
|
})
|
||||||
@@ -795,11 +864,7 @@ describe('Image metadata', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('withMetadata adds default sRGB profile to RGB16', async () => {
|
it('withMetadata adds default sRGB profile to RGB16', async () => {
|
||||||
const data = await sharp({
|
const data = await sharp({ create })
|
||||||
create: {
|
|
||||||
width: 8, height: 8, channels: 4, background: 'orange'
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.toColorspace('rgb16')
|
.toColorspace('rgb16')
|
||||||
.png()
|
.png()
|
||||||
.withMetadata()
|
.withMetadata()
|
||||||
@@ -813,11 +878,7 @@ describe('Image metadata', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('withMetadata adds P3 profile to 16-bit PNG', async () => {
|
it('withMetadata adds P3 profile to 16-bit PNG', async () => {
|
||||||
const data = await sharp({
|
const data = await sharp({ create })
|
||||||
create: {
|
|
||||||
width: 8, height: 8, channels: 4, background: 'orange'
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.toColorspace('rgb16')
|
.toColorspace('rgb16')
|
||||||
.png()
|
.png()
|
||||||
.withMetadata({ icc: 'p3' })
|
.withMetadata({ icc: 'p3' })
|
||||||
@@ -857,7 +918,89 @@ describe('Image metadata', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('Invalid withMetadata parameters', function () {
|
it('keepExif maintains all EXIF metadata', async () => {
|
||||||
|
const data1 = await sharp({ create })
|
||||||
|
.withExif({
|
||||||
|
IFD0: {
|
||||||
|
Copyright: 'Test 1',
|
||||||
|
Software: 'sharp'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.jpeg()
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const data2 = await sharp(data1)
|
||||||
|
.keepExif()
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const md2 = await sharp(data2).metadata();
|
||||||
|
const exif2 = exifReader(md2.exif);
|
||||||
|
assert.strictEqual(exif2.Image.Copyright, 'Test 1');
|
||||||
|
assert.strictEqual(exif2.Image.Software, 'sharp');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('withExif replaces all EXIF metadata', async () => {
|
||||||
|
const data1 = await sharp({ create })
|
||||||
|
.withExif({
|
||||||
|
IFD0: {
|
||||||
|
Copyright: 'Test 1',
|
||||||
|
Software: 'sharp'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.jpeg()
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const md1 = await sharp(data1).metadata();
|
||||||
|
const exif1 = exifReader(md1.exif);
|
||||||
|
assert.strictEqual(exif1.Image.Copyright, 'Test 1');
|
||||||
|
assert.strictEqual(exif1.Image.Software, 'sharp');
|
||||||
|
|
||||||
|
const data2 = await sharp(data1)
|
||||||
|
.withExif({
|
||||||
|
IFD0: {
|
||||||
|
Copyright: 'Test 2'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const md2 = await sharp(data2).metadata();
|
||||||
|
const exif2 = exifReader(md2.exif);
|
||||||
|
assert.strictEqual(exif2.Image.Copyright, 'Test 2');
|
||||||
|
assert.strictEqual(exif2.Image.Software, undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('withExifMerge merges all EXIF metadata', async () => {
|
||||||
|
const data1 = await sharp({ create })
|
||||||
|
.withExif({
|
||||||
|
IFD0: {
|
||||||
|
Copyright: 'Test 1'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.jpeg()
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const md1 = await sharp(data1).metadata();
|
||||||
|
const exif1 = exifReader(md1.exif);
|
||||||
|
assert.strictEqual(exif1.Image.Copyright, 'Test 1');
|
||||||
|
assert.strictEqual(exif1.Image.Software, undefined);
|
||||||
|
|
||||||
|
const data2 = await sharp(data1)
|
||||||
|
.withExifMerge({
|
||||||
|
IFD0: {
|
||||||
|
Copyright: 'Test 2',
|
||||||
|
Software: 'sharp'
|
||||||
|
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const md2 = await sharp(data2).metadata();
|
||||||
|
const exif2 = exifReader(md2.exif);
|
||||||
|
assert.strictEqual(exif2.Image.Copyright, 'Test 2');
|
||||||
|
assert.strictEqual(exif2.Image.Software, 'sharp');
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Invalid parameters', function () {
|
||||||
it('String orientation', function () {
|
it('String orientation', function () {
|
||||||
assert.throws(function () {
|
assert.throws(function () {
|
||||||
sharp().withMetadata({ orientation: 'zoinks' });
|
sharp().withMetadata({ orientation: 'zoinks' });
|
||||||
@@ -908,5 +1051,22 @@ describe('Image metadata', function () {
|
|||||||
sharp().withMetadata({ exif: { ifd0: { fail: false } } });
|
sharp().withMetadata({ exif: { ifd0: { fail: false } } });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
it('withIccProfile invalid profile', () => {
|
||||||
|
assert.throws(
|
||||||
|
() => sharp().withIccProfile(false),
|
||||||
|
/Expected string for icc but received false of type boolean/
|
||||||
|
);
|
||||||
|
});
|
||||||
|
it('withIccProfile missing attach', () => {
|
||||||
|
assert.doesNotThrow(
|
||||||
|
() => sharp().withIccProfile('test', {})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
it('withIccProfile invalid attach', () => {
|
||||||
|
assert.throws(
|
||||||
|
() => sharp().withIccProfile('test', { attach: 1 }),
|
||||||
|
/Expected boolean for attach but received 1 of type number/
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -353,6 +353,21 @@ describe('Rotation', function () {
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
it('Animated image rotate 180', () =>
|
||||||
|
assert.doesNotReject(() => sharp(fixtures.inputGifAnimated, { animated: true })
|
||||||
|
.rotate(180)
|
||||||
|
.toBuffer()
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
it('Animated image rotate non-180 rejects', () =>
|
||||||
|
assert.rejects(() => sharp(fixtures.inputGifAnimated, { animated: true })
|
||||||
|
.rotate(90)
|
||||||
|
.toBuffer(),
|
||||||
|
/Rotate is not supported for multi-page images/
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
it('Multiple rotate emits warning', () => {
|
it('Multiple rotate emits warning', () => {
|
||||||
let warningMessage = '';
|
let warningMessage = '';
|
||||||
const s = sharp();
|
const s = sharp();
|
||||||
|
|||||||
@@ -690,11 +690,25 @@ describe('Image Stats', function () {
|
|||||||
it('File input with corrupt header fails gracefully', function (done) {
|
it('File input with corrupt header fails gracefully', function (done) {
|
||||||
sharp(fixtures.inputJpgWithCorruptHeader)
|
sharp(fixtures.inputJpgWithCorruptHeader)
|
||||||
.stats(function (err) {
|
.stats(function (err) {
|
||||||
assert.strictEqual(true, !!err);
|
assert(err.message.includes('Input file has corrupt header'));
|
||||||
|
assert(err.stack.includes('at Sharp.stats'));
|
||||||
|
assert(err.stack.includes(__filename));
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('Stream input with corrupt header fails gracefully', function (done) {
|
||||||
|
fs.createReadStream(fixtures.inputJpgWithCorruptHeader).pipe(
|
||||||
|
sharp()
|
||||||
|
.stats(function (err) {
|
||||||
|
assert(err.message.includes('Input buffer has corrupt header'));
|
||||||
|
assert(err.stack.includes('at Sharp.stats'));
|
||||||
|
assert(err.stack.includes(__filename));
|
||||||
|
done();
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it('File input with corrupt header fails gracefully, Promise out', function () {
|
it('File input with corrupt header fails gracefully, Promise out', function () {
|
||||||
return sharp(fixtures.inputJpgWithCorruptHeader)
|
return sharp(fixtures.inputJpgWithCorruptHeader)
|
||||||
.stats().then(function (stats) {
|
.stats().then(function (stats) {
|
||||||
|
|||||||
@@ -141,21 +141,21 @@ describe('SVG input', function () {
|
|||||||
|
|
||||||
it('Fails to render SVG larger than 32767x32767', () =>
|
it('Fails to render SVG larger than 32767x32767', () =>
|
||||||
assert.rejects(
|
assert.rejects(
|
||||||
() => sharp(Buffer.from('<svg width="32768" height="1" />')).toBuffer(),
|
() => sharp(Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="32768" height="1" />')).toBuffer(),
|
||||||
/Input SVG image exceeds 32767x32767 pixel limit/
|
/Input SVG image exceeds 32767x32767 pixel limit/
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
it('Fails to render scaled SVG larger than 32767x32767', () =>
|
it('Fails to render scaled SVG larger than 32767x32767', () =>
|
||||||
assert.rejects(
|
assert.rejects(
|
||||||
() => sharp(Buffer.from('<svg width="32767" height="1" />')).resize(32768).toBuffer(),
|
() => sharp(Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="32767" height="1" />')).resize(32768).toBuffer(),
|
||||||
/Input SVG image will exceed 32767x32767 pixel limit when scaled/
|
/Input SVG image will exceed 32767x32767 pixel limit when scaled/
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
it('Detects SVG passed as a string', () =>
|
it('Detects SVG passed as a string', () =>
|
||||||
assert.rejects(
|
assert.rejects(
|
||||||
() => sharp('<svg></svg>').toBuffer(),
|
() => sharp('<svg xmlns="http://www.w3.org/2000/svg"></svg>').toBuffer(),
|
||||||
/Input file is missing, did you mean/
|
/Input file is missing, did you mean/
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -7,17 +7,21 @@ const assert = require('assert');
|
|||||||
|
|
||||||
const sharp = require('../../');
|
const sharp = require('../../');
|
||||||
const fixtures = require('../fixtures');
|
const fixtures = require('../fixtures');
|
||||||
|
const { inRange } = require('../../lib/is');
|
||||||
|
|
||||||
describe('Text to image', function () {
|
describe('Text to image', function () {
|
||||||
this.retries(3);
|
this.retries(3);
|
||||||
|
|
||||||
it('text with default values', async () => {
|
it('text with default values', async function () {
|
||||||
const output = fixtures.path('output.text-default.png');
|
const output = fixtures.path('output.text-default.png');
|
||||||
const text = sharp({
|
const text = sharp({
|
||||||
text: {
|
text: {
|
||||||
text: 'Hello, world !'
|
text: 'Hello, world !'
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
if (!sharp.versions.pango) {
|
||||||
|
return this.skip();
|
||||||
|
}
|
||||||
const info = await text.png().toFile(output);
|
const info = await text.png().toFile(output);
|
||||||
assert.strictEqual('png', info.format);
|
assert.strictEqual('png', info.format);
|
||||||
assert.strictEqual(3, info.channels);
|
assert.strictEqual(3, info.channels);
|
||||||
@@ -40,22 +44,23 @@ describe('Text to image', function () {
|
|||||||
|
|
||||||
it('text with width and height', function (done) {
|
it('text with width and height', function (done) {
|
||||||
const output = fixtures.path('output.text-width-height.png');
|
const output = fixtures.path('output.text-width-height.png');
|
||||||
const maxWidth = 500;
|
|
||||||
const maxHeight = 500;
|
|
||||||
const text = sharp({
|
const text = sharp({
|
||||||
text: {
|
text: {
|
||||||
text: 'Hello, world!',
|
text: 'Hello, world!',
|
||||||
width: maxWidth,
|
width: 500,
|
||||||
height: maxHeight
|
height: 400
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
if (!sharp.versions.pango) {
|
||||||
|
return this.skip();
|
||||||
|
}
|
||||||
text.toFile(output, function (err, info) {
|
text.toFile(output, function (err, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual('png', info.format);
|
assert.strictEqual('png', info.format);
|
||||||
assert.strictEqual(3, info.channels);
|
assert.strictEqual(3, info.channels);
|
||||||
assert.ok(info.width <= maxWidth);
|
assert.ok(inRange(info.width, 400, 600), `Actual width ${info.width}`);
|
||||||
assert.ok(info.height <= maxHeight);
|
assert.ok(inRange(info.height, 300, 500), `Actual height ${info.height}`);
|
||||||
assert.ok(info.textAutofitDpi > 0);
|
assert.ok(inRange(info.textAutofitDpi, 900, 1300), `Actual textAutofitDpi ${info.textAutofitDpi}`);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -69,6 +74,9 @@ describe('Text to image', function () {
|
|||||||
dpi
|
dpi
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
if (!sharp.versions.pango) {
|
||||||
|
return this.skip();
|
||||||
|
}
|
||||||
text.toFile(output, function (err, info) {
|
text.toFile(output, function (err, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual('png', info.format);
|
assert.strictEqual('png', info.format);
|
||||||
@@ -90,6 +98,9 @@ describe('Text to image', function () {
|
|||||||
dpi
|
dpi
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
if (!sharp.versions.pango) {
|
||||||
|
return this.skip();
|
||||||
|
}
|
||||||
text.toFile(output, function (err, info) {
|
text.toFile(output, function (err, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual('png', info.format);
|
assert.strictEqual('png', info.format);
|
||||||
@@ -112,6 +123,9 @@ describe('Text to image', function () {
|
|||||||
font: 'sans 100'
|
font: 'sans 100'
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
if (!sharp.versions.pango) {
|
||||||
|
return this.skip();
|
||||||
|
}
|
||||||
text.toFile(output, function (err, info) {
|
text.toFile(output, function (err, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual('png', info.format);
|
assert.strictEqual('png', info.format);
|
||||||
@@ -122,7 +136,7 @@ describe('Text to image', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('text with justify and composite', done => {
|
it('text with justify and composite', function (done) {
|
||||||
const output = fixtures.path('output.text-composite.png');
|
const output = fixtures.path('output.text-composite.png');
|
||||||
const width = 500;
|
const width = 500;
|
||||||
const dpi = 300;
|
const dpi = 300;
|
||||||
@@ -153,6 +167,9 @@ describe('Text to image', function () {
|
|||||||
left: 30,
|
left: 30,
|
||||||
top: 250
|
top: 250
|
||||||
}]);
|
}]);
|
||||||
|
if (!sharp.versions.pango) {
|
||||||
|
return this.skip();
|
||||||
|
}
|
||||||
text.toFile(output, function (err, info) {
|
text.toFile(output, function (err, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual('png', info.format);
|
assert.strictEqual('png', info.format);
|
||||||
@@ -211,26 +228,34 @@ describe('Text to image', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('bad width input', function () {
|
it('invalid width', () => {
|
||||||
assert.throws(function () {
|
assert.throws(
|
||||||
sharp({
|
() => sharp({ text: { text: 'text', width: 'bad' } }),
|
||||||
text: {
|
/Expected positive integer for text\.width but received bad of type string/
|
||||||
text: 'text',
|
);
|
||||||
width: 'bad'
|
assert.throws(
|
||||||
}
|
() => sharp({ text: { text: 'text', width: 0.1 } }),
|
||||||
});
|
/Expected positive integer for text\.width but received 0.1 of type number/
|
||||||
});
|
);
|
||||||
|
assert.throws(
|
||||||
|
() => sharp({ text: { text: 'text', width: -1 } }),
|
||||||
|
/Expected positive integer for text\.width but received -1 of type number/
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('bad height input', function () {
|
it('invalid height', () => {
|
||||||
assert.throws(function () {
|
assert.throws(
|
||||||
sharp({
|
() => sharp({ text: { text: 'text', height: 'bad' } }),
|
||||||
text: {
|
/Expected positive integer for text\.height but received bad of type string/
|
||||||
text: 'text',
|
);
|
||||||
height: 'bad'
|
assert.throws(
|
||||||
}
|
() => sharp({ text: { text: 'text', height: 0.1 } }),
|
||||||
});
|
/Expected positive integer for text\.height but received 0.1 of type number/
|
||||||
});
|
);
|
||||||
|
assert.throws(
|
||||||
|
() => sharp({ text: { text: 'text', height: -1 } }),
|
||||||
|
/Expected positive integer for text\.height but received -1 of type number/
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('bad align input', function () {
|
it('bad align input', function () {
|
||||||
@@ -255,15 +280,19 @@ describe('Text to image', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('bad dpi input', function () {
|
it('invalid dpi', () => {
|
||||||
assert.throws(function () {
|
assert.throws(
|
||||||
sharp({
|
() => sharp({ text: { text: 'text', dpi: 'bad' } }),
|
||||||
text: {
|
/Expected integer between 1 and 1000000 for text\.dpi but received bad of type string/
|
||||||
text: 'text',
|
);
|
||||||
dpi: -10
|
assert.throws(
|
||||||
}
|
() => sharp({ text: { text: 'text', dpi: 0.1 } }),
|
||||||
});
|
/Expected integer between 1 and 1000000 for text\.dpi but received 0.1 of type number/
|
||||||
});
|
);
|
||||||
|
assert.throws(
|
||||||
|
() => sharp({ text: { text: 'text', dpi: -1 } }),
|
||||||
|
/Expected integer between 1 and 1000000 for text\.dpi but received -1 of type number/
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('bad rgba input', function () {
|
it('bad rgba input', function () {
|
||||||
@@ -277,15 +306,19 @@ describe('Text to image', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('bad spacing input', function () {
|
it('invalid spacing', () => {
|
||||||
assert.throws(function () {
|
assert.throws(
|
||||||
sharp({
|
() => sharp({ text: { text: 'text', spacing: 'bad' } }),
|
||||||
text: {
|
/Expected integer between -1000000 and 1000000 for text\.spacing but received bad of type string/
|
||||||
text: 'text',
|
);
|
||||||
spacing: 'number expected'
|
assert.throws(
|
||||||
}
|
() => sharp({ text: { text: 'text', spacing: 0.1 } }),
|
||||||
});
|
/Expected integer between -1000000 and 1000000 for text\.spacing but received 0.1 of type number/
|
||||||
});
|
);
|
||||||
|
assert.throws(
|
||||||
|
() => sharp({ text: { text: 'text', spacing: -1000001 } }),
|
||||||
|
/Expected integer between -1000000 and 1000000 for text\.spacing but received -1000001 of type number/
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('only height or dpi not both', function () {
|
it('only height or dpi not both', function () {
|
||||||
@@ -302,21 +335,21 @@ describe('Text to image', function () {
|
|||||||
|
|
||||||
it('valid wrap throws', () => {
|
it('valid wrap throws', () => {
|
||||||
assert.doesNotThrow(() => sharp({ text: { text: 'text', wrap: 'none' } }));
|
assert.doesNotThrow(() => sharp({ text: { text: 'text', wrap: 'none' } }));
|
||||||
assert.doesNotThrow(() => sharp({ text: { text: 'text', wrap: 'wordChar' } }));
|
assert.doesNotThrow(() => sharp({ text: { text: 'text', wrap: 'word-char' } }));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('invalid wrap throws', () => {
|
it('invalid wrap throws', () => {
|
||||||
assert.throws(
|
assert.throws(
|
||||||
() => sharp({ text: { text: 'text', wrap: 1 } }),
|
() => sharp({ text: { text: 'text', wrap: 1 } }),
|
||||||
/Expected one of: word, char, wordChar, none for text\.wrap but received 1 of type number/
|
/Expected one of: word, char, word-char, none for text\.wrap but received 1 of type number/
|
||||||
);
|
);
|
||||||
assert.throws(
|
assert.throws(
|
||||||
() => sharp({ text: { text: 'text', wrap: false } }),
|
() => sharp({ text: { text: 'text', wrap: false } }),
|
||||||
/Expected one of: word, char, wordChar, none for text\.wrap but received false of type boolean/
|
/Expected one of: word, char, word-char, none for text\.wrap but received false of type boolean/
|
||||||
);
|
);
|
||||||
assert.throws(
|
assert.throws(
|
||||||
() => sharp({ text: { text: 'text', wrap: 'invalid' } }),
|
() => sharp({ text: { text: 'text', wrap: 'invalid' } }),
|
||||||
/Expected one of: word, char, wordChar, none for text\.wrap but received invalid of type string/
|
/Expected one of: word, char, word-char, none for text\.wrap but received invalid of type string/
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -462,6 +462,18 @@ describe('TIFF', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('TIFF miniswhite true value does not throw error', function () {
|
||||||
|
assert.doesNotThrow(function () {
|
||||||
|
sharp().tiff({ miniswhite: true });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Invalid TIFF miniswhite value throws error', function () {
|
||||||
|
assert.throws(function () {
|
||||||
|
sharp().tiff({ miniswhite: 'true' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it('Invalid TIFF tile value throws error', function () {
|
it('Invalid TIFF tile value throws error', function () {
|
||||||
assert.throws(function () {
|
assert.throws(function () {
|
||||||
sharp().tiff({ tile: 'true' });
|
sharp().tiff({ tile: 'true' });
|
||||||
|
|||||||
@@ -741,28 +741,6 @@ describe('Tile', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Google layout with depth onepixel', function (done) {
|
|
||||||
const directory = fixtures.path('output.google_depth_onepixel.dzi');
|
|
||||||
fs.rm(directory, { recursive: true }, function () {
|
|
||||||
sharp(fixtures.inputJpg)
|
|
||||||
.tile({
|
|
||||||
layout: 'google',
|
|
||||||
depth: 'onepixel',
|
|
||||||
size: 256
|
|
||||||
})
|
|
||||||
.toFile(directory, function (err, info) {
|
|
||||||
if (err) throw err;
|
|
||||||
assert.strictEqual('dz', info.format);
|
|
||||||
assert.strictEqual(2725, info.width);
|
|
||||||
assert.strictEqual(2225, info.height);
|
|
||||||
assert.strictEqual(3, info.channels);
|
|
||||||
assert.strictEqual('number', typeof info.size);
|
|
||||||
|
|
||||||
assertGoogleTiles(directory, 256, 13, done);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('Google layout with depth onetile', function (done) {
|
it('Google layout with depth onetile', function (done) {
|
||||||
const directory = fixtures.path('output.google_depth_onetile.dzi');
|
const directory = fixtures.path('output.google_depth_onetile.dzi');
|
||||||
fs.rm(directory, { recursive: true }, function () {
|
fs.rm(directory, { recursive: true }, function () {
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ const fixtures = require('../fixtures');
|
|||||||
describe('Timeout', function () {
|
describe('Timeout', function () {
|
||||||
it('Will timeout after 1s when performing slow blur operation', () => assert.rejects(
|
it('Will timeout after 1s when performing slow blur operation', () => assert.rejects(
|
||||||
() => sharp(fixtures.inputJpg)
|
() => sharp(fixtures.inputJpg)
|
||||||
.blur(100)
|
.blur(200)
|
||||||
.timeout({ seconds: 1 })
|
.timeout({ seconds: 1 })
|
||||||
.toBuffer(),
|
.toBuffer(),
|
||||||
/timeout: [0-9]+% complete/
|
/timeout: [0-9]+% complete/
|
||||||
|
|||||||
@@ -8,16 +8,19 @@ const assert = require('assert');
|
|||||||
const sharp = require('../../');
|
const sharp = require('../../');
|
||||||
const fixtures = require('../fixtures');
|
const fixtures = require('../fixtures');
|
||||||
|
|
||||||
|
// Allow for small rounding differences between platforms
|
||||||
|
const maxDistance = 6;
|
||||||
|
|
||||||
describe('Tint', function () {
|
describe('Tint', function () {
|
||||||
it('tints rgb image red', function (done) {
|
it('tints rgb image red', function (done) {
|
||||||
const output = fixtures.path('output.tint-red.jpg');
|
const output = fixtures.path('output.tint-red.jpg');
|
||||||
sharp(fixtures.inputJpg)
|
sharp(fixtures.inputJpg)
|
||||||
.resize(320, 240, { fastShrinkOnLoad: false })
|
.resize(320, 240)
|
||||||
.tint('#FF0000')
|
.tint('#FF0000')
|
||||||
.toFile(output, function (err, info) {
|
.toFile(output, function (err, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(true, info.size > 0);
|
assert.strictEqual(true, info.size > 0);
|
||||||
fixtures.assertMaxColourDistance(output, fixtures.expected('tint-red.jpg'), 18);
|
fixtures.assertMaxColourDistance(output, fixtures.expected('tint-red.jpg'), maxDistance);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -25,12 +28,12 @@ describe('Tint', function () {
|
|||||||
it('tints rgb image green', function (done) {
|
it('tints rgb image green', function (done) {
|
||||||
const output = fixtures.path('output.tint-green.jpg');
|
const output = fixtures.path('output.tint-green.jpg');
|
||||||
sharp(fixtures.inputJpg)
|
sharp(fixtures.inputJpg)
|
||||||
.resize(320, 240, { fastShrinkOnLoad: false })
|
.resize(320, 240)
|
||||||
.tint('#00FF00')
|
.tint('#00FF00')
|
||||||
.toFile(output, function (err, info) {
|
.toFile(output, function (err, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(true, info.size > 0);
|
assert.strictEqual(true, info.size > 0);
|
||||||
fixtures.assertMaxColourDistance(output, fixtures.expected('tint-green.jpg'), 27);
|
fixtures.assertMaxColourDistance(output, fixtures.expected('tint-green.jpg'), maxDistance);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -38,40 +41,40 @@ describe('Tint', function () {
|
|||||||
it('tints rgb image blue', function (done) {
|
it('tints rgb image blue', function (done) {
|
||||||
const output = fixtures.path('output.tint-blue.jpg');
|
const output = fixtures.path('output.tint-blue.jpg');
|
||||||
sharp(fixtures.inputJpg)
|
sharp(fixtures.inputJpg)
|
||||||
.resize(320, 240, { fastShrinkOnLoad: false })
|
.resize(320, 240)
|
||||||
.tint('#0000FF')
|
.tint('#0000FF')
|
||||||
.toFile(output, function (err, info) {
|
.toFile(output, function (err, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(true, info.size > 0);
|
assert.strictEqual(true, info.size > 0);
|
||||||
fixtures.assertMaxColourDistance(output, fixtures.expected('tint-blue.jpg'), 14);
|
fixtures.assertMaxColourDistance(output, fixtures.expected('tint-blue.jpg'), maxDistance);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('tints rgb image with sepia tone', function (done) {
|
it('tints rgb image with sepia tone', function (done) {
|
||||||
const output = fixtures.path('output.tint-sepia.jpg');
|
const output = fixtures.path('output.tint-sepia-hex.jpg');
|
||||||
sharp(fixtures.inputJpg)
|
sharp(fixtures.inputJpg)
|
||||||
.resize(320, 240, { fastShrinkOnLoad: false })
|
.resize(320, 240)
|
||||||
.tint('#704214')
|
.tint('#704214')
|
||||||
.toFile(output, function (err, info) {
|
.toFile(output, function (err, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(320, info.width);
|
assert.strictEqual(320, info.width);
|
||||||
assert.strictEqual(240, info.height);
|
assert.strictEqual(240, info.height);
|
||||||
fixtures.assertMaxColourDistance(output, fixtures.expected('tint-sepia.jpg'), 10);
|
fixtures.assertMaxColourDistance(output, fixtures.expected('tint-sepia.jpg'), maxDistance);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('tints rgb image with sepia tone with rgb colour', function (done) {
|
it('tints rgb image with sepia tone with rgb colour', function (done) {
|
||||||
const output = fixtures.path('output.tint-sepia.jpg');
|
const output = fixtures.path('output.tint-sepia-rgb.jpg');
|
||||||
sharp(fixtures.inputJpg)
|
sharp(fixtures.inputJpg)
|
||||||
.resize(320, 240, { fastShrinkOnLoad: false })
|
.resize(320, 240)
|
||||||
.tint([112, 66, 20])
|
.tint([112, 66, 20])
|
||||||
.toFile(output, function (err, info) {
|
.toFile(output, function (err, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(320, info.width);
|
assert.strictEqual(320, info.width);
|
||||||
assert.strictEqual(240, info.height);
|
assert.strictEqual(240, info.height);
|
||||||
fixtures.assertMaxColourDistance(output, fixtures.expected('tint-sepia.jpg'), 10);
|
fixtures.assertMaxColourDistance(output, fixtures.expected('tint-sepia.jpg'), maxDistance);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -79,13 +82,13 @@ describe('Tint', function () {
|
|||||||
it('tints rgb image with alpha channel', function (done) {
|
it('tints rgb image with alpha channel', function (done) {
|
||||||
const output = fixtures.path('output.tint-alpha.png');
|
const output = fixtures.path('output.tint-alpha.png');
|
||||||
sharp(fixtures.inputPngRGBWithAlpha)
|
sharp(fixtures.inputPngRGBWithAlpha)
|
||||||
.resize(320, 240, { fastShrinkOnLoad: false })
|
.resize(320, 240)
|
||||||
.tint('#704214')
|
.tint('#704214')
|
||||||
.toFile(output, function (err, info) {
|
.toFile(output, function (err, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(320, info.width);
|
assert.strictEqual(320, info.width);
|
||||||
assert.strictEqual(240, info.height);
|
assert.strictEqual(240, info.height);
|
||||||
fixtures.assertMaxColourDistance(output, fixtures.expected('tint-alpha.png'), 10);
|
fixtures.assertMaxColourDistance(output, fixtures.expected('tint-alpha.png'), maxDistance);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -93,12 +96,12 @@ describe('Tint', function () {
|
|||||||
it('tints cmyk image red', function (done) {
|
it('tints cmyk image red', function (done) {
|
||||||
const output = fixtures.path('output.tint-cmyk.jpg');
|
const output = fixtures.path('output.tint-cmyk.jpg');
|
||||||
sharp(fixtures.inputJpgWithCmykProfile)
|
sharp(fixtures.inputJpgWithCmykProfile)
|
||||||
.resize(320, 240, { fastShrinkOnLoad: false })
|
.resize(320, 240)
|
||||||
.tint('#FF0000')
|
.tint('#FF0000')
|
||||||
.toFile(output, function (err, info) {
|
.toFile(output, function (err, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(true, info.size > 0);
|
assert.strictEqual(true, info.size > 0);
|
||||||
fixtures.assertMaxColourDistance(output, fixtures.expected('tint-cmyk.jpg'), 15);
|
fixtures.assertMaxColourDistance(output, fixtures.expected('tint-cmyk.jpg'), maxDistance);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -46,7 +46,9 @@ describe('Trim borders', function () {
|
|||||||
it('16-bit PNG with alpha channel', function (done) {
|
it('16-bit PNG with alpha channel', function (done) {
|
||||||
sharp(fixtures.inputPngWithTransparency16bit)
|
sharp(fixtures.inputPngWithTransparency16bit)
|
||||||
.resize(32, 32)
|
.resize(32, 32)
|
||||||
.trim(20)
|
.trim({
|
||||||
|
threshold: 20
|
||||||
|
})
|
||||||
.toBuffer(function (err, data, info) {
|
.toBuffer(function (err, data, info) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
assert.strictEqual(true, data.length > 0);
|
assert.strictEqual(true, data.length > 0);
|
||||||
@@ -96,7 +98,9 @@ describe('Trim borders', function () {
|
|||||||
.then(rotated30 =>
|
.then(rotated30 =>
|
||||||
sharp(rotated30)
|
sharp(rotated30)
|
||||||
.rotate(-30)
|
.rotate(-30)
|
||||||
.trim(128)
|
.trim({
|
||||||
|
threshold: 128
|
||||||
|
})
|
||||||
.toBuffer({ resolveWithObject: true })
|
.toBuffer({ resolveWithObject: true })
|
||||||
.then(({ info }) => {
|
.then(({ info }) => {
|
||||||
assert.strictEqual(20, info.width);
|
assert.strictEqual(20, info.width);
|
||||||
@@ -198,49 +202,26 @@ describe('Trim borders', function () {
|
|||||||
assert.strictEqual(trimOffsetLeft, 0);
|
assert.strictEqual(trimOffsetLeft, 0);
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('Valid parameters', function () {
|
it('Works with line-art', async () => {
|
||||||
const expected = fixtures.expected('alpha-layer-1-fill-trim-resize.png');
|
const { info } = await sharp(fixtures.inputJpgOverlayLayer2)
|
||||||
Object.entries({
|
.trim({ lineArt: true })
|
||||||
'Background and threshold default': undefined,
|
.toBuffer({ resolveWithObject: true });
|
||||||
'Background string': '#00000000',
|
|
||||||
'Background option': {
|
assert.strictEqual(info.trimOffsetTop, -552);
|
||||||
background: '#00000000'
|
|
||||||
},
|
|
||||||
'Threshold number': 10,
|
|
||||||
'Threshold option': {
|
|
||||||
threshold: 10
|
|
||||||
}
|
|
||||||
}).forEach(function ([description, parameter]) {
|
|
||||||
it(description, function (done) {
|
|
||||||
sharp(fixtures.inputPngOverlayLayer1)
|
|
||||||
.resize(450, 322)
|
|
||||||
.trim(parameter)
|
|
||||||
.toBuffer(function (err, data, info) {
|
|
||||||
if (err) throw err;
|
|
||||||
assert.strictEqual('png', info.format);
|
|
||||||
assert.strictEqual(450, info.width);
|
|
||||||
assert.strictEqual(322, info.height);
|
|
||||||
assert.strictEqual(-204, info.trimOffsetLeft);
|
|
||||||
assert.strictEqual(0, info.trimOffsetTop);
|
|
||||||
fixtures.assertSimilar(expected, data, done);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('Invalid parameters', function () {
|
describe('Invalid parameters', function () {
|
||||||
Object.entries({
|
Object.entries({
|
||||||
'Invalid background string': 'fail',
|
'Invalid string': 'fail',
|
||||||
'Invalid background option': {
|
'Invalid background option': {
|
||||||
background: 'fail'
|
background: 'fail'
|
||||||
},
|
},
|
||||||
|
|
||||||
'Negative threshold number': -1,
|
|
||||||
'Negative threshold option': {
|
'Negative threshold option': {
|
||||||
threshold: -1
|
threshold: -1
|
||||||
},
|
},
|
||||||
|
'Invalid lineArt': {
|
||||||
Boolean: false
|
lineArt: 'fail'
|
||||||
|
}
|
||||||
}).forEach(function ([description, parameter]) {
|
}).forEach(function ([description, parameter]) {
|
||||||
it(description, function () {
|
it(description, function () {
|
||||||
assert.throws(function () {
|
assert.throws(function () {
|
||||||
@@ -253,7 +234,9 @@ describe('Trim borders', function () {
|
|||||||
describe('Specific background colour', function () {
|
describe('Specific background colour', function () {
|
||||||
it('Doesn\'t trim at all', async () => {
|
it('Doesn\'t trim at all', async () => {
|
||||||
const { info } = await sharp(fixtures.inputPngTrimSpecificColour)
|
const { info } = await sharp(fixtures.inputPngTrimSpecificColour)
|
||||||
.trim('yellow')
|
.trim({
|
||||||
|
background: 'yellow'
|
||||||
|
})
|
||||||
.toBuffer({ resolveWithObject: true });
|
.toBuffer({ resolveWithObject: true });
|
||||||
|
|
||||||
const { width, height, trimOffsetTop, trimOffsetLeft } = info;
|
const { width, height, trimOffsetTop, trimOffsetLeft } = info;
|
||||||
@@ -265,7 +248,9 @@ describe('Trim borders', function () {
|
|||||||
|
|
||||||
it('Only trims the bottom', async () => {
|
it('Only trims the bottom', async () => {
|
||||||
const { info } = await sharp(fixtures.inputPngTrimSpecificColour)
|
const { info } = await sharp(fixtures.inputPngTrimSpecificColour)
|
||||||
.trim('#21468B')
|
.trim({
|
||||||
|
background: '#21468B'
|
||||||
|
})
|
||||||
.toBuffer({ resolveWithObject: true });
|
.toBuffer({ resolveWithObject: true });
|
||||||
|
|
||||||
const { width, height, trimOffsetTop, trimOffsetLeft } = info;
|
const { width, height, trimOffsetTop, trimOffsetLeft } = info;
|
||||||
@@ -277,7 +262,9 @@ describe('Trim borders', function () {
|
|||||||
|
|
||||||
it('Only trims the bottom, in 16-bit', async () => {
|
it('Only trims the bottom, in 16-bit', async () => {
|
||||||
const { info } = await sharp(fixtures.inputPngTrimSpecificColour16bit)
|
const { info } = await sharp(fixtures.inputPngTrimSpecificColour16bit)
|
||||||
.trim('#21468B')
|
.trim({
|
||||||
|
background: '#21468B'
|
||||||
|
})
|
||||||
.toBuffer({ resolveWithObject: true });
|
.toBuffer({ resolveWithObject: true });
|
||||||
|
|
||||||
const { width, height, trimOffsetTop, trimOffsetLeft } = info;
|
const { width, height, trimOffsetTop, trimOffsetLeft } = info;
|
||||||
@@ -289,7 +276,9 @@ describe('Trim borders', function () {
|
|||||||
|
|
||||||
it('Only trims the bottom, including alpha', async () => {
|
it('Only trims the bottom, including alpha', async () => {
|
||||||
const { info } = await sharp(fixtures.inputPngTrimSpecificColourIncludeAlpha)
|
const { info } = await sharp(fixtures.inputPngTrimSpecificColourIncludeAlpha)
|
||||||
.trim('#21468B80')
|
.trim({
|
||||||
|
background: '#21468B80'
|
||||||
|
})
|
||||||
.toBuffer({ resolveWithObject: true });
|
.toBuffer({ resolveWithObject: true });
|
||||||
|
|
||||||
const { width, height, trimOffsetTop, trimOffsetLeft } = info;
|
const { width, height, trimOffsetTop, trimOffsetLeft } = info;
|
||||||
|
|||||||
@@ -9,16 +9,19 @@ const sharp = require('../../');
|
|||||||
|
|
||||||
describe('Utilities', function () {
|
describe('Utilities', function () {
|
||||||
describe('Cache', function () {
|
describe('Cache', function () {
|
||||||
it('Can be disabled', function () {
|
it('Can be disabled', function (done) {
|
||||||
sharp.cache(false);
|
queueMicrotask(() => {
|
||||||
const cache = sharp.cache(false);
|
sharp.cache(false);
|
||||||
assert.strictEqual(cache.memory.current, 0);
|
const cache = sharp.cache(false);
|
||||||
assert.strictEqual(cache.memory.max, 0);
|
assert.strictEqual(cache.memory.current, 0);
|
||||||
assert.strictEqual(typeof cache.memory.high, 'number');
|
assert.strictEqual(cache.memory.max, 0);
|
||||||
assert.strictEqual(cache.files.current, 0);
|
assert.strictEqual(typeof cache.memory.high, 'number');
|
||||||
assert.strictEqual(cache.files.max, 0);
|
assert.strictEqual(cache.files.current, 0);
|
||||||
assert.strictEqual(cache.items.current, 0);
|
assert.strictEqual(cache.files.max, 0);
|
||||||
assert.strictEqual(cache.items.max, 0);
|
assert.strictEqual(cache.items.current, 0);
|
||||||
|
assert.strictEqual(cache.items.max, 0);
|
||||||
|
done();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
it('Can be enabled with defaults', function () {
|
it('Can be enabled with defaults', function () {
|
||||||
const cache = sharp.cache(true);
|
const cache = sharp.cache(true);
|
||||||
@@ -131,7 +134,7 @@ describe('Utilities', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
it('input fileSuffix', function () {
|
it('input fileSuffix', function () {
|
||||||
assert.deepStrictEqual(['.jpg', '.jpeg', '.jpe'], sharp.format.jpeg.input.fileSuffix);
|
assert.deepStrictEqual(['.jpg', '.jpeg', '.jpe', '.jfif'], sharp.format.jpeg.input.fileSuffix);
|
||||||
});
|
});
|
||||||
it('output alias', function () {
|
it('output alias', function () {
|
||||||
assert.deepStrictEqual(['jpe', 'jpg'], sharp.format.jpeg.output.alias);
|
assert.deepStrictEqual(['jpe', 'jpg'], sharp.format.jpeg.output.alias);
|
||||||
|
|||||||