Compare commits
No commits in common. "main" and "v0.32.0" have entirely different histories.
79
.circleci/config.yml
Normal file
@ -0,0 +1,79 @@
|
||||
version: 2.1
|
||||
|
||||
workflows:
|
||||
build:
|
||||
jobs:
|
||||
- linux-arm64-glibc-node-14:
|
||||
filters:
|
||||
tags:
|
||||
only: /^v.*/
|
||||
- linux-arm64-musl-node-14:
|
||||
filters:
|
||||
tags:
|
||||
only: /^v.*/
|
||||
- linux-arm64-glibc-node-18:
|
||||
filters:
|
||||
tags:
|
||||
only: /^v.*/
|
||||
- linux-arm64-musl-node-18:
|
||||
filters:
|
||||
tags:
|
||||
only: /^v.*/
|
||||
|
||||
jobs:
|
||||
linux-arm64-glibc-node-14:
|
||||
resource_class: arm.medium
|
||||
machine:
|
||||
image: ubuntu-2004:current
|
||||
steps:
|
||||
- checkout
|
||||
- run: |
|
||||
sudo docker run -dit --name sharp --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp arm64v8/debian:bullseye
|
||||
sudo docker exec sharp sh -c "apt-get update && apt-get install -y build-essential git python3 curl fonts-noto-core"
|
||||
sudo docker exec sharp sh -c "curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -"
|
||||
sudo docker exec sharp sh -c "echo 'deb https://deb.nodesource.com/node_14.x sid main' >/etc/apt/sources.list.d/nodesource.list"
|
||||
sudo docker exec sharp sh -c "apt-get update && apt-get install -y nodejs"
|
||||
- run: sudo docker exec sharp sh -c "npm install --build-from-source --unsafe-perm"
|
||||
- run: sudo docker exec sharp sh -c "npm test"
|
||||
- run: "[[ -n $CIRCLE_TAG ]] && sudo docker exec --env prebuild_upload sharp sh -c \"npx prebuild --runtime napi --target 7 --upload=$prebuild_upload\" || true"
|
||||
linux-arm64-glibc-node-18:
|
||||
resource_class: arm.medium
|
||||
machine:
|
||||
image: ubuntu-2004:current
|
||||
steps:
|
||||
- checkout
|
||||
- run: |
|
||||
sudo docker run -dit --name sharp --workdir /mnt/sharp arm64v8/debian:bullseye
|
||||
sudo docker exec sharp sh -c "apt-get update && apt-get install -y build-essential git python3 curl fonts-noto-core"
|
||||
sudo docker exec sharp sh -c "curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -"
|
||||
sudo docker exec sharp sh -c "echo 'deb https://deb.nodesource.com/node_18.x sid main' >/etc/apt/sources.list.d/nodesource.list"
|
||||
sudo docker exec sharp sh -c "apt-get update && apt-get install -y nodejs"
|
||||
sudo docker exec sharp sh -c "mkdir -p /mnt/sharp"
|
||||
sudo docker cp . sharp:/mnt/sharp/.
|
||||
- run: sudo docker exec sharp sh -c "npm install --build-from-source"
|
||||
- run: sudo docker exec sharp sh -c "npm test"
|
||||
linux-arm64-musl-node-14:
|
||||
resource_class: arm.medium
|
||||
machine:
|
||||
image: ubuntu-2004:current
|
||||
steps:
|
||||
- checkout
|
||||
- run: |
|
||||
sudo docker run -dit --name sharp --volume "${PWD}:/mnt/sharp" --workdir /mnt/sharp node:14-alpine3.12
|
||||
sudo docker exec sharp sh -c "apk add build-base git python3 font-noto --update-cache"
|
||||
- run: sudo docker exec sharp sh -c "npm install --build-from-source --unsafe-perm"
|
||||
- run: sudo docker exec sharp sh -c "npm test"
|
||||
- run: "[[ -n $CIRCLE_TAG ]] && sudo docker exec --env prebuild_upload sharp sh -c \"npx prebuild --runtime napi --target 7 --upload=$prebuild_upload\" || true"
|
||||
linux-arm64-musl-node-18:
|
||||
resource_class: arm.medium
|
||||
machine:
|
||||
image: ubuntu-2004:current
|
||||
steps:
|
||||
- checkout
|
||||
- run: |
|
||||
sudo docker run -dit --name sharp --workdir /mnt/sharp node:18-alpine3.14
|
||||
sudo docker exec sharp sh -c "apk add build-base git python3 font-noto --update-cache"
|
||||
sudo docker exec sharp sh -c "mkdir -p /mnt/sharp"
|
||||
sudo docker cp . sharp:/mnt/sharp/.
|
||||
- run: sudo docker exec sharp sh -c "npm install --build-from-source"
|
||||
- run: sudo docker exec sharp sh -c "npm test"
|
@ -1,5 +1,5 @@
|
||||
freebsd_instance:
|
||||
image_family: freebsd-15-0-snap
|
||||
image_family: freebsd-14-0-snap
|
||||
|
||||
task:
|
||||
name: FreeBSD
|
||||
@ -9,9 +9,8 @@ task:
|
||||
prerequisites_script:
|
||||
- pkg update -f
|
||||
- pkg upgrade -y
|
||||
- pkg install -y devel/git devel/pkgconf graphics/vips www/node20 www/npm
|
||||
- pkg-config --modversion vips-cpp
|
||||
- pkg install -y devel/pkgconf graphics/vips www/node16 www/npm
|
||||
install_script:
|
||||
- npm install --build-from-source
|
||||
- npm install --build-from-source --unsafe-perm
|
||||
test_script:
|
||||
- npx mocha --no-config --spec=test/unit/io.js --timeout=30000
|
||||
- npm test
|
||||
|
1
.gitattributes
vendored
Normal file
@ -0,0 +1 @@
|
||||
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
|
||||
|
||||
The public API is documented with [JSDoc](https://jsdoc.app/) annotated comments.
|
||||
The public API is documented with [JSDoc](http://usejsdoc.org/) annotated comments.
|
||||
|
||||
These can be converted to Markdown by running:
|
||||
```sh
|
||||
|
38
.github/ISSUE_TEMPLATE/installation.md
vendored
@ -11,10 +11,8 @@ labels: installation
|
||||
|
||||
<!-- Please place an [x] in the box to confirm. -->
|
||||
|
||||
- [ ] I have read and understood all of the [documentation relating to installation](https://sharp.pixelplumbing.com/install).
|
||||
- [ ] I have searched for known bugs relating to this problem in my choice of package manager.
|
||||
|
||||
You must confirm both of these before continuing.
|
||||
- [ ] I have read the [documentation relating to installation](https://sharp.pixelplumbing.com/install).
|
||||
- [ ] I have ensured that the architecture and platform of Node.js used for `npm install` is the same as the architecture and platform of Node.js used at runtime.
|
||||
|
||||
### Are you using the latest version of sharp?
|
||||
|
||||
@ -24,37 +22,15 @@ You must confirm both of these before continuing.
|
||||
|
||||
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?
|
||||
### Is this a problem with filesystem permissions?
|
||||
|
||||
<!-- Please place an [x] in the relevant box to confirm. -->
|
||||
If you are using npm v6 or earlier and installing as a `root` or `sudo` user, have you tried with the `npm install --unsafe-perm` flag?
|
||||
|
||||
- [ ] I am using Node.js with a version that satisfies `^18.17.0 || ^20.3.0 || >=21.0.0`
|
||||
- [ ] I am using Deno
|
||||
- [ ] I am using Bun
|
||||
If you are using npm v7 or later, does the user running `npm install` own the directory it is run in?
|
||||
|
||||
If you cannot confirm any of these,
|
||||
please upgrade to the latest version
|
||||
and try again before opening an issue.
|
||||
|
||||
### Are you using a supported package manager and installing optional dependencies?
|
||||
|
||||
<!-- Please place an [x] in the relevant box to confirm. -->
|
||||
|
||||
- [ ] I am using npm >= 10.1.0 with `--include=optional`
|
||||
- [ ] I am using yarn >= 3.2.0
|
||||
- [ ] I am using pnpm >= 7.1.0 with `--no-optional=false`
|
||||
- [ ] I am using Deno
|
||||
- [ ] I am using Bun
|
||||
|
||||
If you cannot confirm any of these, please upgrade to the latest version of your chosen package manager
|
||||
and ensure you are allowing the installation of optional or multi-platform dependencies before opening an issue.
|
||||
|
||||
### What is the complete error message, including the full stack trace?
|
||||
|
||||
<!-- Please provide the error message and stack trace here. -->
|
||||
If you are using the `ignore-scripts` feature of `npm`, have you tried with the `npm install --ignore-scripts=false` flag?
|
||||
|
||||
### What is the complete output of running `npm install --verbose --foreground-scripts sharp` in an empty directory?
|
||||
|
||||
|
16
.github/ISSUE_TEMPLATE/possible-bug.md
vendored
@ -32,22 +32,6 @@ If you are using another package which depends on a version of `sharp` that is n
|
||||
|
||||
<!-- Please provide output of the above command here. -->
|
||||
|
||||
### Does this problem relate to file caching?
|
||||
|
||||
The default behaviour of libvips is to cache input files, which can lead to `EBUSY` or `EPERM` errors on Windows.
|
||||
Use [`sharp.cache(false)`](https://sharp.pixelplumbing.com/api-utility#cache) to switch this feature off.
|
||||
|
||||
- [ ] Adding `sharp.cache(false)` does not fix this problem.
|
||||
|
||||
### Does this problem relate to images appearing to have been rotated by 90 degrees?
|
||||
|
||||
Images that contain EXIF Orientation metadata are not auto-oriented. By default, EXIF metadata is removed.
|
||||
|
||||
- To auto-orient pixel values use the parameter-less [`rotate()`](https://sharp.pixelplumbing.com/api-operation#rotate) operation.
|
||||
- To retain EXIF Orientation use [`keepExif()`](https://sharp.pixelplumbing.com/api-output#keepexif).
|
||||
|
||||
- [ ] Using `rotate()` or `keepExif()` does not fix this problem.
|
||||
|
||||
### What are the steps to reproduce?
|
||||
|
||||
<!-- Please enter steps to reproduce here. -->
|
||||
|
18
.github/SECURITY.md
vendored
@ -1,18 +0,0 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
The latest version of `sharp` as published to npm
|
||||
and reported by `npm view sharp dist-tags.latest`
|
||||
is supported with security updates.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Please use
|
||||
[e-mail](https://github.com/lovell/sharp/blob/main/package.json#L5)
|
||||
to report a vulnerability.
|
||||
|
||||
You can expect a response within 48 hours
|
||||
if you are a human reporting a genuine issue.
|
||||
|
||||
Thank you in advance.
|
40
.github/workflows/ci-darwin-arm64v8.yml
vendored
Normal file
@ -0,0 +1,40 @@
|
||||
name: CI (MacStadium)
|
||||
on:
|
||||
- push
|
||||
- pull_request
|
||||
permissions: {}
|
||||
jobs:
|
||||
CI:
|
||||
permissions:
|
||||
contents: write # for npx prebuild to make release
|
||||
name: Node.js ${{ matrix.nodejs_version }} ${{ matrix.nodejs_arch }} ${{ matrix.prebuild && '- prebuild' }}
|
||||
runs-on: macos-m1
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- nodejs_version: 14
|
||||
nodejs_arch: x64
|
||||
- nodejs_version: 18
|
||||
nodejs_arch: arm64
|
||||
prebuild: true
|
||||
defaults:
|
||||
run:
|
||||
shell: /usr/bin/arch -arch arm64e /bin/bash -l {0}
|
||||
steps:
|
||||
- name: Dependencies (Node.js)
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: ${{ matrix.nodejs_version }}
|
||||
architecture: ${{ matrix.nodejs_arch }}
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
- name: Install
|
||||
run: npm install --build-from-source --unsafe-perm
|
||||
- name: Test
|
||||
run: npm test
|
||||
- name: Prebuild
|
||||
if: matrix.prebuild && startsWith(github.ref, 'refs/tags/')
|
||||
env:
|
||||
prebuild_upload: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: npx prebuild --runtime napi --target 7
|
355
.github/workflows/ci.yml
vendored
@ -1,324 +1,105 @@
|
||||
name: CI
|
||||
name: CI (GitHub)
|
||||
on:
|
||||
- push
|
||||
- pull_request
|
||||
permissions: {}
|
||||
jobs:
|
||||
build-native:
|
||||
CI:
|
||||
permissions:
|
||||
contents: read
|
||||
name: "build-${{ matrix.platform }} [Node.js ${{ matrix.nodejs_version_major }}] ${{ matrix.package && '[package]' }}"
|
||||
contents: write # for npx prebuild to make release
|
||||
name: ${{ matrix.container || matrix.os }} - Node.js ${{ matrix.nodejs_version }} ${{ matrix.nodejs_arch }} ${{ matrix.prebuild && '- prebuild' }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
container: ${{ matrix.container }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-24.04
|
||||
- os: ubuntu-22.04
|
||||
container: centos:7
|
||||
nodejs_version: 14
|
||||
prebuild: true
|
||||
- os: ubuntu-22.04
|
||||
container: centos:7
|
||||
nodejs_version: 16
|
||||
- os: ubuntu-22.04
|
||||
container: rockylinux:8
|
||||
nodejs_version: 18
|
||||
- os: ubuntu-22.04
|
||||
container: node:14-alpine3.12
|
||||
prebuild: true
|
||||
- os: ubuntu-22.04
|
||||
container: node:16-alpine3.12
|
||||
- os: ubuntu-22.04
|
||||
container: node:18-alpine3.14
|
||||
- os: macos-11
|
||||
nodejs_version: 14
|
||||
prebuild: true
|
||||
nodejs_arch: x64
|
||||
nodejs_version: "^18.17.0"
|
||||
nodejs_version_major: 18
|
||||
platform: linux-x64
|
||||
package: true
|
||||
- os: ubuntu-24.04
|
||||
container: rockylinux:8
|
||||
- os: macos-11
|
||||
nodejs_version: 16
|
||||
nodejs_arch: x64
|
||||
nodejs_version: "^20.3.0"
|
||||
nodejs_version_major: 20
|
||||
platform: linux-x64
|
||||
- os: ubuntu-24.04
|
||||
container: rockylinux:8
|
||||
- os: macos-11
|
||||
nodejs_version: 18
|
||||
nodejs_arch: x64
|
||||
nodejs_version: "^22.9.0"
|
||||
nodejs_version_major: 22
|
||||
platform: linux-x64
|
||||
- os: ubuntu-24.04
|
||||
container: node:18-alpine3.17
|
||||
nodejs_version_major: 18
|
||||
platform: linuxmusl-x64
|
||||
package: true
|
||||
- os: ubuntu-24.04
|
||||
container: node:20-alpine3.18
|
||||
nodejs_version_major: 20
|
||||
platform: linuxmusl-x64
|
||||
- os: ubuntu-24.04
|
||||
container: node:22-alpine3.20
|
||||
nodejs_version_major: 22
|
||||
platform: linuxmusl-x64
|
||||
- os: ubuntu-24.04-arm
|
||||
container: arm64v8/rockylinux:8
|
||||
nodejs_arch: arm64
|
||||
nodejs_version: "^18.17.0"
|
||||
nodejs_version_major: 18
|
||||
platform: linux-arm64
|
||||
package: true
|
||||
- os: ubuntu-24.04-arm
|
||||
container: arm64v8/rockylinux:8
|
||||
nodejs_arch: arm64
|
||||
nodejs_version: "^20.3.0"
|
||||
nodejs_version_major: 20
|
||||
platform: linux-arm64
|
||||
- os: macos-13
|
||||
nodejs_arch: x64
|
||||
nodejs_version: "^18.17.0"
|
||||
nodejs_version_major: 18
|
||||
platform: darwin-x64
|
||||
package: true
|
||||
- os: macos-13
|
||||
nodejs_arch: x64
|
||||
nodejs_version: "^20.3.0"
|
||||
nodejs_version_major: 20
|
||||
platform: darwin-x64
|
||||
- os: macos-13
|
||||
nodejs_arch: x64
|
||||
nodejs_version: "^22.9.0"
|
||||
nodejs_version_major: 22
|
||||
platform: darwin-x64
|
||||
- os: macos-14
|
||||
nodejs_arch: arm64
|
||||
nodejs_version: "^18.17.0"
|
||||
nodejs_version_major: 18
|
||||
platform: darwin-arm64
|
||||
package: true
|
||||
- os: macos-14
|
||||
nodejs_arch: arm64
|
||||
nodejs_version: "^20.3.0"
|
||||
nodejs_version_major: 20
|
||||
platform: darwin-arm64
|
||||
- os: macos-14
|
||||
nodejs_arch: arm64
|
||||
nodejs_version: "^22.9.0"
|
||||
nodejs_version_major: 22
|
||||
platform: darwin-arm64
|
||||
- os: windows-2022
|
||||
- os: windows-2019
|
||||
nodejs_version: 14
|
||||
nodejs_arch: x86
|
||||
nodejs_version: "18.18.2" # pinned to avoid 18.19.0 and npm 10
|
||||
nodejs_version_major: 18
|
||||
platform: win32-ia32
|
||||
package: true
|
||||
- os: windows-2022
|
||||
prebuild: true
|
||||
- os: windows-2019
|
||||
nodejs_version: 16
|
||||
nodejs_arch: x86
|
||||
nodejs_version: "^20.3.0"
|
||||
nodejs_version_major: 20
|
||||
platform: win32-ia32
|
||||
- os: windows-2022
|
||||
- os: windows-2019
|
||||
nodejs_version: 18
|
||||
nodejs_arch: x86
|
||||
nodejs_version: "^22.9.0"
|
||||
nodejs_version_major: 22
|
||||
platform: win32-ia32
|
||||
- os: windows-2022
|
||||
- os: windows-2019
|
||||
nodejs_version: 14
|
||||
nodejs_arch: x64
|
||||
nodejs_version: "^18.17.0"
|
||||
nodejs_version_major: 18
|
||||
platform: win32-x64
|
||||
package: true
|
||||
- os: windows-2022
|
||||
prebuild: true
|
||||
- os: windows-2019
|
||||
nodejs_version: 16
|
||||
nodejs_arch: x64
|
||||
nodejs_version: "^20.3.0"
|
||||
nodejs_version_major: 20
|
||||
platform: win32-x64
|
||||
- os: windows-2022
|
||||
- os: windows-2019
|
||||
nodejs_version: 18
|
||||
nodejs_arch: x64
|
||||
nodejs_version: "^22.9.0"
|
||||
nodejs_version_major: 22
|
||||
platform: win32-x64
|
||||
- os: windows-11-arm
|
||||
nodejs_arch: arm64
|
||||
nodejs_version: "^20.3.0"
|
||||
nodejs_version_major: 20
|
||||
platform: win32-arm64
|
||||
package: true
|
||||
- os: windows-11-arm
|
||||
nodejs_arch: arm64
|
||||
nodejs_version: "^22.9.0"
|
||||
nodejs_version_major: 22
|
||||
platform: win32-arm64
|
||||
steps:
|
||||
- name: Dependencies (Linux glibc)
|
||||
if: contains(matrix.container, 'centos')
|
||||
run: |
|
||||
curl -sL https://rpm.nodesource.com/setup_${{ matrix.nodejs_version }}.x | bash -
|
||||
yum install -y centos-release-scl
|
||||
yum install -y devtoolset-11-gcc-c++ make git python3 nodejs fontconfig google-noto-sans-fonts
|
||||
echo "/opt/rh/devtoolset-11/root/usr/bin" >> $GITHUB_PATH
|
||||
- name: Dependencies (Rocky Linux glibc)
|
||||
if: contains(matrix.container, 'rockylinux')
|
||||
run: |
|
||||
dnf install -y gcc-toolset-14-gcc-c++ make git python3.12 fontconfig google-noto-sans-fonts
|
||||
echo "/opt/rh/gcc-toolset-14/root/usr/bin" >> $GITHUB_PATH
|
||||
curl -sL https://rpm.nodesource.com/setup_${{ matrix.nodejs_version }}.x | bash -
|
||||
dnf install -y gcc-toolset-11-gcc-c++ make git python3 nodejs fontconfig google-noto-sans-fonts
|
||||
echo "/opt/rh/gcc-toolset-11/root/usr/bin" >> $GITHUB_PATH
|
||||
- name: Dependencies (Linux musl)
|
||||
if: contains(matrix.container, 'alpine')
|
||||
run: apk add build-base git python3 font-noto --update-cache
|
||||
- name: Dependencies (Python 3.11 - macOS, Windows)
|
||||
- name: Dependencies (Python 3.10 - macOS, Windows)
|
||||
if: contains(matrix.os, 'macos') || contains(matrix.os, 'windows')
|
||||
uses: actions/setup-python@v5
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- name: Dependencies (Node.js)
|
||||
if: "!contains(matrix.platform, 'linuxmusl')"
|
||||
uses: actions/setup-node@v4
|
||||
python-version: '3.10'
|
||||
- name: Dependencies (Node.js - macOS, Windows)
|
||||
if: contains(matrix.os, 'macos') || contains(matrix.os, 'windows')
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: ${{ matrix.nodejs_version }}
|
||||
architecture: ${{ matrix.nodejs_arch }}
|
||||
- uses: actions/checkout@v4
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
- name: Fix working directory ownership
|
||||
if: matrix.container
|
||||
run: chown root.root .
|
||||
- name: Install
|
||||
run: npm install --build-from-source
|
||||
run: npm install --build-from-source --unsafe-perm
|
||||
- name: Test
|
||||
run: npm test
|
||||
- name: Populate npm package
|
||||
if: matrix.package
|
||||
run: npm run package-from-local-build
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: matrix.package
|
||||
with:
|
||||
name: ${{ matrix.platform }}
|
||||
path: npm/${{ matrix.platform }}
|
||||
retention-days: 1
|
||||
if-no-files-found: error
|
||||
build-linuxmusl-arm-64:
|
||||
permissions:
|
||||
contents: read
|
||||
name: "build-linuxmusl-arm64 [Node.js ${{ matrix.nodejs_version_major }}] ${{ matrix.package && '[package]' }}"
|
||||
runs-on: ubuntu-24.04-arm
|
||||
container:
|
||||
image: ${{ matrix.container }}
|
||||
volumes:
|
||||
- /:/host
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- container: node:18-alpine3.17
|
||||
nodejs_version_major: 18
|
||||
package: true
|
||||
- container: node:20-alpine3.18
|
||||
nodejs_version_major: 20
|
||||
steps:
|
||||
- name: Allow Linux musl containers on ARM64 runners # https://github.com/actions/runner/issues/801#issuecomment-2394425757
|
||||
shell: sh
|
||||
run: |
|
||||
apk add nodejs
|
||||
sed -i "s:ID=alpine:ID=NotpineForGHA:" /etc/os-release
|
||||
cd /host/home/runner/runners/*/externals/
|
||||
rm -rf node20/*
|
||||
mkdir node20/bin
|
||||
ln -s /usr/bin/node node20/bin/node
|
||||
- name: Dependencies
|
||||
run: apk add build-base git python3 font-noto --update-cache
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install
|
||||
run: npm install --build-from-source
|
||||
- name: Test
|
||||
run: npm test
|
||||
- name: Populate npm package
|
||||
if: matrix.package
|
||||
run: npm run package-from-local-build
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: matrix.package
|
||||
with:
|
||||
name: linuxmusl-arm64
|
||||
path: npm/linuxmusl-arm64
|
||||
retention-days: 1
|
||||
if-no-files-found: error
|
||||
build-qemu:
|
||||
permissions:
|
||||
contents: read
|
||||
name: "build-${{ matrix.platform }} [Node.js ${{ matrix.nodejs_version_major }}] [package]"
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- platform: linux-arm
|
||||
distro: bullseye
|
||||
run_on_arch: armv6
|
||||
nodejs_arch: armv6l
|
||||
nodejs_hostname: unofficial-builds.nodejs.org
|
||||
nodejs_version: "18.17.0"
|
||||
nodejs_version_major: 18
|
||||
- platform: linux-s390x
|
||||
distro: bullseye
|
||||
run_on_arch: s390x
|
||||
nodejs_arch: s390x
|
||||
nodejs_hostname: nodejs.org
|
||||
nodejs_version: "18.17.0"
|
||||
nodejs_version_major: 18
|
||||
- platform: linux-ppc64
|
||||
distro: bullseye
|
||||
run_on_arch: ppc64le
|
||||
nodejs_arch: ppc64le
|
||||
nodejs_hostname: nodejs.org
|
||||
nodejs_version: "18.17.0"
|
||||
nodejs_version_major: 18
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: uraimo/run-on-arch-action@v3
|
||||
with:
|
||||
arch: ${{ matrix.run_on_arch }}
|
||||
distro: ${{ matrix.distro }}
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y curl g++ git libatomic1 make python3 xz-utils
|
||||
mkdir /opt/nodejs
|
||||
curl --silent https://${{ matrix.nodejs_hostname }}/download/release/v${{ matrix.nodejs_version}}/node-v${{ matrix.nodejs_version}}-linux-${{ matrix.nodejs_arch }}.tar.xz | tar xJC /opt/nodejs --strip-components=1
|
||||
export PATH=$PATH:/opt/nodejs/bin
|
||||
npm install --build-from-source
|
||||
npx mocha --no-config --spec=test/unit/io.js --timeout=30000
|
||||
npm run package-from-local-build
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ${{ matrix.platform }}
|
||||
path: npm/${{ matrix.platform }}
|
||||
retention-days: 1
|
||||
if-no-files-found: error
|
||||
build-emscripten:
|
||||
permissions:
|
||||
contents: read
|
||||
name: "build-wasm32 [package]"
|
||||
runs-on: ubuntu-24.04
|
||||
container: "emscripten/emsdk:4.0.10"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Dependencies
|
||||
run: apt-get update && apt-get install -y pkg-config
|
||||
- name: Dependencies (Node.js)
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
- name: Install
|
||||
run: emmake npm install --build-from-source
|
||||
- name: Verify emscripten versions match
|
||||
run: |
|
||||
EMSCRIPTEN_VERSION_LIBVIPS=$(node -p "require('@img/sharp-libvips-dev-wasm32/versions').emscripten")
|
||||
EMSCRIPTEN_VERSION_SHARP=$(emcc -dumpversion)
|
||||
echo "libvips built with emscripten $EMSCRIPTEN_VERSION_LIBVIPS"
|
||||
echo "sharp built with emscripten $EMSCRIPTEN_VERSION_SHARP"
|
||||
test "$EMSCRIPTEN_VERSION_LIBVIPS" = "$EMSCRIPTEN_VERSION_SHARP"
|
||||
- name: Test
|
||||
run: emmake npm test
|
||||
- name: Populate npm package
|
||||
run: emmake npm run package-from-local-build
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: wasm32
|
||||
path: npm/wasm32
|
||||
retention-days: 1
|
||||
if-no-files-found: error
|
||||
release:
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-24.04
|
||||
needs:
|
||||
- build-native
|
||||
- build-linuxmusl-arm-64
|
||||
- build-qemu
|
||||
- build-emscripten
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: npm
|
||||
- name: Create npm workspace tarball
|
||||
run: tar -vcaf npm-workspace.tar.xz --directory npm --exclude=from-local-build.js .
|
||||
- name: Create GitHub release for tag
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
artifacts: npm-workspace.tar.xz
|
||||
artifactContentType: application/x-xz
|
||||
prerelease: ${{ contains(github.ref, '-rc') }}
|
||||
makeLatest: ${{ !contains(github.ref, '-rc') }}
|
||||
- name: Prebuild
|
||||
if: matrix.prebuild && startsWith(github.ref, 'refs/tags/')
|
||||
env:
|
||||
prebuild_upload: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: npx prebuild --runtime napi --target 7
|
||||
|
194
.github/workflows/npm.yml
vendored
@ -1,194 +0,0 @@
|
||||
name: "CI: npm smoke test"
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v**"
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
release-smoke-test:
|
||||
name: "${{ github.ref_name }} ${{ matrix.name }}"
|
||||
runs-on: ${{ matrix.runs-on }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- name: linux-x64-node-npm
|
||||
runs-on: ubuntu-24.04
|
||||
runtime: node
|
||||
package-manager: npm
|
||||
- name: linux-x64-node-pnpm
|
||||
runs-on: ubuntu-24.04
|
||||
runtime: node
|
||||
package-manager: pnpm
|
||||
- name: linux-x64-node-yarn
|
||||
runs-on: ubuntu-24.04
|
||||
runtime: node
|
||||
package-manager: yarn
|
||||
- name: linux-x64-node-yarn-pnp
|
||||
runs-on: ubuntu-24.04
|
||||
runtime: node
|
||||
package-manager: yarn-pnp
|
||||
- name: linux-x64-node-yarn-v1
|
||||
runs-on: ubuntu-24.04
|
||||
runtime: node
|
||||
package-manager: yarn-v1
|
||||
- name: linux-x64-deno
|
||||
runs-on: ubuntu-24.04
|
||||
runtime: deno
|
||||
- name: linux-x64-bun
|
||||
runs-on: ubuntu-24.04
|
||||
runtime: bun
|
||||
|
||||
- name: darwin-x64-node-npm
|
||||
runs-on: macos-13
|
||||
runtime: node
|
||||
package-manager: npm
|
||||
- name: darwin-x64-node-pnpm
|
||||
runs-on: macos-13
|
||||
runtime: node
|
||||
package-manager: pnpm
|
||||
- name: darwin-x64-node-yarn
|
||||
runs-on: macos-13
|
||||
runtime: node
|
||||
package-manager: yarn
|
||||
- name: darwin-x64-node-yarn-pnp
|
||||
runs-on: macos-13
|
||||
runtime: node
|
||||
package-manager: yarn-pnp
|
||||
- name: darwin-x64-node-yarn-v1
|
||||
runs-on: macos-13
|
||||
runtime: node
|
||||
package-manager: yarn-v1
|
||||
- name: darwin-x64-deno
|
||||
runs-on: macos-13
|
||||
runtime: deno
|
||||
- name: darwin-x64-bun
|
||||
runs-on: macos-13
|
||||
runtime: bun
|
||||
|
||||
- name: win32-x64-node-npm
|
||||
runs-on: windows-2022
|
||||
runtime: node
|
||||
package-manager: npm
|
||||
- name: win32-x64-node-pnpm
|
||||
runs-on: windows-2022
|
||||
runtime: node
|
||||
package-manager: pnpm
|
||||
- name: win32-x64-node-yarn
|
||||
runs-on: windows-2022
|
||||
runtime: node
|
||||
package-manager: yarn
|
||||
- name: win32-x64-node-yarn-pnp
|
||||
runs-on: windows-2022
|
||||
runtime: node
|
||||
package-manager: yarn-pnp
|
||||
- name: win32-x64-node-yarn-v1
|
||||
runs-on: windows-2022
|
||||
runtime: node
|
||||
package-manager: yarn-v1
|
||||
- name: win32-x64-deno
|
||||
runs-on: windows-2022
|
||||
runtime: deno
|
||||
|
||||
steps:
|
||||
- name: Install Node.js
|
||||
if: ${{ matrix.runtime == 'node' }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
- name: Install pnpm
|
||||
if: ${{ matrix.package-manager == 'pnpm' }}
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 8
|
||||
- name: Install Deno
|
||||
if: ${{ matrix.runtime == 'deno' }}
|
||||
uses: denoland/setup-deno@v1
|
||||
with:
|
||||
deno-version: v1.x
|
||||
- name: Install Bun
|
||||
if: ${{ matrix.runtime == 'bun' }}
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Version
|
||||
id: version
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
core.setOutput('semver', context.ref.replace('refs/tags/v',''))
|
||||
- name: Create package.json
|
||||
uses: DamianReeves/write-file-action@v1.3
|
||||
with:
|
||||
path: package.json
|
||||
contents: |
|
||||
{
|
||||
"dependencies": {
|
||||
"sharp": "${{ steps.version.outputs.semver }}"
|
||||
},
|
||||
"type": "module"
|
||||
}
|
||||
- name: Create release.mjs
|
||||
uses: DamianReeves/write-file-action@v1.3
|
||||
with:
|
||||
path: release.mjs
|
||||
contents: |
|
||||
import { deepStrictEqual } from 'node:assert';
|
||||
import sharp from 'sharp';
|
||||
deepStrictEqual(['.jpg', '.jpeg', '.jpe', '.jfif'], sharp.format.jpeg.input.fileSuffix);
|
||||
|
||||
- name: Run with Node.js + npm
|
||||
if: ${{ matrix.package-manager == 'npm' }}
|
||||
run: |
|
||||
npm install --ignore-scripts
|
||||
node release.mjs
|
||||
|
||||
- name: Run with Node.js + pnpm
|
||||
if: ${{ matrix.package-manager == 'pnpm' }}
|
||||
run: |
|
||||
pnpm install --ignore-scripts
|
||||
node release.mjs
|
||||
|
||||
- name: Run with Node.js + yarn
|
||||
if: ${{ matrix.package-manager == 'yarn' }}
|
||||
run: |
|
||||
corepack enable
|
||||
yarn set version stable
|
||||
yarn config set enableImmutableInstalls false
|
||||
yarn config set enableScripts false
|
||||
yarn config set nodeLinker node-modules
|
||||
yarn install
|
||||
node release.mjs
|
||||
|
||||
- name: Run with Node.js + yarn pnp
|
||||
if: ${{ matrix.package-manager == 'yarn-pnp' }}
|
||||
run: |
|
||||
corepack enable
|
||||
yarn set version stable
|
||||
yarn config set enableImmutableInstalls false
|
||||
yarn config set enableScripts false
|
||||
yarn config set nodeLinker pnp
|
||||
yarn install
|
||||
yarn node release.mjs
|
||||
|
||||
- name: Run with Node.js + yarn v1
|
||||
if: ${{ matrix.package-manager == 'yarn-v1' }}
|
||||
run: |
|
||||
corepack enable
|
||||
yarn set version classic
|
||||
yarn install
|
||||
node release.mjs
|
||||
|
||||
- name: Run with Deno
|
||||
if: ${{ matrix.runtime == 'deno' }}
|
||||
run: deno run --allow-read --allow-ffi release.mjs
|
||||
|
||||
- name: Run with Bun
|
||||
if: ${{ matrix.runtime == 'bun' }}
|
||||
run: |
|
||||
bun install --ignore-scripts
|
||||
bun release.mjs
|
14
.gitignore
vendored
@ -1,18 +1,18 @@
|
||||
src/build
|
||||
src/node_modules
|
||||
build
|
||||
node_modules
|
||||
/coverage
|
||||
npm/*/*
|
||||
!npm/*/package.json
|
||||
test/bench/node_modules
|
||||
test/fixtures/output*
|
||||
test/fixtures/vips-properties.xml
|
||||
test/leak/libvips.supp
|
||||
test/saliency/report.json
|
||||
test/saliency/Image*
|
||||
test/saliency/[Uu]serData*
|
||||
!test/saliency/userData.js
|
||||
vendor
|
||||
.gitattributes
|
||||
.DS_Store
|
||||
.nyc_output
|
||||
.vscode/
|
||||
package-lock.json
|
||||
.idea
|
||||
.firebase
|
||||
.astro
|
||||
docs/dist
|
||||
|
4
.prebuildrc
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"include-regex": "(sharp-.+\\.node|libvips-cpp\\.dll)",
|
||||
"strip": true
|
||||
}
|
12
README.md
@ -1,15 +1,11 @@
|
||||
# sharp
|
||||
|
||||
<img src="https://sharp.pixelplumbing.com/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-API module
|
||||
The typical use case for this high speed Node.js module
|
||||
is to convert large images in common formats to
|
||||
smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions.
|
||||
|
||||
It can be used with all JavaScript runtimes
|
||||
that provide support for Node-API v9, including
|
||||
Node.js (^18.17.0 or >= 20.3.0), Deno and Bun.
|
||||
|
||||
Resizing an image is typically 4x-5x faster than using the
|
||||
quickest ImageMagick and GraphicsMagick settings
|
||||
due to its use of [libvips](https://github.com/libvips/libvips).
|
||||
@ -20,7 +16,7 @@ Lanczos resampling ensures quality is not sacrificed for speed.
|
||||
As well as image resizing, operations such as
|
||||
rotation, extraction, compositing and gamma correction are available.
|
||||
|
||||
Most modern macOS, Windows and Linux systems
|
||||
Most modern macOS, Windows and Linux systems running Node.js >= 14.15.0
|
||||
do not require any additional install or runtime dependencies.
|
||||
|
||||
## Documentation
|
||||
@ -102,6 +98,8 @@ readableStream
|
||||
A [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md)
|
||||
covers reporting bugs, requesting features and submitting code changes.
|
||||
|
||||
[](https://nodejs.org/dist/latest/docs/api/n-api.html#n_api_n_api_version_matrix)
|
||||
|
||||
## Licensing
|
||||
|
||||
Copyright 2013 Lovell Fuller and others.
|
||||
|
234
binding.gyp
Normal file
@ -0,0 +1,234 @@
|
||||
{
|
||||
'variables': {
|
||||
'vips_version': '<!(node -p "require(\'./lib/libvips\').minimumLibvipsVersion")',
|
||||
'platform_and_arch': '<!(node -p "require(\'./lib/platform\')()")',
|
||||
'sharp_vendor_dir': './vendor/<(vips_version)/<(platform_and_arch)'
|
||||
},
|
||||
'targets': [{
|
||||
'target_name': 'libvips-cpp',
|
||||
'conditions': [
|
||||
['OS == "win"', {
|
||||
# Build libvips C++ binding for Windows due to MSVC std library ABI changes
|
||||
'type': 'shared_library',
|
||||
'defines': [
|
||||
'VIPS_CPLUSPLUS_EXPORTS',
|
||||
'_ALLOW_KEYWORD_MACROS'
|
||||
],
|
||||
'sources': [
|
||||
'src/libvips/cplusplus/VConnection.cpp',
|
||||
'src/libvips/cplusplus/VError.cpp',
|
||||
'src/libvips/cplusplus/VImage.cpp',
|
||||
'src/libvips/cplusplus/VInterpolate.cpp',
|
||||
'src/libvips/cplusplus/VRegion.cpp'
|
||||
],
|
||||
'include_dirs': [
|
||||
'<(sharp_vendor_dir)/include',
|
||||
'<(sharp_vendor_dir)/include/glib-2.0',
|
||||
'<(sharp_vendor_dir)/lib/glib-2.0/include'
|
||||
],
|
||||
'link_settings': {
|
||||
'library_dirs': ['<(sharp_vendor_dir)/lib'],
|
||||
'libraries': [
|
||||
'libvips.lib',
|
||||
'libglib-2.0.lib',
|
||||
'libgobject-2.0.lib'
|
||||
],
|
||||
},
|
||||
'configurations': {
|
||||
'Release': {
|
||||
'msvs_settings': {
|
||||
'VCCLCompilerTool': {
|
||||
'ExceptionHandling': 1,
|
||||
'Optimization': 1,
|
||||
'WholeProgramOptimization': 'true'
|
||||
},
|
||||
'VCLibrarianTool': {
|
||||
'AdditionalOptions': [
|
||||
'/LTCG:INCREMENTAL'
|
||||
]
|
||||
},
|
||||
'VCLinkerTool': {
|
||||
'ImageHasSafeExceptionHandlers': 'false',
|
||||
'OptimizeReferences': 2,
|
||||
'EnableCOMDATFolding': 2,
|
||||
'LinkIncremental': 1,
|
||||
'AdditionalOptions': [
|
||||
'/LTCG:INCREMENTAL'
|
||||
]
|
||||
}
|
||||
},
|
||||
'msvs_disabled_warnings': [
|
||||
4275
|
||||
]
|
||||
}
|
||||
}
|
||||
}, {
|
||||
# Ignore this target for non-Windows
|
||||
'type': 'none'
|
||||
}]
|
||||
]
|
||||
}, {
|
||||
'target_name': 'sharp-<(platform_and_arch)',
|
||||
'defines': [
|
||||
'NAPI_VERSION=7'
|
||||
],
|
||||
'dependencies': [
|
||||
'<!(node -p "require(\'node-addon-api\').gyp")',
|
||||
'libvips-cpp'
|
||||
],
|
||||
'variables': {
|
||||
'runtime_link%': 'shared',
|
||||
'conditions': [
|
||||
['OS != "win"', {
|
||||
'pkg_config_path': '<!(node -p "require(\'./lib/libvips\').pkgConfigPath()")',
|
||||
'use_global_libvips': '<!(node -p "Boolean(require(\'./lib/libvips\').useGlobalLibvips()).toString()")'
|
||||
}, {
|
||||
'pkg_config_path': '',
|
||||
'use_global_libvips': ''
|
||||
}]
|
||||
]
|
||||
},
|
||||
'sources': [
|
||||
'src/common.cc',
|
||||
'src/metadata.cc',
|
||||
'src/stats.cc',
|
||||
'src/operations.cc',
|
||||
'src/pipeline.cc',
|
||||
'src/utilities.cc',
|
||||
'src/sharp.cc'
|
||||
],
|
||||
'include_dirs': [
|
||||
'<!(node -p "require(\'node-addon-api\').include_dir")',
|
||||
],
|
||||
'conditions': [
|
||||
['use_global_libvips == "true"', {
|
||||
# Use pkg-config for include and lib
|
||||
'include_dirs': ['<!@(PKG_CONFIG_PATH="<(pkg_config_path)" pkg-config --cflags-only-I vips-cpp vips glib-2.0 | sed s\/-I//g)'],
|
||||
'conditions': [
|
||||
['runtime_link == "static"', {
|
||||
'libraries': ['<!@(PKG_CONFIG_PATH="<(pkg_config_path)" pkg-config --libs --static vips-cpp)']
|
||||
}, {
|
||||
'libraries': ['<!@(PKG_CONFIG_PATH="<(pkg_config_path)" pkg-config --libs vips-cpp)']
|
||||
}],
|
||||
['OS == "linux"', {
|
||||
'defines': [
|
||||
# Inspect libvips-cpp.so to determine which C++11 ABI version was used and set _GLIBCXX_USE_CXX11_ABI accordingly. This is quite horrible.
|
||||
'_GLIBCXX_USE_CXX11_ABI=<!(if readelf -Ws "$(PKG_CONFIG_PATH="<(pkg_config_path)" pkg-config --variable libdir vips-cpp)/libvips-cpp.so" | c++filt | grep -qF __cxx11;then echo "1";else echo "0";fi)'
|
||||
]
|
||||
}]
|
||||
]
|
||||
}, {
|
||||
# Use pre-built libvips stored locally within node_modules
|
||||
'include_dirs': [
|
||||
'<(sharp_vendor_dir)/include',
|
||||
'<(sharp_vendor_dir)/include/glib-2.0',
|
||||
'<(sharp_vendor_dir)/lib/glib-2.0/include'
|
||||
],
|
||||
'conditions': [
|
||||
['OS == "win"', {
|
||||
'defines': [
|
||||
'_ALLOW_KEYWORD_MACROS',
|
||||
'_FILE_OFFSET_BITS=64'
|
||||
],
|
||||
'link_settings': {
|
||||
'library_dirs': ['<(sharp_vendor_dir)/lib'],
|
||||
'libraries': [
|
||||
'libvips.lib',
|
||||
'libglib-2.0.lib',
|
||||
'libgobject-2.0.lib'
|
||||
]
|
||||
}
|
||||
}],
|
||||
['OS == "mac"', {
|
||||
'link_settings': {
|
||||
'library_dirs': ['../<(sharp_vendor_dir)/lib'],
|
||||
'libraries': [
|
||||
'libvips-cpp.42.dylib'
|
||||
]
|
||||
},
|
||||
'xcode_settings': {
|
||||
'OTHER_LDFLAGS': [
|
||||
# Ensure runtime linking is relative to sharp.node
|
||||
'-Wl,-rpath,\'@loader_path/../../<(sharp_vendor_dir)/lib\''
|
||||
]
|
||||
}
|
||||
}],
|
||||
['OS == "linux"', {
|
||||
'defines': [
|
||||
'_GLIBCXX_USE_CXX11_ABI=1'
|
||||
],
|
||||
'link_settings': {
|
||||
'library_dirs': ['../<(sharp_vendor_dir)/lib'],
|
||||
'libraries': [
|
||||
'-l:libvips-cpp.so.42'
|
||||
],
|
||||
'ldflags': [
|
||||
# Ensure runtime linking is relative to sharp.node
|
||||
'-Wl,-s -Wl,--disable-new-dtags -Wl,-rpath=\'$$ORIGIN/../../<(sharp_vendor_dir)/lib\''
|
||||
]
|
||||
}
|
||||
}]
|
||||
]
|
||||
}]
|
||||
],
|
||||
'cflags_cc': [
|
||||
'-std=c++0x',
|
||||
'-fexceptions',
|
||||
'-Wall',
|
||||
'-Os'
|
||||
],
|
||||
'xcode_settings': {
|
||||
'CLANG_CXX_LANGUAGE_STANDARD': 'c++11',
|
||||
'MACOSX_DEPLOYMENT_TARGET': '10.13',
|
||||
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
|
||||
'GCC_ENABLE_CPP_RTTI': 'YES',
|
||||
'OTHER_CPLUSPLUSFLAGS': [
|
||||
'-fexceptions',
|
||||
'-Wall',
|
||||
'-Oz'
|
||||
]
|
||||
},
|
||||
'configurations': {
|
||||
'Release': {
|
||||
'conditions': [
|
||||
['OS == "linux"', {
|
||||
'cflags_cc': [
|
||||
'-Wno-cast-function-type'
|
||||
]
|
||||
}],
|
||||
['target_arch == "arm"', {
|
||||
'cflags_cc': [
|
||||
'-Wno-psabi'
|
||||
]
|
||||
}],
|
||||
['OS == "win"', {
|
||||
'msvs_settings': {
|
||||
'VCCLCompilerTool': {
|
||||
'ExceptionHandling': 1,
|
||||
'Optimization': 1,
|
||||
'WholeProgramOptimization': 'true'
|
||||
},
|
||||
'VCLibrarianTool': {
|
||||
'AdditionalOptions': [
|
||||
'/LTCG:INCREMENTAL'
|
||||
]
|
||||
},
|
||||
'VCLinkerTool': {
|
||||
'ImageHasSafeExceptionHandlers': 'false',
|
||||
'OptimizeReferences': 2,
|
||||
'EnableCOMDATFolding': 2,
|
||||
'LinkIncremental': 1,
|
||||
'AdditionalOptions': [
|
||||
'/LTCG:INCREMENTAL'
|
||||
]
|
||||
}
|
||||
},
|
||||
'msvs_disabled_warnings': [
|
||||
4275
|
||||
]
|
||||
}]
|
||||
]
|
||||
}
|
||||
},
|
||||
}]
|
||||
}
|
@ -1,17 +1,11 @@
|
||||
---
|
||||
title: "High performance Node.js image processing"
|
||||
---
|
||||
# sharp
|
||||
|
||||
<img src="/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-API module
|
||||
The typical use case for this high speed Node.js module
|
||||
is to convert large images in common formats to
|
||||
smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions.
|
||||
|
||||
It can be used with all JavaScript runtimes
|
||||
that provide support for Node-API v9, including
|
||||
Node.js >= 18.17.0, Deno and Bun.
|
||||
|
||||
Resizing an image is typically 4x-5x faster than using the
|
||||
quickest ImageMagick and GraphicsMagick settings
|
||||
due to its use of [libvips](https://github.com/libvips/libvips).
|
||||
@ -22,14 +16,10 @@ Lanczos resampling ensures quality is not sacrificed for speed.
|
||||
As well as image resizing, operations such as
|
||||
rotation, extraction, compositing and gamma correction are available.
|
||||
|
||||
Most modern macOS, Windows and Linux systems
|
||||
Most modern macOS, Windows and Linux systems running Node.js >= 14.15.0
|
||||
do not require any additional install or runtime dependencies.
|
||||
|
||||
```sh
|
||||
npm install sharp
|
||||
```
|
||||
|
||||
## Formats
|
||||
### Formats
|
||||
|
||||
This module supports reading JPEG, PNG, WebP, GIF, AVIF, TIFF and SVG images.
|
||||
|
||||
@ -43,7 +33,7 @@ Deep Zoom image pyramids can be generated,
|
||||
suitable for use with "slippy map" tile viewers like
|
||||
[OpenSeadragon](https://github.com/openseadragon/openseadragon).
|
||||
|
||||
## Fast
|
||||
### Fast
|
||||
|
||||
This module is powered by the blazingly fast
|
||||
[libvips](https://github.com/libvips/libvips) image processing library,
|
||||
@ -58,7 +48,7 @@ taking full advantage of multiple CPU cores and L1/L2/L3 cache.
|
||||
Everything remains non-blocking thanks to _libuv_,
|
||||
no child processes are spawned and Promises/async/await are supported.
|
||||
|
||||
## Optimal
|
||||
### Optimal
|
||||
|
||||
The features of `mozjpeg` and `pngquant` can be used
|
||||
to optimise the file size of JPEG and PNG images respectively,
|
||||
@ -77,12 +67,12 @@ The file size of animated GIF output is optimised
|
||||
without having to use separate command line tools such as
|
||||
[gifsicle](https://www.lcdf.org/gifsicle/).
|
||||
|
||||
## Contributing
|
||||
### Contributing
|
||||
|
||||
A [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md)
|
||||
covers reporting bugs, requesting features and submitting code changes.
|
||||
|
||||
## Licensing
|
||||
### Licensing
|
||||
|
||||
Copyright 2013 Lovell Fuller and others.
|
||||
|
@ -1,12 +1,5 @@
|
||||
---
|
||||
# This file was auto-generated from JSDoc in lib/channel.js
|
||||
title: Channel manipulation
|
||||
---
|
||||
|
||||
## removeAlpha
|
||||
> removeAlpha() ⇒ <code>Sharp</code>
|
||||
|
||||
Remove alpha channels, if any. This is a no-op if the image does not have an alpha channel.
|
||||
Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel.
|
||||
|
||||
See also [flatten](/api-operation#flatten).
|
||||
|
||||
@ -22,8 +15,6 @@ sharp('rgba.png')
|
||||
|
||||
|
||||
## ensureAlpha
|
||||
> ensureAlpha([alpha]) ⇒ <code>Sharp</code>
|
||||
|
||||
Ensure the output image has an alpha transparency channel.
|
||||
If missing, the added alpha channel will have the specified
|
||||
transparency level, defaulting to fully-opaque (1).
|
||||
@ -57,8 +48,6 @@ const rgba = await sharp(rgb)
|
||||
|
||||
|
||||
## extractChannel
|
||||
> extractChannel(channel) ⇒ <code>Sharp</code>
|
||||
|
||||
Extract a single channel from a multi-channel image.
|
||||
|
||||
|
||||
@ -89,8 +78,6 @@ const [red1, red2, ...] = await sharp(input)
|
||||
|
||||
|
||||
## joinChannel
|
||||
> joinChannel(images, options) ⇒ <code>Sharp</code>
|
||||
|
||||
Join one or more channels to the image.
|
||||
The meaning of the added channels depends on the output colourspace, set with `toColourspace()`.
|
||||
By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.
|
||||
@ -115,8 +102,6 @@ For raw pixel input, the `options` object should contain a `raw` attribute, whic
|
||||
|
||||
|
||||
## bandbool
|
||||
> bandbool(boolOp) ⇒ <code>Sharp</code>
|
||||
|
||||
Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image.
|
||||
|
||||
|
@ -1,12 +1,5 @@
|
||||
---
|
||||
# This file was auto-generated from JSDoc in lib/colour.js
|
||||
title: Colour manipulation
|
||||
---
|
||||
|
||||
## tint
|
||||
> tint(tint) ⇒ <code>Sharp</code>
|
||||
|
||||
Tint the image using the provided colour.
|
||||
Tint the image using the provided chroma while preserving the image luminance.
|
||||
An alpha channel may be present and will be unchanged by the operation.
|
||||
|
||||
|
||||
@ -17,7 +10,7 @@ An alpha channel may be present and will be unchanged by the operation.
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| tint | <code>string</code> \| <code>Object</code> | Parsed by the [color](https://www.npmjs.org/package/color) module. |
|
||||
| rgb | <code>string</code> \| <code>Object</code> | parsed by the [color](https://www.npmjs.org/package/color) module to extract chroma values. |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
@ -28,13 +21,11 @@ const output = await sharp(input)
|
||||
|
||||
|
||||
## greyscale
|
||||
> greyscale([greyscale]) ⇒ <code>Sharp</code>
|
||||
|
||||
Convert to 8-bit greyscale; 256 shades of grey.
|
||||
This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results.
|
||||
By default the output image will be web-friendly sRGB and contain three (identical) colour channels.
|
||||
By default the output image will be web-friendly sRGB and contain three (identical) color channels.
|
||||
This may be overridden by other sharp operations such as `toColourspace('b-w')`,
|
||||
which will produce an output image containing one colour channel.
|
||||
which will produce an output image containing one color channel.
|
||||
An alpha channel may be present, and will be unchanged by the operation.
|
||||
|
||||
|
||||
@ -50,8 +41,6 @@ const output = await sharp(input).greyscale().toBuffer();
|
||||
|
||||
|
||||
## grayscale
|
||||
> grayscale([grayscale]) ⇒ <code>Sharp</code>
|
||||
|
||||
Alternative spelling of `greyscale`.
|
||||
|
||||
|
||||
@ -63,13 +52,12 @@ Alternative spelling of `greyscale`.
|
||||
|
||||
|
||||
## pipelineColourspace
|
||||
> pipelineColourspace([colourspace]) ⇒ <code>Sharp</code>
|
||||
|
||||
Set the pipeline colourspace.
|
||||
|
||||
The input image will be converted to the provided colourspace at the start of the pipeline.
|
||||
All operations will use this colourspace before converting to the output colourspace,
|
||||
as defined by [toColourspace](#tocolourspace).
|
||||
All operations will use this colourspace before converting to the output colourspace, as defined by [toColourspace](#toColourspace).
|
||||
|
||||
This feature is experimental and has not yet been fully-tested with all operations.
|
||||
|
||||
|
||||
**Throws**:
|
||||
@ -93,8 +81,6 @@ await sharp(input)
|
||||
|
||||
|
||||
## pipelineColorspace
|
||||
> pipelineColorspace([colorspace]) ⇒ <code>Sharp</code>
|
||||
|
||||
Alternative spelling of `pipelineColourspace`.
|
||||
|
||||
|
||||
@ -110,8 +96,6 @@ Alternative spelling of `pipelineColourspace`.
|
||||
|
||||
|
||||
## toColourspace
|
||||
> toColourspace([colourspace]) ⇒ <code>Sharp</code>
|
||||
|
||||
Set the output colourspace.
|
||||
By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.
|
||||
|
||||
@ -135,8 +119,6 @@ await sharp(input)
|
||||
|
||||
|
||||
## toColorspace
|
||||
> toColorspace([colorspace]) ⇒ <code>Sharp</code>
|
||||
|
||||
Alternative spelling of `toColourspace`.
|
||||
|
||||
|
@ -1,18 +1,11 @@
|
||||
---
|
||||
# This file was auto-generated from JSDoc in lib/composite.js
|
||||
title: Compositing images
|
||||
---
|
||||
|
||||
## composite
|
||||
> composite(images) ⇒ <code>Sharp</code>
|
||||
|
||||
Composite image(s) over the processed (resized, extracted etc.) image.
|
||||
|
||||
The images to composite must be the same size or smaller than the processed image.
|
||||
If both `top` and `left` options are provided, they take precedence over `gravity`.
|
||||
|
||||
Other operations in the same processing pipeline (e.g. resize, rotate, flip,
|
||||
flop, extract) will always be applied to the input image before composition.
|
||||
Any resize or rotate operations in the same processing pipeline
|
||||
will always be applied to the input image before composition.
|
||||
|
||||
The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`,
|
||||
`dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`,
|
||||
@ -49,15 +42,14 @@ and https://www.cairographics.org/operators/
|
||||
| [images[].input.text.align] | <code>string</code> | <code>"'left'"</code> | text alignment (`'left'`, `'centre'`, `'center'`, `'right'`). |
|
||||
| [images[].input.text.justify] | <code>boolean</code> | <code>false</code> | set this to true to apply justification to the text. |
|
||||
| [images[].input.text.dpi] | <code>number</code> | <code>72</code> | the resolution (size) at which to render the text. Does not take effect if `height` is specified. |
|
||||
| [images[].input.text.rgba] | <code>boolean</code> | <code>false</code> | set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like `<span foreground="red">Red!</span>`. |
|
||||
| [images[].input.text.rgba] | <code>boolean</code> | <code>false</code> | set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`. |
|
||||
| [images[].input.text.spacing] | <code>number</code> | <code>0</code> | text line height in points. Will use the font line height if none is specified. |
|
||||
| [images[].autoOrient] | <code>Boolean</code> | <code>false</code> | set to true to use EXIF orientation data, if present, to orient the image. |
|
||||
| [images[].blend] | <code>String</code> | <code>'over'</code> | how to blend this image with the image below. |
|
||||
| [images[].gravity] | <code>String</code> | <code>'centre'</code> | gravity at which to place the overlay. |
|
||||
| [images[].top] | <code>Number</code> | | the pixel offset from the top edge. |
|
||||
| [images[].left] | <code>Number</code> | | the pixel offset from the left edge. |
|
||||
| [images[].tile] | <code>Boolean</code> | <code>false</code> | set to true to repeat the overlay image across the entire image with the given `gravity`. |
|
||||
| [images[].premultiplied] | <code>Boolean</code> | <code>false</code> | set to true to avoid premultiplying the image below. Equivalent to the `--premultiplied` vips option. |
|
||||
| [images[].premultiplied] | <code>Boolean</code> | <code>false</code> | set to true to avoid premultipling the image below. Equivalent to the `--premultiplied` vips option. |
|
||||
| [images[].density] | <code>Number</code> | <code>72</code> | number representing the DPI for vector overlay image. |
|
||||
| [images[].raw] | <code>Object</code> | | describes overlay when using raw pixel data. |
|
||||
| [images[].raw.width] | <code>Number</code> | | |
|
@ -1,18 +1,9 @@
|
||||
---
|
||||
# This file was auto-generated from JSDoc in lib/constructor.js
|
||||
title: Constructor
|
||||
---
|
||||
|
||||
## Sharp
|
||||
> Sharp
|
||||
|
||||
|
||||
**Emits**: <code>Sharp#event:info</code>, <code>Sharp#event:warning</code>
|
||||
<a name="new_Sharp_new"></a>
|
||||
|
||||
### new
|
||||
> new Sharp([input], [options])
|
||||
|
||||
Constructor factory to create an instance of `sharp`, to which further methods are chained.
|
||||
|
||||
JPEG, PNG, WebP, GIF, AVIF or TIFF format image data can be streamed out from this object.
|
||||
@ -22,10 +13,6 @@ 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.
|
||||
|
||||
When loading more than one page/frame of an animated image,
|
||||
these are combined as a vertically-stacked "toilet roll" image
|
||||
where the overall height is the `pageHeight` multiplied by the number of `pages`.
|
||||
|
||||
**Throws**:
|
||||
|
||||
- <code>Error</code> Invalid parameters
|
||||
@ -33,64 +20,45 @@ where the overall height is the `pageHeight` multiplied by the number of `pages`
|
||||
|
||||
| Param | Type | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| [input] | <code>Buffer</code> \| <code>ArrayBuffer</code> \| <code>Uint8Array</code> \| <code>Uint8ClampedArray</code> \| <code>Int8Array</code> \| <code>Uint16Array</code> \| <code>Int16Array</code> \| <code>Uint32Array</code> \| <code>Int32Array</code> \| <code>Float32Array</code> \| <code>Float64Array</code> \| <code>string</code> \| <code>Array</code> | | if present, can be a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or a TypedArray containing raw pixel image data, or a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. An array of inputs can be provided, and these will be joined together. JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. |
|
||||
| [input] | <code>Buffer</code> \| <code>ArrayBuffer</code> \| <code>Uint8Array</code> \| <code>Uint8ClampedArray</code> \| <code>Int8Array</code> \| <code>Uint16Array</code> \| <code>Int16Array</code> \| <code>Uint32Array</code> \| <code>Int32Array</code> \| <code>Float32Array</code> \| <code>Float64Array</code> \| <code>string</code> | | if present, can be a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or a TypedArray containing raw pixel image data, or a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. |
|
||||
| [options] | <code>Object</code> | | if present, is an Object with optional attributes. |
|
||||
| [options.failOn] | <code>string</code> | <code>"'warning'"</code> | When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort. |
|
||||
| [options.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), highers level imply lower levels, invalid metadata will always abort. |
|
||||
| [options.limitInputPixels] | <code>number</code> \| <code>boolean</code> | <code>268402689</code> | Do not process input images where the number of pixels (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted. An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). |
|
||||
| [options.unlimited] | <code>boolean</code> | <code>false</code> | Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). |
|
||||
| [options.autoOrient] | <code>boolean</code> | <code>false</code> | Set this to `true` to rotate/flip the image to match EXIF `Orientation`, if any. |
|
||||
| [options.sequentialRead] | <code>boolean</code> | <code>true</code> | Set this to `false` to use random access rather than sequential read. Some operations will do this automatically. |
|
||||
| [options.density] | <code>number</code> | <code>72</code> | number representing the DPI for vector images in the range 1 to 100000. |
|
||||
| [options.ignoreIcc] | <code>number</code> | <code>false</code> | should the embedded ICC profile, if any, be ignored. |
|
||||
| [options.pages] | <code>number</code> | <code>1</code> | Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages. |
|
||||
| [options.page] | <code>number</code> | <code>0</code> | Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based. |
|
||||
| [options.subifd] | <code>number</code> | <code>-1</code> | subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. |
|
||||
| [options.level] | <code>number</code> | <code>0</code> | level to extract from a multi-level input (OpenSlide), zero based. |
|
||||
| [options.animated] | <code>boolean</code> | <code>false</code> | Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`. |
|
||||
| [options.raw] | <code>Object</code> | | describes raw pixel input image data. See `raw()` for pixel ordering. |
|
||||
| [options.raw.width] | <code>number</code> | | integral number of pixels wide. |
|
||||
| [options.raw.height] | <code>number</code> | | integral number of pixels high. |
|
||||
| [options.raw.channels] | <code>number</code> | | integral number of channels, between 1 and 4. |
|
||||
| [options.raw.premultiplied] | <code>boolean</code> | | specifies that the raw input has already been premultiplied, set to `true` to avoid sharp premultiplying the image. (optional, default `false`) |
|
||||
| [options.raw.pageHeight] | <code>number</code> | | The pixel height of each page/frame for animated images, must be an integral factor of `raw.height`. |
|
||||
| [options.create] | <code>Object</code> | | describes a new image to be created. |
|
||||
| [options.create.width] | <code>number</code> | | integral number of pixels wide. |
|
||||
| [options.create.height] | <code>number</code> | | integral number of pixels high. |
|
||||
| [options.create.channels] | <code>number</code> | | integral number of channels, either 3 (RGB) or 4 (RGBA). |
|
||||
| [options.create.background] | <code>string</code> \| <code>Object</code> | | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |
|
||||
| [options.create.pageHeight] | <code>number</code> | | The pixel height of each page/frame for animated images, must be an integral factor of `create.height`. |
|
||||
| [options.create.noise] | <code>Object</code> | | describes a noise to be created. |
|
||||
| [options.create.noise.type] | <code>string</code> | | type of generated noise, currently only `gaussian` is supported. |
|
||||
| [options.create.noise.mean] | <code>number</code> | <code>128</code> | Mean value of pixels in the generated noise. |
|
||||
| [options.create.noise.sigma] | <code>number</code> | <code>30</code> | Standard deviation of pixel values in the generated noise. |
|
||||
| [options.create.noise.mean] | <code>number</code> | | mean of pixels in generated noise. |
|
||||
| [options.create.noise.sigma] | <code>number</code> | | standard deviation of pixels in generated noise. |
|
||||
| [options.text] | <code>Object</code> | | describes a new text image to be created. |
|
||||
| [options.text.text] | <code>string</code> | | text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`. |
|
||||
| [options.text.font] | <code>string</code> | | font name to render with. |
|
||||
| [options.text.fontfile] | <code>string</code> | | absolute filesystem path to a font file that can be used by `font`. |
|
||||
| [options.text.width] | <code>number</code> | <code>0</code> | Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. |
|
||||
| [options.text.height] | <code>number</code> | <code>0</code> | Maximum integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. |
|
||||
| [options.text.align] | <code>string</code> | <code>"'left'"</code> | Alignment style for multi-line text (`'left'`, `'centre'`, `'center'`, `'right'`). |
|
||||
| [options.text.width] | <code>number</code> | <code>0</code> | integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. |
|
||||
| [options.text.height] | <code>number</code> | <code>0</code> | integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. |
|
||||
| [options.text.align] | <code>string</code> | <code>"'left'"</code> | text alignment (`'left'`, `'centre'`, `'center'`, `'right'`). |
|
||||
| [options.text.justify] | <code>boolean</code> | <code>false</code> | set this to true to apply justification to the text. |
|
||||
| [options.text.dpi] | <code>number</code> | <code>72</code> | the resolution (size) at which to render the text. Does not take effect if `height` is specified. |
|
||||
| [options.text.rgba] | <code>boolean</code> | <code>false</code> | set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`. |
|
||||
| [options.text.spacing] | <code>number</code> | <code>0</code> | text line height in points. Will use the font line height if none is specified. |
|
||||
| [options.text.wrap] | <code>string</code> | <code>"'word'"</code> | word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'. |
|
||||
| [options.join] | <code>Object</code> | | describes how an array of input images should be joined. |
|
||||
| [options.join.across] | <code>number</code> | <code>1</code> | number of images to join horizontally. |
|
||||
| [options.join.animated] | <code>boolean</code> | <code>false</code> | set this to `true` to join the images as an animated image. |
|
||||
| [options.join.shim] | <code>number</code> | <code>0</code> | number of pixels to insert between joined images. |
|
||||
| [options.join.background] | <code>string</code> \| <code>Object</code> | | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |
|
||||
| [options.join.halign] | <code>string</code> | <code>"'left'"</code> | horizontal alignment style for images joined horizontally (`'left'`, `'centre'`, `'center'`, `'right'`). |
|
||||
| [options.join.valign] | <code>string</code> | <code>"'top'"</code> | vertical alignment style for images joined vertically (`'top'`, `'centre'`, `'center'`, `'bottom'`). |
|
||||
| [options.tiff] | <code>Object</code> | | Describes TIFF specific options. |
|
||||
| [options.tiff.subifd] | <code>number</code> | <code>-1</code> | Sub Image File Directory to extract for OME-TIFF, defaults to main image. |
|
||||
| [options.svg] | <code>Object</code> | | Describes SVG specific options. |
|
||||
| [options.svg.stylesheet] | <code>string</code> | | Custom CSS for SVG input, applied with a User Origin during the CSS cascade. |
|
||||
| [options.svg.highBitdepth] | <code>boolean</code> | <code>false</code> | Set to `true` to render SVG input at 32-bits per channel (128-bit) instead of 8-bits per channel (32-bit) RGBA. |
|
||||
| [options.pdf] | <code>Object</code> | | Describes PDF specific options. Requires the use of a globally-installed libvips compiled with support for PDFium, Poppler, ImageMagick or GraphicsMagick. |
|
||||
| [options.pdf.background] | <code>string</code> \| <code>Object</code> | | Background colour to use when PDF is partially transparent. Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |
|
||||
| [options.openSlide] | <code>Object</code> | | Describes OpenSlide specific options. Requires the use of a globally-installed libvips compiled with support for OpenSlide. |
|
||||
| [options.openSlide.level] | <code>number</code> | <code>0</code> | Level to extract from a multi-level input, zero based. |
|
||||
| [options.jp2] | <code>Object</code> | | Describes JPEG 2000 specific options. Requires the use of a globally-installed libvips compiled with support for OpenJPEG. |
|
||||
| [options.jp2.oneshot] | <code>boolean</code> | <code>false</code> | Set to `true` to decode tiled JPEG 2000 images in a single operation, improving compatibility. |
|
||||
| [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'. |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
@ -103,22 +71,20 @@ sharp('input.jpg')
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
// Read image data from remote URL,
|
||||
// Read image data from readableStream,
|
||||
// resize to 300 pixels wide,
|
||||
// emit an 'info' event with calculated dimensions
|
||||
// and finally write image data to writableStream
|
||||
const { body } = fetch('https://...');
|
||||
const readableStream = Readable.fromWeb(body);
|
||||
const transformer = sharp()
|
||||
var transformer = sharp()
|
||||
.resize(300)
|
||||
.on('info', ({ height }) => {
|
||||
console.log(`Image height is ${height}`);
|
||||
.on('info', function(info) {
|
||||
console.log('Image height is ' + info.height);
|
||||
});
|
||||
readableStream.pipe(transformer).pipe(writableStream);
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
// Create a blank 300x200 PNG image of semi-translucent red pixels
|
||||
// Create a blank 300x200 PNG image of semi-transluent red pixels
|
||||
sharp({
|
||||
create: {
|
||||
width: 300,
|
||||
@ -190,27 +156,9 @@ await sharp({
|
||||
}
|
||||
}).toFile('text_rgba.png');
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
// Join four input images as a 2x2 grid with a 4 pixel gutter
|
||||
const data = await sharp(
|
||||
[image1, image2, image3, image4],
|
||||
{ join: { across: 2, shim: 4 } }
|
||||
).toBuffer();
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
// Generate a two-frame animated image from emoji
|
||||
const images = ['😀', '😛'].map(text => ({
|
||||
text: { text, width: 64, height: 64, channels: 4, rgba: true }
|
||||
}));
|
||||
await sharp(images, { join: { animated: true } }).toFile('out.gif');
|
||||
```
|
||||
|
||||
|
||||
## clone
|
||||
> clone() ⇒ [<code>Sharp</code>](#Sharp)
|
||||
|
||||
Take a "snapshot" of the Sharp instance, returning a new instance.
|
||||
Cloned instances inherit the input of their parent instance.
|
||||
This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream.
|
@ -1,11 +1,4 @@
|
||||
---
|
||||
# This file was auto-generated from JSDoc in lib/input.js
|
||||
title: Input metadata
|
||||
---
|
||||
|
||||
## metadata
|
||||
> metadata([callback]) ⇒ <code>Promise.<Object></code> \| <code>Sharp</code>
|
||||
|
||||
Fast access to (uncached) image metadata without decoding any compressed pixel data.
|
||||
|
||||
This is read from the header of the input image.
|
||||
@ -27,8 +20,6 @@ A `Promise` is returned when `callback` is not provided.
|
||||
- `density`: Number of pixels per inch (DPI), if present
|
||||
- `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK
|
||||
- `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan
|
||||
- `isPalette`: Boolean indicating whether the image is palette-based (GIF, PNG).
|
||||
- `bitsPerSample`: Number of bits per sample for each channel (GIF, PNG, HEIF).
|
||||
- `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP
|
||||
- `pageHeight`: Number of pixels high each page in a multi-page image will be.
|
||||
- `loop`: Number of times to loop an animated image, zero refers to a continuous loop.
|
||||
@ -36,7 +27,7 @@ A `Promise` is returned when `callback` is not provided.
|
||||
- `pagePrimary`: Number of the primary page in a HEIF image
|
||||
- `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide
|
||||
- `subifds`: Number of Sub Image File Directories in an OME-TIFF image
|
||||
- `background`: Default background colour, if present, for PNG (bKGD) and GIF images
|
||||
- `background`: Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value
|
||||
- `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC)
|
||||
- `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present
|
||||
- `hasProfile`: Boolean indicating the presence of an embedded ICC profile
|
||||
@ -48,7 +39,6 @@ A `Promise` is returned when `callback` is not provided.
|
||||
- `xmp`: Buffer containing raw XMP data, if present
|
||||
- `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present
|
||||
- `formatMagick`: String containing format for images loaded via *magick
|
||||
- `comments`: Array of keyword/text pairs representing PNG text blocks, if present.
|
||||
|
||||
|
||||
|
||||
@ -77,15 +67,19 @@ image
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
// Get dimensions taking EXIF Orientation into account.
|
||||
const { autoOrient } = await sharp(input).metadata();
|
||||
const { width, height } = autoOrient;
|
||||
// Based on EXIF rotation metadata, get the right-side-up width and height:
|
||||
|
||||
const size = getNormalSize(await sharp(input).metadata());
|
||||
|
||||
function getNormalSize({ width, height, orientation }) {
|
||||
return (orientation || 0) >= 5
|
||||
? { width: height, height: width }
|
||||
: { width, height };
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## stats
|
||||
> stats([callback]) ⇒ <code>Promise.<Object></code>
|
||||
|
||||
Access to pixel-derived image statistics for every channel in the image.
|
||||
A `Promise` is returned when `callback` is not provided.
|
||||
|
@ -1,26 +1,20 @@
|
||||
---
|
||||
# This file was auto-generated from JSDoc in lib/operation.js
|
||||
title: Image operations
|
||||
---
|
||||
|
||||
## rotate
|
||||
> rotate([angle], [options]) ⇒ <code>Sharp</code>
|
||||
Rotate the output image by either an explicit angle
|
||||
or auto-orient based on the EXIF `Orientation` tag.
|
||||
|
||||
Rotate the output image.
|
||||
|
||||
The provided angle is converted to a valid positive degree rotation.
|
||||
For example, `-450` will produce a 270 degree rotation.
|
||||
If an angle is provided, it is converted to a valid positive degree rotation.
|
||||
For example, `-450` will produce a 270deg rotation.
|
||||
|
||||
When rotating by an angle other than a multiple of 90,
|
||||
the background colour can be provided with the `background` option.
|
||||
|
||||
For backwards compatibility, if no angle is provided, `.autoOrient()` will be called.
|
||||
If no angle is provided, it is determined from the EXIF data.
|
||||
Mirroring is supported and may infer the use of a flip operation.
|
||||
|
||||
Only one rotation can occur per pipeline (aside from an initial call without
|
||||
arguments to orient via EXIF data). Previous calls to `rotate` in the same
|
||||
pipeline will be ignored.
|
||||
The use of `rotate` implies the removal of the EXIF `Orientation` tag, if any.
|
||||
|
||||
Multi-page images can only be rotated by 180 degrees.
|
||||
Only one rotation can occur per pipeline.
|
||||
Previous calls to `rotate` in the same pipeline will be ignored.
|
||||
|
||||
Method order is important when rotating, resizing and/or extracting regions,
|
||||
for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.
|
||||
@ -37,6 +31,18 @@ for example `.rotate(x).extract(y)` will produce a different result to `.extract
|
||||
| [options] | <code>Object</code> | | if present, is an Object with optional attributes. |
|
||||
| [options.background] | <code>string</code> \| <code>Object</code> | <code>"\"#000000\""</code> | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
const pipeline = sharp()
|
||||
.rotate()
|
||||
.resize(null, 200)
|
||||
.toBuffer(function (err, outputBuffer, info) {
|
||||
// outputBuffer contains 200px high JPEG image data,
|
||||
// auto-rotated using EXIF Orientation tag
|
||||
// info.width and info.height contain the dimensions of the resized image
|
||||
});
|
||||
readableStream.pipe(pipeline);
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
const rotateThenResize = await sharp(input)
|
||||
@ -50,41 +56,9 @@ const resizeThenRotate = await sharp(input)
|
||||
```
|
||||
|
||||
|
||||
## autoOrient
|
||||
> autoOrient() ⇒ <code>Sharp</code>
|
||||
|
||||
Auto-orient based on the EXIF `Orientation` tag, then remove the tag.
|
||||
Mirroring is supported and may infer the use of a flip operation.
|
||||
|
||||
Previous or subsequent use of `rotate(angle)` and either `flip()` or `flop()`
|
||||
will logically occur after auto-orientation, regardless of call order.
|
||||
|
||||
|
||||
**Example**
|
||||
```js
|
||||
const output = await sharp(input).autoOrient().toBuffer();
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
const pipeline = sharp()
|
||||
.autoOrient()
|
||||
.resize(null, 200)
|
||||
.toBuffer(function (err, outputBuffer, info) {
|
||||
// outputBuffer contains 200px high JPEG image data,
|
||||
// auto-oriented using EXIF Orientation tag
|
||||
// info.width and info.height contain the dimensions of the resized image
|
||||
});
|
||||
readableStream.pipe(pipeline);
|
||||
```
|
||||
|
||||
|
||||
## flip
|
||||
> flip([flip]) ⇒ <code>Sharp</code>
|
||||
|
||||
Mirror the image vertically (up-down) about the x-axis.
|
||||
This always occurs before rotation, if any.
|
||||
|
||||
This operation does not work correctly with multi-page images.
|
||||
Flip the image about the vertical Y axis. This always occurs before rotation, if any.
|
||||
The use of `flip` implies the removal of the EXIF `Orientation` tag, if any.
|
||||
|
||||
|
||||
|
||||
@ -99,10 +73,8 @@ const output = await sharp(input).flip().toBuffer();
|
||||
|
||||
|
||||
## flop
|
||||
> flop([flop]) ⇒ <code>Sharp</code>
|
||||
|
||||
Mirror the image horizontally (left-right) about the y-axis.
|
||||
This always occurs before rotation, if any.
|
||||
Flop the image about the horizontal X axis. This always occurs before rotation, if any.
|
||||
The use of `flop` implies the removal of the EXIF `Orientation` tag, if any.
|
||||
|
||||
|
||||
|
||||
@ -117,13 +89,11 @@ const output = await sharp(input).flop().toBuffer();
|
||||
|
||||
|
||||
## affine
|
||||
> affine(matrix, [options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.
|
||||
|
||||
You must provide an array of length 4 or a 2x2 affine transformation matrix.
|
||||
By default, new pixels are filled with a black background. You can provide a background colour with the `background` option.
|
||||
A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`.
|
||||
By default, new pixels are filled with a black background. You can provide a background color with the `background` option.
|
||||
A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolator` Object e.g. `sharp.interpolator.nohalo`.
|
||||
|
||||
In the case of a 2x2 matrix, the transform is:
|
||||
- X = `matrix[0, 0]` \* (x + `idx`) + `matrix[0, 1]` \* (y + `idy`) + `odx`
|
||||
@ -157,7 +127,7 @@ where:
|
||||
const pipeline = sharp()
|
||||
.affine([[1, 0.3], [0.1, 0.7]], {
|
||||
background: 'white',
|
||||
interpolator: sharp.interpolators.nohalo
|
||||
interpolate: sharp.interpolators.nohalo
|
||||
})
|
||||
.toBuffer((err, outputBuffer, info) => {
|
||||
// outputBuffer contains the transformed image
|
||||
@ -170,8 +140,6 @@ inputStream
|
||||
|
||||
|
||||
## sharpen
|
||||
> sharpen([options], [flat], [jagged]) ⇒ <code>Sharp</code>
|
||||
|
||||
Sharpen the image.
|
||||
|
||||
When used without parameters, performs a fast, mild sharpen of the output image.
|
||||
@ -223,8 +191,6 @@ const data = await sharp(input)
|
||||
|
||||
|
||||
## median
|
||||
> median([size]) ⇒ <code>Sharp</code>
|
||||
|
||||
Apply median filter.
|
||||
When used without parameters the default window is 3x3.
|
||||
|
||||
@ -249,8 +215,6 @@ const output = await sharp(input).median(5).toBuffer();
|
||||
|
||||
|
||||
## blur
|
||||
> blur([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Blur the image.
|
||||
|
||||
When used without parameters, performs a fast 3x3 box blur (equivalent to a box linear filter).
|
||||
@ -263,12 +227,9 @@ When a `sigma` is provided, performs a slower, more accurate Gaussian blur.
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
|
||||
| Param | Type | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| [options] | <code>Object</code> \| <code>number</code> \| <code>Boolean</code> | | |
|
||||
| [options.sigma] | <code>number</code> | | a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. |
|
||||
| [options.precision] | <code>string</code> | <code>"'integer'"</code> | How accurate the operation should be, one of: integer, float, approximate. |
|
||||
| [options.minAmplitude] | <code>number</code> | <code>0.2</code> | A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask. |
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| [sigma] | <code>number</code> | a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
@ -284,55 +245,7 @@ const gaussianBlurred = await sharp(input)
|
||||
```
|
||||
|
||||
|
||||
## dilate
|
||||
> dilate([width]) ⇒ <code>Sharp</code>
|
||||
|
||||
Expand foreground objects using the dilate morphological operator.
|
||||
|
||||
|
||||
**Throws**:
|
||||
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
|
||||
| Param | Type | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| [width] | <code>Number</code> | <code>1</code> | dilation width in pixels. |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
const output = await sharp(input)
|
||||
.dilate()
|
||||
.toBuffer();
|
||||
```
|
||||
|
||||
|
||||
## erode
|
||||
> erode([width]) ⇒ <code>Sharp</code>
|
||||
|
||||
Shrink foreground objects using the erode morphological operator.
|
||||
|
||||
|
||||
**Throws**:
|
||||
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
|
||||
| Param | Type | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| [width] | <code>Number</code> | <code>1</code> | erosion width in pixels. |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
const output = await sharp(input)
|
||||
.erode()
|
||||
.toBuffer();
|
||||
```
|
||||
|
||||
|
||||
## flatten
|
||||
> flatten([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Merge alpha transparency channel, if any, with a background, then remove the alpha channel.
|
||||
|
||||
See also [removeAlpha](/api-channel#removealpha).
|
||||
@ -352,36 +265,7 @@ await sharp(rgbaInput)
|
||||
```
|
||||
|
||||
|
||||
## unflatten
|
||||
> unflatten()
|
||||
|
||||
Ensure the image has an alpha channel
|
||||
with all white pixel values made fully transparent.
|
||||
|
||||
Existing alpha channel values for non-white pixels remain unchanged.
|
||||
|
||||
This feature is experimental and the API may change.
|
||||
|
||||
|
||||
**Since**: 0.32.1
|
||||
**Example**
|
||||
```js
|
||||
await sharp(rgbInput)
|
||||
.unflatten()
|
||||
.toBuffer();
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
await sharp(rgbInput)
|
||||
.threshold(128, { grayscale: false }) // converter bright pixels to white
|
||||
.unflatten()
|
||||
.toBuffer();
|
||||
```
|
||||
|
||||
|
||||
## gamma
|
||||
> gamma([gamma], [gammaOut]) ⇒ <code>Sharp</code>
|
||||
|
||||
Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of `1/gamma`
|
||||
then increasing the encoding (brighten) post-resize at a factor of `gamma`.
|
||||
This can improve the perceived brightness of a resized image in non-linear colour spaces.
|
||||
@ -404,8 +288,6 @@ Supply a second argument to use a different output gamma value, otherwise the fi
|
||||
|
||||
|
||||
## negate
|
||||
> negate([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Produce the "negative" of the image.
|
||||
|
||||
|
||||
@ -430,8 +312,6 @@ const output = await sharp(input)
|
||||
|
||||
|
||||
## normalise
|
||||
> normalise([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Enhance output image contrast by stretching its luminance to cover a full dynamic range.
|
||||
|
||||
Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes.
|
||||
@ -462,8 +342,6 @@ const output = await sharp(input)
|
||||
|
||||
|
||||
## normalize
|
||||
> normalize([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Alternative spelling of normalise.
|
||||
|
||||
|
||||
@ -483,8 +361,6 @@ const output = await sharp(input)
|
||||
|
||||
|
||||
## clahe
|
||||
> clahe(options) ⇒ <code>Sharp</code>
|
||||
|
||||
Perform contrast limiting adaptive histogram equalization
|
||||
[CLAHE](https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE).
|
||||
|
||||
@ -516,8 +392,6 @@ const output = await sharp(input)
|
||||
|
||||
|
||||
## convolve
|
||||
> convolve(kernel) ⇒ <code>Sharp</code>
|
||||
|
||||
Convolve the image with the specified kernel.
|
||||
|
||||
|
||||
@ -552,8 +426,6 @@ sharp(input)
|
||||
|
||||
|
||||
## threshold
|
||||
> threshold([threshold], [options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0.
|
||||
|
||||
|
||||
@ -572,8 +444,6 @@ Any pixel value greater than or equal to the threshold value will be set to 255,
|
||||
|
||||
|
||||
## boolean
|
||||
> boolean(operand, operator, [options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Perform a bitwise boolean operation with operand image.
|
||||
|
||||
This operation creates an output image where each pixel is the result of
|
||||
@ -598,8 +468,6 @@ the selected bitwise boolean `operation` between the corresponding pixels of the
|
||||
|
||||
|
||||
## linear
|
||||
> linear([a], [b]) ⇒ <code>Sharp</code>
|
||||
|
||||
Apply the linear formula `a` * input + `b` to the image to adjust image levels.
|
||||
|
||||
When a single number is provided, it will be used for all image channels.
|
||||
@ -634,9 +502,7 @@ await sharp(rgbInput)
|
||||
|
||||
|
||||
## recomb
|
||||
> recomb(inputMatrix) ⇒ <code>Sharp</code>
|
||||
|
||||
Recombine the image with the specified matrix.
|
||||
Recomb the image with the specified matrix.
|
||||
|
||||
|
||||
**Throws**:
|
||||
@ -647,7 +513,7 @@ Recombine the image with the specified matrix.
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| inputMatrix | <code>Array.<Array.<number>></code> | 3x3 or 4x4 Recombination matrix |
|
||||
| inputMatrix | <code>Array.<Array.<number>></code> | 3x3 Recombination matrix |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
@ -659,15 +525,13 @@ sharp(input)
|
||||
])
|
||||
.raw()
|
||||
.toBuffer(function(err, data, info) {
|
||||
// data contains the raw pixel data after applying the matrix
|
||||
// data contains the raw pixel data after applying the recomb
|
||||
// With this example input, a sepia filter has been applied
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
## modulate
|
||||
> modulate([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Transforms the image using brightness, saturation, hue rotation, and lightness.
|
||||
Brightness and lightness both operate on luminance, with the difference being that
|
||||
brightness is multiplicative whereas lightness is additive.
|
||||
@ -712,7 +576,7 @@ const output = await sharp(input)
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
// decrease brightness and saturation while also hue-rotating by 90 degrees
|
||||
// decreate brightness and saturation while also hue-rotating by 90 degrees
|
||||
const output = await sharp(input)
|
||||
.modulate({
|
||||
brightness: 0.5,
|
@ -1,11 +1,4 @@
|
||||
---
|
||||
# This file was auto-generated from JSDoc in lib/output.js
|
||||
title: Output options
|
||||
---
|
||||
|
||||
## toFile
|
||||
> toFile(fileOut, [callback]) ⇒ <code>Promise.<Object></code>
|
||||
|
||||
Write output image data to a file.
|
||||
|
||||
If an explicit output format is not selected, it will be inferred from the extension,
|
||||
@ -13,7 +6,7 @@ with JPEG, PNG, WebP, AVIF, TIFF, GIF, DZI, and libvips' V format supported.
|
||||
Note that raw pixel data is only supported for buffer output.
|
||||
|
||||
By default all metadata will be removed, which includes EXIF-based orientation.
|
||||
See [withMetadata](#withmetadata) for control over this.
|
||||
See [withMetadata](#withMetadata) for control over this.
|
||||
|
||||
The caller is responsible for ensuring directory structures and permissions exist.
|
||||
|
||||
@ -29,7 +22,7 @@ A `Promise` is returned when `callback` is not provided.
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| fileOut | <code>string</code> | the path to write the image data to. |
|
||||
| [callback] | <code>function</code> | called on completion with two arguments `(err, info)`. `info` contains the output image `format`, `size` (bytes), `width`, `height`, `channels` and `premultiplied` (indicating if premultiplication was used). When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region. Animated output will also contain `pageHeight` and `pages`. May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. |
|
||||
| [callback] | <code>function</code> | called on completion with two arguments `(err, info)`. `info` contains the output image `format`, `size` (bytes), `width`, `height`, `channels` and `premultiplied` (indicating if premultiplication was used). When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region. May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
@ -46,17 +39,15 @@ sharp(input)
|
||||
|
||||
|
||||
## toBuffer
|
||||
> toBuffer([options], [callback]) ⇒ <code>Promise.<Buffer></code>
|
||||
|
||||
Write output to a Buffer.
|
||||
JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.
|
||||
|
||||
Use [toFormat](#toformat) or one of the format-specific functions such as [jpeg](#jpeg), [png](#png) etc. to set the output format.
|
||||
Use [toFormat](#toFormat) or one of the format-specific functions such as [jpeg](#jpeg), [png](#png) etc. to set the output format.
|
||||
|
||||
If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output.
|
||||
|
||||
By default all metadata will be removed, which includes EXIF-based orientation.
|
||||
See [withMetadata](#withmetadata) for control over this.
|
||||
See [withMetadata](#withMetadata) for control over this.
|
||||
|
||||
`callback`, if present, gets three arguments `(err, data, info)` where:
|
||||
- `err` is an error, if any.
|
||||
@ -64,7 +55,6 @@ See [withMetadata](#withmetadata) for control over this.
|
||||
- `info` contains the output image `format`, `size` (bytes), `width`, `height`,
|
||||
`channels` and `premultiplied` (indicating if premultiplication was used).
|
||||
When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
|
||||
Animated output will also contain `pageHeight` and `pages`.
|
||||
May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.
|
||||
|
||||
A `Promise` is returned when `callback` is not provided.
|
||||
@ -117,225 +107,48 @@ await sharp(pixelArray, { raw: { width, height, channels } })
|
||||
```
|
||||
|
||||
|
||||
## keepExif
|
||||
> keepExif() ⇒ <code>Sharp</code>
|
||||
## withMetadata
|
||||
Include all metadata (EXIF, XMP, IPTC) from the input image in the output image.
|
||||
This will also convert to and add a web-friendly sRGB ICC profile unless a custom
|
||||
output profile is provided.
|
||||
|
||||
Keep all EXIF metadata from the input image in the output image.
|
||||
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.
|
||||
|
||||
|
||||
**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? |
|
||||
| [options.orientation] | <code>number</code> | | value between 1 and 8, used to update the EXIF `Orientation` tag. |
|
||||
| [options.icc] | <code>string</code> | <code>"'srgb'"</code> | Filesystem path to output ICC profile, relative to `process.cwd()`, defaults to built-in sRGB. |
|
||||
| [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**
|
||||
```js
|
||||
const outputWithP3 = await sharp(input)
|
||||
.withIccProfile('p3')
|
||||
.toBuffer();
|
||||
```
|
||||
|
||||
|
||||
## keepXmp
|
||||
> keepXmp() ⇒ <code>Sharp</code>
|
||||
|
||||
Keep XMP metadata from the input image in the output image.
|
||||
|
||||
|
||||
**Since**: 0.34.3
|
||||
**Example**
|
||||
```js
|
||||
const outputWithXmp = await sharp(inputWithXmp)
|
||||
.keepXmp()
|
||||
.toBuffer();
|
||||
```
|
||||
|
||||
|
||||
## withXmp
|
||||
> withXmp(xmp) ⇒ <code>Sharp</code>
|
||||
|
||||
Set XMP metadata in the output image.
|
||||
|
||||
Supported by PNG, JPEG, WebP, and TIFF output.
|
||||
|
||||
|
||||
**Throws**:
|
||||
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
**Since**: 0.34.3
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| xmp | <code>string</code> | String containing XMP metadata to be embedded in the output image. |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
const xmpString = `
|
||||
<?xml version="1.0"?>
|
||||
<x:xmpmeta xmlns:x="adobe:ns:meta/">
|
||||
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||
<dc:creator><rdf:Seq><rdf:li>John Doe</rdf:li></rdf:Seq></dc:creator>
|
||||
</rdf:Description>
|
||||
</rdf:RDF>
|
||||
</x:xmpmeta>`;
|
||||
|
||||
const data = await sharp(input)
|
||||
.withXmp(xmpString)
|
||||
.toBuffer();
|
||||
```
|
||||
|
||||
|
||||
## keepMetadata
|
||||
> keepMetadata() ⇒ <code>Sharp</code>
|
||||
|
||||
Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image.
|
||||
|
||||
The default behaviour, when `keepMetadata` is not used, is to convert to the device-independent
|
||||
sRGB colour space and strip all metadata, including the removal of any ICC profile.
|
||||
|
||||
|
||||
**Since**: 0.33.0
|
||||
**Example**
|
||||
```js
|
||||
const outputWithMetadata = await sharp(inputWithMetadata)
|
||||
.keepMetadata()
|
||||
.toBuffer();
|
||||
```
|
||||
|
||||
|
||||
## withMetadata
|
||||
> withMetadata([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Keep most metadata (EXIF, XMP, IPTC) from the input image in the output image.
|
||||
|
||||
This will also convert to and add a web-friendly sRGB ICC profile if appropriate.
|
||||
|
||||
Allows orientation and density to be set or updated.
|
||||
|
||||
|
||||
**Throws**:
|
||||
|
||||
- <code>Error</code> Invalid parameters
|
||||
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| [options] | <code>Object</code> | |
|
||||
| [options.orientation] | <code>number</code> | Used to update the EXIF `Orientation` tag, integer between 1 and 8. |
|
||||
| [options.density] | <code>number</code> | Number of pixels per inch (DPI). |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
const outputSrgbWithMetadata = await sharp(inputRgbWithMetadata)
|
||||
sharp('input.jpg')
|
||||
.withMetadata()
|
||||
.toFile('output-with-metadata.jpg')
|
||||
.then(info => { ... });
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
// Set "IFD0-Copyright" in output EXIF metadata
|
||||
const data = await sharp(input)
|
||||
.withMetadata({
|
||||
exif: {
|
||||
IFD0: {
|
||||
Copyright: 'Wernham Hogg'
|
||||
}
|
||||
}
|
||||
})
|
||||
.toBuffer();
|
||||
```
|
||||
**Example**
|
||||
@ -348,8 +161,6 @@ const data = await sharp(input)
|
||||
|
||||
|
||||
## toFormat
|
||||
> toFormat(format, options) ⇒ <code>Sharp</code>
|
||||
|
||||
Force output to a given format.
|
||||
|
||||
|
||||
@ -373,8 +184,6 @@ const data = await sharp(input)
|
||||
|
||||
|
||||
## jpeg
|
||||
> jpeg([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Use these JPEG options for output image.
|
||||
|
||||
|
||||
@ -420,18 +229,12 @@ const data = await sharp(input)
|
||||
|
||||
|
||||
## png
|
||||
> png([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Use these PNG options for output image.
|
||||
|
||||
By default, PNG output is full colour at 8 bits per pixel.
|
||||
|
||||
By default, PNG output is full colour at 8 or 16 bits per pixel.
|
||||
Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel.
|
||||
Set `palette` to `true` for slower, indexed PNG output.
|
||||
|
||||
For 16 bits per pixel output, convert to `rgb16` via
|
||||
[toColourspace](/api-colour#tocolourspace).
|
||||
|
||||
|
||||
**Throws**:
|
||||
|
||||
@ -466,19 +269,9 @@ const data = await sharp(input)
|
||||
.png({ palette: true })
|
||||
.toBuffer();
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
// Output 16 bits per pixel RGB(A)
|
||||
const data = await sharp(input)
|
||||
.toColourspace('rgb16')
|
||||
.png()
|
||||
.toBuffer();
|
||||
```
|
||||
|
||||
|
||||
## webp
|
||||
> webp([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Use these WebP options for output image.
|
||||
|
||||
|
||||
@ -495,8 +288,6 @@ Use these WebP options for output image.
|
||||
| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression mode |
|
||||
| [options.nearLossless] | <code>boolean</code> | <code>false</code> | use near_lossless compression mode |
|
||||
| [options.smartSubsample] | <code>boolean</code> | <code>false</code> | use high quality chroma subsampling |
|
||||
| [options.smartDeblock] | <code>boolean</code> | <code>false</code> | auto-adjust the deblocking filter, can improve low contrast edges (slow) |
|
||||
| [options.preset] | <code>string</code> | <code>"'default'"</code> | named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text |
|
||||
| [options.effort] | <code>number</code> | <code>4</code> | CPU effort, between 0 (fastest) and 6 (slowest) |
|
||||
| [options.loop] | <code>number</code> | <code>0</code> | number of animation iterations, use 0 for infinite animation |
|
||||
| [options.delay] | <code>number</code> \| <code>Array.<number></code> | | delay(s) between animation frames (in milliseconds) |
|
||||
@ -521,8 +312,6 @@ const outputWebp = await sharp(inputWebp, { animated: true })
|
||||
|
||||
|
||||
## gif
|
||||
> gif([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Use these GIF options for the output image.
|
||||
|
||||
The first entry in the palette is reserved for transparency.
|
||||
@ -547,7 +336,6 @@ The palette of the input image will be re-used if possible.
|
||||
| [options.dither] | <code>number</code> | <code>1.0</code> | level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) |
|
||||
| [options.interFrameMaxError] | <code>number</code> | <code>0</code> | maximum inter-frame error for transparency, between 0 (lossless) and 32 |
|
||||
| [options.interPaletteMaxError] | <code>number</code> | <code>3</code> | maximum inter-palette error for palette reuse, between 0 and 256 |
|
||||
| [options.keepDuplicateFrames] | <code>boolean</code> | <code>false</code> | keep duplicate frames in the output instead of combining them |
|
||||
| [options.loop] | <code>number</code> | <code>0</code> | number of animation iterations, use 0 for infinite animation |
|
||||
| [options.delay] | <code>number</code> \| <code>Array.<number></code> | | delay(s) between animation frames (in milliseconds) |
|
||||
| [options.force] | <code>boolean</code> | <code>true</code> | force GIF output, otherwise attempt to use input format |
|
||||
@ -582,57 +370,10 @@ await sharp('in.gif', { animated: true })
|
||||
```
|
||||
|
||||
|
||||
## jp2
|
||||
> jp2([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Use these JP2 options for output image.
|
||||
|
||||
Requires libvips compiled with support for OpenJPEG.
|
||||
The prebuilt binaries do not include this - see
|
||||
[installing a custom libvips](https://sharp.pixelplumbing.com/install#custom-libvips).
|
||||
|
||||
|
||||
**Throws**:
|
||||
|
||||
- <code>Error</code> Invalid options
|
||||
|
||||
**Since**: 0.29.1
|
||||
|
||||
| Param | Type | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| [options] | <code>Object</code> | | output options |
|
||||
| [options.quality] | <code>number</code> | <code>80</code> | quality, integer 1-100 |
|
||||
| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression mode |
|
||||
| [options.tileWidth] | <code>number</code> | <code>512</code> | horizontal tile size |
|
||||
| [options.tileHeight] | <code>number</code> | <code>512</code> | vertical tile size |
|
||||
| [options.chromaSubsampling] | <code>string</code> | <code>"'4:4:4'"</code> | set to '4:2:0' to use chroma subsampling |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
// Convert any input to lossless JP2 output
|
||||
const data = await sharp(input)
|
||||
.jp2({ lossless: true })
|
||||
.toBuffer();
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
// Convert any input to very high quality JP2 output
|
||||
const data = await sharp(input)
|
||||
.jp2({
|
||||
quality: 100,
|
||||
chromaSubsampling: '4:4:4'
|
||||
})
|
||||
.toBuffer();
|
||||
```
|
||||
|
||||
|
||||
## tiff
|
||||
> tiff([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Use these TIFF options for output image.
|
||||
|
||||
The `density` can be set in pixels/inch via [withMetadata](#withmetadata)
|
||||
instead of providing `xres` and `yres` in pixels/mm.
|
||||
The `density` can be set in pixels/inch via [withMetadata](#withMetadata) instead of providing `xres` and `yres` in pixels/mm.
|
||||
|
||||
|
||||
**Throws**:
|
||||
@ -655,7 +396,6 @@ instead of providing `xres` and `yres` in pixels/mm.
|
||||
| [options.yres] | <code>number</code> | <code>1.0</code> | vertical resolution in pixels/mm |
|
||||
| [options.resolutionUnit] | <code>string</code> | <code>"'inch'"</code> | resolution unit options: inch, cm |
|
||||
| [options.bitdepth] | <code>number</code> | <code>8</code> | reduce bitdepth to 1, 2 or 4 bit |
|
||||
| [options.miniswhite] | <code>boolean</code> | <code>false</code> | write 1-bit images as miniswhite |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
@ -671,15 +411,12 @@ sharp('input.svg')
|
||||
|
||||
|
||||
## avif
|
||||
> avif([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Use these AVIF options for output image.
|
||||
|
||||
AVIF image sequences are not supported.
|
||||
Prebuilt binaries support a bitdepth of 8 only.
|
||||
Whilst it is possible to create AVIF images smaller than 16x16 pixels,
|
||||
most web browsers do not display these properly.
|
||||
|
||||
This feature is experimental on the Windows ARM64 platform
|
||||
and requires a CPU with ARM64v8.4 or later.
|
||||
AVIF image sequences are not supported.
|
||||
|
||||
|
||||
**Throws**:
|
||||
@ -695,7 +432,6 @@ and requires a CPU with ARM64v8.4 or later.
|
||||
| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression |
|
||||
| [options.effort] | <code>number</code> | <code>4</code> | CPU effort, between 0 (fastest) and 9 (slowest) |
|
||||
| [options.chromaSubsampling] | <code>string</code> | <code>"'4:4:4'"</code> | set to '4:2:0' to use chroma subsampling |
|
||||
| [options.bitdepth] | <code>number</code> | <code>8</code> | set bitdepth to 8, 10 or 12 bit |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
@ -712,8 +448,6 @@ const data = await sharp(input)
|
||||
|
||||
|
||||
## heif
|
||||
> heif(options) ⇒ <code>Sharp</code>
|
||||
|
||||
Use these HEIF options for output image.
|
||||
|
||||
Support for patent-encumbered HEIC images using `hevc` compression requires the use of a
|
||||
@ -728,13 +462,12 @@ globally-installed libvips compiled with support for libheif, libde265 and x265.
|
||||
|
||||
| Param | Type | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| options | <code>Object</code> | | output options |
|
||||
| options.compression | <code>string</code> | | compression format: av1, hevc |
|
||||
| [options] | <code>Object</code> | | output options |
|
||||
| [options.quality] | <code>number</code> | <code>50</code> | quality, integer 1-100 |
|
||||
| [options.compression] | <code>string</code> | <code>"'av1'"</code> | compression format: av1, hevc |
|
||||
| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression |
|
||||
| [options.effort] | <code>number</code> | <code>4</code> | CPU effort, between 0 (fastest) and 9 (slowest) |
|
||||
| [options.chromaSubsampling] | <code>string</code> | <code>"'4:4:4'"</code> | set to '4:2:0' to use chroma subsampling |
|
||||
| [options.bitdepth] | <code>number</code> | <code>8</code> | set bitdepth to 8, 10 or 12 bit |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
@ -745,8 +478,6 @@ const data = await sharp(input)
|
||||
|
||||
|
||||
## jxl
|
||||
> jxl([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Use these JPEG-XL (JXL) options for output image.
|
||||
|
||||
This feature is experimental, please do not use in production systems.
|
||||
@ -755,6 +486,8 @@ Requires libvips compiled with support for libjxl.
|
||||
The prebuilt binaries do not include this - see
|
||||
[installing a custom libvips](https://sharp.pixelplumbing.com/install#custom-libvips).
|
||||
|
||||
Image metadata (EXIF, XMP) is unsupported.
|
||||
|
||||
|
||||
**Throws**:
|
||||
|
||||
@ -769,15 +502,11 @@ The prebuilt binaries do not include this - see
|
||||
| [options.quality] | <code>number</code> | | calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified |
|
||||
| [options.decodingTier] | <code>number</code> | <code>0</code> | target decode speed tier, between 0 (highest quality) and 4 (lowest quality) |
|
||||
| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression |
|
||||
| [options.effort] | <code>number</code> | <code>7</code> | CPU effort, between 1 (fastest) and 9 (slowest) |
|
||||
| [options.loop] | <code>number</code> | <code>0</code> | number of animation iterations, use 0 for infinite animation |
|
||||
| [options.delay] | <code>number</code> \| <code>Array.<number></code> | | delay(s) between animation frames (in milliseconds) |
|
||||
| [options.effort] | <code>number</code> | <code>7</code> | CPU effort, between 3 (fastest) and 9 (slowest) |
|
||||
|
||||
|
||||
|
||||
## raw
|
||||
> raw([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Force output to be raw, uncompressed pixel data.
|
||||
Pixel ordering is left-to-right, top-to-bottom, without padding.
|
||||
Channel ordering will be RGB or RGBA for non-greyscale colourspaces.
|
||||
@ -813,8 +542,6 @@ const data = await sharp('input.png')
|
||||
|
||||
|
||||
## tile
|
||||
> tile([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Use tile-based deep zoom (image pyramid) output.
|
||||
|
||||
Set the format and options for tile images via the `toFormat`, `jpeg`, `png` or `webp` functions.
|
||||
@ -822,6 +549,10 @@ Use a `.zip` or `.szi` file extension with `toFile` to write to a compressed arc
|
||||
|
||||
The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`.
|
||||
|
||||
Requires libvips compiled with support for libgsf.
|
||||
The prebuilt binaries do not include this - see
|
||||
[installing a custom libvips](https://sharp.pixelplumbing.com/install#custom-libvips).
|
||||
|
||||
|
||||
**Throws**:
|
||||
|
||||
@ -836,7 +567,7 @@ The container will be set to `zip` when the output is a Buffer or Stream, otherw
|
||||
| [options.angle] | <code>number</code> | <code>0</code> | tile angle of rotation, must be a multiple of 90. |
|
||||
| [options.background] | <code>string</code> \| <code>Object</code> | <code>"{r: 255, g: 255, b: 255, alpha: 1}"</code> | background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to white without transparency. |
|
||||
| [options.depth] | <code>string</code> | | how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout. |
|
||||
| [options.skipBlanks] | <code>number</code> | <code>-1</code> | Threshold to skip tile generation. Range is 0-255 for 8-bit images, 0-65535 for 16-bit images. Default is 5 for `google` layout, -1 (no skip) otherwise. |
|
||||
| [options.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.container] | <code>string</code> | <code>"'fs'"</code> | tile container, with value `fs` (filesystem) or `zip` (compressed file). |
|
||||
| [options.layout] | <code>string</code> | <code>"'dz'"</code> | filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`. |
|
||||
| [options.centre] | <code>boolean</code> | <code>false</code> | centre image in tile. |
|
||||
@ -872,8 +603,6 @@ readableStream
|
||||
|
||||
|
||||
## timeout
|
||||
> timeout(options) ⇒ <code>Sharp</code>
|
||||
|
||||
Set a timeout for processing, in seconds.
|
||||
Use a value of zero to continue processing indefinitely, the default behaviour.
|
||||
|
@ -1,11 +1,4 @@
|
||||
---
|
||||
# This file was auto-generated from JSDoc in lib/resize.js
|
||||
title: Resizing images
|
||||
---
|
||||
|
||||
## resize
|
||||
> resize([width], [height], [options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Resize image to `width`, `height` or `width x height`.
|
||||
|
||||
When both a `width` and `height` are provided, the possible methods by which the image should **fit** these are:
|
||||
@ -17,7 +10,7 @@ When both a `width` and `height` are provided, the possible methods by which the
|
||||
|
||||
Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property.
|
||||
|
||||
<img alt="Examples of various values for the fit property when resizing" width="100%" style="aspect-ratio: 998/243" src="/api-resize-fit.svg">
|
||||
<img alt="Examples of various values for the fit property when resizing" width="100%" style="aspect-ratio: 998/243" src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/api-resize-fit.png">
|
||||
|
||||
When using a **fit** of `cover` or `contain`, the default **position** is `centre`. Other options are:
|
||||
- `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`.
|
||||
@ -26,23 +19,17 @@ 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.
|
||||
|
||||
The strategy-based approach initially resizes so one dimension is at its target length
|
||||
The experimental strategy-based approach resizes so one dimension is at its target length
|
||||
then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.
|
||||
- `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29).
|
||||
- `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
|
||||
|
||||
Possible downsizing kernels are:
|
||||
Possible interpolation kernels are:
|
||||
- `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation).
|
||||
- `linear`: Use a [triangle filter](https://en.wikipedia.org/wiki/Triangular_function).
|
||||
- `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline).
|
||||
- `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf).
|
||||
- `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`.
|
||||
- `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
|
||||
- `mks2013`: Use a [Magic Kernel Sharp](https://johncostella.com/magic/mks.pdf) 2013 kernel, as adopted by Facebook.
|
||||
- `mks2021`: Use a Magic Kernel Sharp 2021 kernel, with more accurate (reduced) sharpening than the 2013 version.
|
||||
|
||||
When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators.
|
||||
Downsampling kernels without a matching upsampling interpolator map to `cubic`.
|
||||
|
||||
Only one resize can occur per pipeline.
|
||||
Previous calls to `resize` in the same pipeline will be ignored.
|
||||
@ -63,7 +50,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.position] | <code>String</code> | <code>'centre'</code> | A position, gravity or strategy to use when `fit` is `cover` or `contain`. |
|
||||
| [options.background] | <code>String</code> \| <code>Object</code> | <code>{r: 0, g: 0, b: 0, alpha: 1}</code> | background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency. |
|
||||
| [options.kernel] | <code>String</code> | <code>'lanczos3'</code> | The kernel to use for image reduction and the inferred interpolator to use for upsampling. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load. |
|
||||
| [options.kernel] | <code>String</code> | <code>'lanczos3'</code> | The kernel to use for image reduction. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load. |
|
||||
| [options.withoutEnlargement] | <code>Boolean</code> | <code>false</code> | Do not scale up if the width *or* height are already less than the target dimensions, equivalent to GraphicsMagick's `>` geometry option. This may result in output dimensions smaller than the target dimensions. |
|
||||
| [options.withoutReduction] | <code>Boolean</code> | <code>false</code> | Do not scale down if the width *or* height are already greater than the target dimensions, equivalent to GraphicsMagick's `<` geometry option. This may still result in a crop to reach the target dimensions. |
|
||||
| [options.fastShrinkOnLoad] | <code>Boolean</code> | <code>true</code> | Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern or round-down of an auto-scaled dimension. |
|
||||
@ -159,8 +146,6 @@ const scaleByHalf = await sharp(input)
|
||||
|
||||
|
||||
## extend
|
||||
> extend(extend) ⇒ <code>Sharp</code>
|
||||
|
||||
Extend / pad / extrude one or more edges of the image with either
|
||||
the provided background colour or pixels derived from the image.
|
||||
This operation will always occur after resizing and extraction, if any.
|
||||
@ -219,13 +204,11 @@ sharp(input)
|
||||
|
||||
|
||||
## extract
|
||||
> extract(options) ⇒ <code>Sharp</code>
|
||||
|
||||
Extract/crop a region of the image.
|
||||
|
||||
- Use `extract` before `resize` for pre-resize extraction.
|
||||
- Use `extract` after `resize` for post-resize extraction.
|
||||
- Use `extract` twice and `resize` once for extract-then-resize-then-extract in a fixed operation order.
|
||||
- Use `extract` before and after for both.
|
||||
|
||||
|
||||
**Throws**:
|
||||
@ -262,15 +245,14 @@ sharp(input)
|
||||
|
||||
|
||||
## trim
|
||||
> trim([options]) ⇒ <code>Sharp</code>
|
||||
|
||||
Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.
|
||||
|
||||
Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels.
|
||||
|
||||
If the result of this operation would trim an image to nothing then no change is made.
|
||||
|
||||
The `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` properties.
|
||||
The `info` response Object, obtained from callback of `.toFile()` or `.toBuffer()`,
|
||||
will contain `trimOffsetLeft` and `trimOffsetTop` properties.
|
||||
|
||||
|
||||
**Throws**:
|
||||
@ -280,44 +262,46 @@ The `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` pro
|
||||
|
||||
| Param | Type | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| [options] | <code>Object</code> | | |
|
||||
| [options.background] | <code>string</code> \| <code>Object</code> | <code>"'top-left pixel'"</code> | Background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel. |
|
||||
| [options.threshold] | <code>number</code> | <code>10</code> | Allowed difference from the above colour, a positive number. |
|
||||
| [options.lineArt] | <code>boolean</code> | <code>false</code> | Does the input more closely resemble line art (e.g. vector) rather than being photographic? |
|
||||
| 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. |
|
||||
| [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. |
|
||||
| [trim.threshold] | <code>number</code> | <code>10</code> | the allowed difference from the above colour, a positive number. |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
// Trim pixels with a colour similar to that of the top-left pixel.
|
||||
await sharp(input)
|
||||
sharp(input)
|
||||
.trim()
|
||||
.toFile(output);
|
||||
.toFile(output, function(err, info) {
|
||||
...
|
||||
});
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
// Trim pixels with the exact same colour as that of the top-left pixel.
|
||||
await sharp(input)
|
||||
.trim({
|
||||
threshold: 0
|
||||
})
|
||||
.toFile(output);
|
||||
sharp(input)
|
||||
.trim(0)
|
||||
.toFile(output, function(err, info) {
|
||||
...
|
||||
});
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
// Assume input is line art and trim only pixels with a similar colour to red.
|
||||
const output = await sharp(input)
|
||||
.trim({
|
||||
background: "#FF0000",
|
||||
lineArt: true
|
||||
})
|
||||
.toBuffer();
|
||||
// Trim only pixels with a similar colour to red.
|
||||
sharp(input)
|
||||
.trim("#FF0000")
|
||||
.toFile(output, function(err, info) {
|
||||
...
|
||||
});
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
// Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
|
||||
const output = await sharp(input)
|
||||
sharp(input)
|
||||
.trim({
|
||||
background: "yellow",
|
||||
threshold: 42,
|
||||
})
|
||||
.toBuffer();
|
||||
.toFile(output, function(err, info) {
|
||||
...
|
||||
});
|
||||
```
|
@ -1,13 +1,5 @@
|
||||
---
|
||||
# This file was auto-generated from JSDoc in lib/utility.js
|
||||
title: Global properties
|
||||
---
|
||||
|
||||
## versions
|
||||
> versions
|
||||
|
||||
An Object containing the version numbers of sharp, libvips
|
||||
and (when using prebuilt binaries) its dependencies.
|
||||
An Object containing the version numbers of sharp, libvips and its dependencies.
|
||||
|
||||
|
||||
**Example**
|
||||
@ -17,8 +9,6 @@ console.log(sharp.versions);
|
||||
|
||||
|
||||
## interpolators
|
||||
> interpolators : <code>enum</code>
|
||||
|
||||
An Object containing the available interpolators and their proper values
|
||||
|
||||
|
||||
@ -37,8 +27,6 @@ An Object containing the available interpolators and their proper values
|
||||
|
||||
|
||||
## format
|
||||
> format ⇒ <code>Object</code>
|
||||
|
||||
An Object containing nested boolean values representing the available input and output formats/methods.
|
||||
|
||||
|
||||
@ -48,9 +36,18 @@ console.log(sharp.format);
|
||||
```
|
||||
|
||||
|
||||
## queue
|
||||
> queue
|
||||
## vendor
|
||||
An Object containing the platform and architecture
|
||||
of the current and installed vendored binaries.
|
||||
|
||||
|
||||
**Example**
|
||||
```js
|
||||
console.log(sharp.vendor);
|
||||
```
|
||||
|
||||
|
||||
## queue
|
||||
An EventEmitter that emits a `change` event when a task is either:
|
||||
- queued, waiting for _libuv_ to provide a worker thread
|
||||
- complete
|
||||
@ -65,8 +62,6 @@ sharp.queue.on('change', function(queueLength) {
|
||||
|
||||
|
||||
## cache
|
||||
> cache([options]) ⇒ <code>Object</code>
|
||||
|
||||
Gets or, when options are provided, sets the limits of _libvips'_ operation cache.
|
||||
Existing entries in the cache will be trimmed after any change in limits.
|
||||
This method always returns cache statistics,
|
||||
@ -94,8 +89,6 @@ sharp.cache(false);
|
||||
|
||||
|
||||
## concurrency
|
||||
> concurrency([concurrency]) ⇒ <code>number</code>
|
||||
|
||||
Gets or, when a concurrency is provided, sets
|
||||
the maximum number of threads _libvips_ should use to process _each image_.
|
||||
These are from a thread pool managed by glib,
|
||||
@ -113,9 +106,15 @@ Some image format libraries spawn additional threads,
|
||||
e.g. libaom manages its own 4 threads when encoding AVIF images,
|
||||
and these are independent of the value set here.
|
||||
|
||||
:::note
|
||||
Further [control over performance](/performance) is available.
|
||||
:::
|
||||
The maximum number of images that sharp can process in parallel
|
||||
is controlled by libuv's `UV_THREADPOOL_SIZE` environment variable,
|
||||
which defaults to 4.
|
||||
|
||||
https://nodejs.org/api/cli.html#uv_threadpool_sizesize
|
||||
|
||||
For example, by default, a machine with 8 CPU cores will process
|
||||
4 images in parallel and use up to 8 threads per image,
|
||||
so there will be up to 32 concurrent threads.
|
||||
|
||||
|
||||
**Returns**: <code>number</code> - concurrency
|
||||
@ -133,8 +132,6 @@ sharp.concurrency(0); // 4
|
||||
|
||||
|
||||
## counters
|
||||
> counters() ⇒ <code>Object</code>
|
||||
|
||||
Provides access to internal task counters.
|
||||
- queue is the number of tasks this module has queued waiting for _libuv_ to provide a worker thread from its pool.
|
||||
- process is the number of resize tasks currently being processed.
|
||||
@ -147,10 +144,8 @@ const counters = sharp.counters(); // { queue: 2, process: 4 }
|
||||
|
||||
|
||||
## simd
|
||||
> simd([simd]) ⇒ <code>boolean</code>
|
||||
|
||||
Get and set use of SIMD vector unit instructions.
|
||||
Requires libvips to have been compiled with highway support.
|
||||
Requires libvips to have been compiled with liborc support.
|
||||
|
||||
Improves the performance of `resize`, `blur` and `sharpen` operations
|
||||
by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.
|
||||
@ -164,69 +159,10 @@ by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM N
|
||||
**Example**
|
||||
```js
|
||||
const simd = sharp.simd();
|
||||
// simd is `true` if the runtime use of highway is currently enabled
|
||||
// simd is `true` if the runtime use of liborc is currently enabled
|
||||
```
|
||||
**Example**
|
||||
```js
|
||||
const simd = sharp.simd(false);
|
||||
// prevent libvips from using highway at runtime
|
||||
```
|
||||
|
||||
|
||||
## block
|
||||
> block(options)
|
||||
|
||||
Block libvips operations at runtime.
|
||||
|
||||
This is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable,
|
||||
which when set will block all "untrusted" operations.
|
||||
|
||||
|
||||
**Since**: 0.32.4
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| options | <code>Object</code> | |
|
||||
| options.operation | <code>Array.<string></code> | List of libvips low-level operation names to block. |
|
||||
|
||||
**Example** *(Block all TIFF input.)*
|
||||
```js
|
||||
sharp.block({
|
||||
operation: ['VipsForeignLoadTiff']
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
## unblock
|
||||
> unblock(options)
|
||||
|
||||
Unblock libvips operations at runtime.
|
||||
|
||||
This is useful for defining a list of allowed operations.
|
||||
|
||||
|
||||
**Since**: 0.32.4
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| options | <code>Object</code> | |
|
||||
| options.operation | <code>Array.<string></code> | List of libvips low-level operation names to unblock. |
|
||||
|
||||
**Example** *(Block all input except WebP from the filesystem.)*
|
||||
```js
|
||||
sharp.block({
|
||||
operation: ['VipsForeignLoad']
|
||||
});
|
||||
sharp.unblock({
|
||||
operation: ['VipsForeignLoadWebpFile']
|
||||
});
|
||||
```
|
||||
**Example** *(Block all input except JPEG and PNG from a Buffer or Stream.)*
|
||||
```js
|
||||
sharp.block({
|
||||
operation: ['VipsForeignLoad']
|
||||
});
|
||||
sharp.unblock({
|
||||
operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer']
|
||||
});
|
||||
// prevent libvips from using liborc at runtime
|
||||
```
|
@ -1,79 +0,0 @@
|
||||
// @ts-check
|
||||
import { defineConfig } from 'astro/config';
|
||||
import starlight from '@astrojs/starlight';
|
||||
|
||||
export default defineConfig({
|
||||
site: 'https://sharp.pixelplumbing.com',
|
||||
integrations: [
|
||||
starlight({
|
||||
title: 'sharp',
|
||||
description:
|
||||
'High performance Node.js image processing. The fastest module to resize JPEG, PNG, WebP and TIFF images.',
|
||||
logo: {
|
||||
src: './src/assets/sharp-logo.svg',
|
||||
alt: '#'
|
||||
},
|
||||
customCss: ['./src/styles/custom.css'],
|
||||
head: [{
|
||||
tag: 'meta',
|
||||
attrs: {
|
||||
'http-equiv': 'Content-Security-Policy',
|
||||
content: "default-src 'self'; connect-src 'self'; object-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://static.cloudflareinsights.com/beacon.min.js/;"
|
||||
}
|
||||
}, {
|
||||
tag: 'link',
|
||||
attrs: {
|
||||
rel: 'author',
|
||||
href: '/humans.txt',
|
||||
type: 'text/plain'
|
||||
}
|
||||
}, {
|
||||
tag: 'script',
|
||||
attrs: {
|
||||
type: 'application/ld+json'
|
||||
},
|
||||
content: JSON.stringify({
|
||||
'@context': 'https://schema.org',
|
||||
'@type': 'SoftwareSourceCode',
|
||||
name: 'sharp',
|
||||
description: 'High performance Node.js image processing',
|
||||
url: 'https://sharp.pixelplumbing.com',
|
||||
codeRepository: 'https://github.com/lovell/sharp',
|
||||
programmingLanguage: ['JavaScript', 'C++'],
|
||||
runtimePlatform: 'Node.js',
|
||||
copyrightHolder: {
|
||||
'@context': 'https://schema.org',
|
||||
'@type': 'Person',
|
||||
name: 'Lovell Fuller'
|
||||
},
|
||||
copyrightYear: 2013,
|
||||
license: 'https://www.apache.org/licenses/LICENSE-2.0'
|
||||
})
|
||||
}],
|
||||
sidebar: [
|
||||
{ label: 'Home', link: '/' },
|
||||
{ label: 'Installation', slug: 'install' },
|
||||
{
|
||||
label: 'API',
|
||||
items: [
|
||||
{ label: 'Constructor', slug: 'api-constructor' },
|
||||
{ label: 'Input metadata', slug: 'api-input' },
|
||||
{ label: 'Output options', slug: 'api-output' },
|
||||
{ label: 'Resizing images', slug: 'api-resize' },
|
||||
{ label: 'Compositing images', slug: 'api-composite' },
|
||||
{ label: 'Image operations', slug: 'api-operation' },
|
||||
{ label: 'Colour manipulation', slug: 'api-colour' },
|
||||
{ label: 'Channel manipulation', slug: 'api-channel' },
|
||||
{ label: 'Global properties', slug: 'api-utility' }
|
||||
]
|
||||
},
|
||||
{ label: 'Performance', slug: 'performance' },
|
||||
{ label: 'Changelog', slug: 'changelog' }
|
||||
],
|
||||
social: [
|
||||
{ icon: 'openCollective', label: 'Open Collective', href: 'https://opencollective.com/libvips' },
|
||||
{ icon: 'github', label: 'GitHub', href: 'https://github.com/lovell/sharp' }
|
||||
]
|
||||
})
|
||||
]
|
||||
});
|
38
docs/build.js
Normal file
@ -0,0 +1,38 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
const jsdoc2md = require('jsdoc-to-markdown');
|
||||
|
||||
[
|
||||
'constructor',
|
||||
'input',
|
||||
'resize',
|
||||
'composite',
|
||||
'operation',
|
||||
'colour',
|
||||
'channel',
|
||||
'output',
|
||||
'utility'
|
||||
].forEach(async (m) => {
|
||||
const input = path.join('lib', `${m}.js`);
|
||||
const output = path.join('docs', `api-${m}.md`);
|
||||
|
||||
const ast = await jsdoc2md.getTemplateData({ files: input });
|
||||
const markdown = await jsdoc2md.render({
|
||||
data: ast,
|
||||
'global-index-format': 'none',
|
||||
'module-index-format': 'none'
|
||||
});
|
||||
|
||||
const cleanMarkdown = markdown
|
||||
.replace(/(## [A-Za-z]+)[^\n]*/g, '$1') // simplify headings to match those of documentationjs, ensures existing URLs work
|
||||
.replace(/<a name="[A-Za-z+]+"><\/a>/g, '') // remove anchors, let docute add these (at markdown to HTML render time)
|
||||
.replace(/\*\*Kind\*\*: global[^\n]+/g, '') // remove all "global" Kind labels (requires JSDoc refactoring)
|
||||
.trim();
|
||||
|
||||
await fs.writeFile(output, cleanMarkdown);
|
||||
});
|
@ -1,42 +0,0 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import jsdoc2md from 'jsdoc-to-markdown';
|
||||
|
||||
const pages = {
|
||||
constructor: 'Constructor',
|
||||
input: 'Input metadata',
|
||||
resize: 'Resizing images',
|
||||
composite: 'Compositing images',
|
||||
operation: 'Image operations',
|
||||
colour: 'Colour manipulation',
|
||||
channel: 'Channel manipulation',
|
||||
output: 'Output options',
|
||||
utility: 'Global properties'
|
||||
};
|
||||
|
||||
Object.keys(pages).forEach(async (m) => {
|
||||
const input = path.join('lib', `${m}.js`);
|
||||
const output = path.join('docs', 'src', 'content', 'docs', `api-${m}.md`);
|
||||
|
||||
const ast = await jsdoc2md.getTemplateData({ files: input });
|
||||
const markdown = await jsdoc2md.render({
|
||||
data: ast,
|
||||
'global-index-format': 'none',
|
||||
'module-index-format': 'none'
|
||||
});
|
||||
|
||||
const cleanMarkdown =
|
||||
`---\n# This file was auto-generated from JSDoc in lib/${m}.js\ntitle: ${pages[m]}\n---\n\n` +
|
||||
markdown
|
||||
.replace(/(## )([A-Za-z0-9]+)([^\n]*)/g, '$1$2\n> $2$3\n') // simplify headings
|
||||
.replace(/<a name="[A-Za-z0-9+]+"><\/a>/g, '') // remove anchors
|
||||
.replace(/\*\*Kind\*\*: global[^\n]+/g, '') // remove all "global" Kind labels (requires JSDoc refactoring)
|
||||
.trim();
|
||||
|
||||
await fs.writeFile(output, cleanMarkdown);
|
||||
});
|
@ -1,395 +1,8 @@
|
||||
---
|
||||
title: Changelog
|
||||
---
|
||||
|
||||
## v0.34 - *hat*
|
||||
|
||||
Requires libvips v8.17.1
|
||||
|
||||
### v0.34.3 - TBD
|
||||
|
||||
* Upgrade to libvips v8.17.1 for upstream bug fixes.
|
||||
|
||||
* Add "Magic Kernel Sharp" (no relation) to resizing kernels.
|
||||
|
||||
* Deprecate top-level, format-specific constructor parameters, e.g. `subifd` becomes `tiff.subifd`.
|
||||
|
||||
* Expose `stylesheet` and `highBitdepth` SVG input parameters.
|
||||
|
||||
* Expose `keepDuplicateFrames` GIF output parameter.
|
||||
|
||||
* Add support for RAW digital camera image input. Requires libvips compiled with libraw support.
|
||||
|
||||
* Provide XMP metadata as a string, as well as a Buffer, where possible.
|
||||
|
||||
* Add `pageHeight` option to `create` and `raw` input for animated images.
|
||||
[#3236](https://github.com/lovell/sharp/issues/3236)
|
||||
|
||||
* Expose JPEG 2000 `oneshot` decoder option.
|
||||
[#4262](https://github.com/lovell/sharp/pull/4262)
|
||||
[@mbklein](https://github.com/mbklein)
|
||||
|
||||
* Support composite operation with non-sRGB pipeline colourspace.
|
||||
[#4412](https://github.com/lovell/sharp/pull/4412)
|
||||
[@kleisauke](https://github.com/kleisauke)
|
||||
|
||||
* Add `keepXmp` and `withXmp` for control over output XMP metadata.
|
||||
[#4416](https://github.com/lovell/sharp/pull/4416)
|
||||
[@tpatel](https://github.com/tpatel)
|
||||
|
||||
### v0.34.2 - 20th May 2025
|
||||
|
||||
* Ensure animated GIF to WebP conversion retains loop (regression in 0.34.0).
|
||||
[#3394](https://github.com/lovell/sharp/issues/3394)
|
||||
|
||||
* Ensure `pdfBackground` constructor property is used.
|
||||
[#4207](https://github.com/lovell/sharp/pull/4207)
|
||||
[#4398](https://github.com/lovell/sharp/issues/4398)
|
||||
|
||||
* Add experimental support for prebuilt Windows ARM64 binaries.
|
||||
[#4375](https://github.com/lovell/sharp/pull/4375)
|
||||
[@hans00](https://github.com/hans00)
|
||||
|
||||
* Ensure resizing with a `fit` of `contain` supports multiple alpha channels.
|
||||
[#4382](https://github.com/lovell/sharp/issues/4382)
|
||||
|
||||
* TypeScript: Ensure `metadata` response more closely matches reality.
|
||||
[#4383](https://github.com/lovell/sharp/issues/4383)
|
||||
|
||||
* TypeScript: Ensure `smartDeblock` property is included in WebP definition.
|
||||
[#4387](https://github.com/lovell/sharp/pull/4387)
|
||||
[@Stephen-X](https://github.com/Stephen-X)
|
||||
|
||||
* Ensure support for wide-character filenames on Windows (regression in 0.34.0).
|
||||
[#4391](https://github.com/lovell/sharp/issues/4391)
|
||||
|
||||
### v0.34.1 - 7th April 2025
|
||||
|
||||
* TypeScript: Ensure new `autoOrient` property is optional.
|
||||
[#4362](https://github.com/lovell/sharp/pull/4362)
|
||||
[@styfle](https://github.com/styfle)
|
||||
|
||||
### v0.34.0 - 4th April 2025
|
||||
|
||||
* Breaking: Support array of input images to be joined or animated.
|
||||
[#1580](https://github.com/lovell/sharp/issues/1580)
|
||||
|
||||
* Breaking: Ensure `removeAlpha` removes all alpha channels.
|
||||
[#2266](https://github.com/lovell/sharp/issues/2266)
|
||||
|
||||
* Breaking: Non-animated GIF output defaults to no-loop instead of loop-forever.
|
||||
[#3394](https://github.com/lovell/sharp/issues/3394)
|
||||
|
||||
* Breaking: Support `info.size` on wide-character systems via upgrade to C++17.
|
||||
[#3943](https://github.com/lovell/sharp/issues/3943)
|
||||
|
||||
* Breaking: Ensure `background` metadata can be parsed by `color` package.
|
||||
[#4090](https://github.com/lovell/sharp/issues/4090)
|
||||
|
||||
* Add `isPalette` and `bitsPerSample` to metadata, deprecate `paletteBitDepth`.
|
||||
|
||||
* Expose WebP `smartDeblock` output option.
|
||||
|
||||
* Prevent use of linux-x64 binaries with v1 microarchitecture.
|
||||
|
||||
* Add `autoOrient` operation and constructor option.
|
||||
[#4151](https://github.com/lovell/sharp/pull/4151)
|
||||
[@happycollision](https://github.com/happycollision)
|
||||
|
||||
* TypeScript: Ensure channel counts use the correct range.
|
||||
[#4197](https://github.com/lovell/sharp/pull/4197)
|
||||
[@DavidVaness](https://github.com/DavidVaness)
|
||||
|
||||
* Improve support for ppc64le architecture.
|
||||
[#4203](https://github.com/lovell/sharp/pull/4203)
|
||||
[@sumitd2](https://github.com/sumitd2)
|
||||
|
||||
* Add `pdfBackground` constructor property.
|
||||
[#4207](https://github.com/lovell/sharp/pull/4207)
|
||||
[@calebmer](https://github.com/calebmer)
|
||||
|
||||
* Expose erode and dilate operations.
|
||||
[#4243](https://github.com/lovell/sharp/pull/4243)
|
||||
[@qpincon](https://github.com/qpincon)
|
||||
|
||||
* Add support for RGBE images. Requires libvips compiled with radiance support.
|
||||
[#4316](https://github.com/lovell/sharp/pull/4316)
|
||||
[@florentzabera](https://github.com/florentzabera)
|
||||
|
||||
* Allow wide-gamut HEIF output at higher bitdepths.
|
||||
[#4344](https://github.com/lovell/sharp/issues/4344)
|
||||
|
||||
## v0.33 - *gauge*
|
||||
|
||||
Requires libvips v8.15.3
|
||||
|
||||
### v0.33.5 - 16th August 2024
|
||||
|
||||
* Upgrade to libvips v8.15.3 for upstream bug fixes.
|
||||
|
||||
* Add `pageHeight` and `pages` to response of multi-page output.
|
||||
[#3411](https://github.com/lovell/sharp/issues/3411)
|
||||
|
||||
* Ensure option to force use of a globally-installed libvips works correctly.
|
||||
[#4111](https://github.com/lovell/sharp/pull/4111)
|
||||
[@project0](https://github.com/project0)
|
||||
|
||||
* Minimise use of `engines` property to improve yarn v1 support.
|
||||
[#4130](https://github.com/lovell/sharp/issues/4130)
|
||||
|
||||
* Ensure `sharp.format.heif` includes only AVIF when using prebuilt binaries.
|
||||
[#4132](https://github.com/lovell/sharp/issues/4132)
|
||||
|
||||
* Add support to recomb operation for 4x4 matrices.
|
||||
[#4147](https://github.com/lovell/sharp/pull/4147)
|
||||
[@ton11797](https://github.com/ton11797)
|
||||
|
||||
* Expose PNG text chunks as `comments` metadata.
|
||||
[#4157](https://github.com/lovell/sharp/pull/4157)
|
||||
[@nkeynes](https://github.com/nkeynes)
|
||||
|
||||
* Expose optional `precision` and `minAmplitude` parameters of `blur` operation.
|
||||
[#4168](https://github.com/lovell/sharp/pull/4168)
|
||||
[#4172](https://github.com/lovell/sharp/pull/4172)
|
||||
[@marcosc90](https://github.com/marcosc90)
|
||||
|
||||
* Ensure `keepIccProfile` avoids colour transformation where possible.
|
||||
[#4186](https://github.com/lovell/sharp/issues/4186)
|
||||
|
||||
* TypeScript: `chromaSubsampling` metadata is optional.
|
||||
[#4191](https://github.com/lovell/sharp/pull/4191)
|
||||
[@DavidVaness](https://github.com/DavidVaness)
|
||||
|
||||
### v0.33.4 - 16th May 2024
|
||||
|
||||
* Remove experimental status from `pipelineColourspace`.
|
||||
|
||||
* Reduce default concurrency when musl thread over-subscription detected.
|
||||
|
||||
* TypeScript: add missing definitions for `OverlayOptions`.
|
||||
[#4048](https://github.com/lovell/sharp/pull/4048)
|
||||
[@ike-gg](https://github.com/ike-gg)
|
||||
|
||||
* Install: add advanced option to force use of a globally-installed libvips.
|
||||
[#4060](https://github.com/lovell/sharp/issues/4060)
|
||||
|
||||
* Expose `bilinear` resizing kernel (and interpolator).
|
||||
[#4061](https://github.com/lovell/sharp/issues/4061)
|
||||
|
||||
* Ensure `extend` operation stays sequential for multi-page TIFF (regression in 0.32.0).
|
||||
[#4069](https://github.com/lovell/sharp/issues/4069)
|
||||
|
||||
* Tighten validation of constructor `text` integer properties.
|
||||
[#4071](https://github.com/lovell/sharp/issues/4071)
|
||||
|
||||
* Simplify internal StaySequential logic.
|
||||
[#4074](https://github.com/lovell/sharp/pull/4074)
|
||||
[@kleisauke](https://github.com/kleisauke)
|
||||
|
||||
* Ensure negate operation occurs after profile conversion.
|
||||
[#4096](https://github.com/lovell/sharp/pull/4096)
|
||||
[@adriaanmeuris](https://github.com/adriaanmeuris)
|
||||
|
||||
### v0.33.3 - 23rd March 2024
|
||||
|
||||
* Upgrade to libvips v8.15.2 for upstream bug fixes.
|
||||
|
||||
* Ensure `keepIccProfile` retains P3 and CMYK input profiles.
|
||||
[#3906](https://github.com/lovell/sharp/issues/3906)
|
||||
[#4008](https://github.com/lovell/sharp/issues/4008)
|
||||
|
||||
* Ensure `text.wrap` property can accept `word-char` as value.
|
||||
[#4028](https://github.com/lovell/sharp/pull/4028)
|
||||
[@yolopunk](https://github.com/yolopunk)
|
||||
|
||||
* Ensure `clone` takes a deep copy of existing options.
|
||||
[#4029](https://github.com/lovell/sharp/issues/4029)
|
||||
|
||||
* Add `bitdepth` option to `heif` output (prebuilt binaries support 8-bit only).
|
||||
[#4036](https://github.com/lovell/sharp/pull/4036)
|
||||
[@mertalev](https://github.com/mertalev)
|
||||
|
||||
### v0.33.2 - 12th January 2024
|
||||
|
||||
* Upgrade to libvips v8.15.1 for upstream bug fixes.
|
||||
|
||||
* TypeScript: add definition for `keepMetadata`.
|
||||
[#3914](https://github.com/lovell/sharp/pull/3914)
|
||||
[@abhi0498](https://github.com/abhi0498)
|
||||
|
||||
* Ensure `extend` operation stays sequential when copying (regression in 0.32.0).
|
||||
[#3928](https://github.com/lovell/sharp/issues/3928)
|
||||
|
||||
* Improve error handling for unsupported multi-page rotation.
|
||||
[#3940](https://github.com/lovell/sharp/issues/3940)
|
||||
|
||||
### v0.33.1 - 17th December 2023
|
||||
|
||||
* Add support for Yarn Plug'n'Play filesystem layout.
|
||||
[#3888](https://github.com/lovell/sharp/issues/3888)
|
||||
|
||||
* Emit warning when attempting to use invalid ICC profiles.
|
||||
[#3895](https://github.com/lovell/sharp/issues/3895)
|
||||
|
||||
* Ensure `VIPS_NOVECTOR` environment variable is respected.
|
||||
[#3897](https://github.com/lovell/sharp/pull/3897)
|
||||
[@icetee](https://github.com/icetee)
|
||||
|
||||
### v0.33.0 - 29th November 2023
|
||||
|
||||
* Drop support for Node.js 14 and 16, now requires Node.js ^18.17.0 or >= 20.3.0
|
||||
|
||||
* Prebuilt binaries distributed via npm registry and installed via package manager.
|
||||
|
||||
* Building from source requires dependency on `node-addon-api`.
|
||||
|
||||
* Remove `sharp.vendor`.
|
||||
|
||||
* Partially deprecate `withMetadata()`, use `withExif()` and `withIccProfile()`.
|
||||
|
||||
* Add experimental support for WebAssembly-based runtimes.
|
||||
[@RReverser](https://github.com/RReverser)
|
||||
|
||||
* Options for `trim` operation must be an Object, add new `lineArt` option.
|
||||
[#2363](https://github.com/lovell/sharp/issues/2363)
|
||||
|
||||
* Improve luminance of `tint` operation with weighting function.
|
||||
[#3338](https://github.com/lovell/sharp/issues/3338)
|
||||
[@jcupitt](https://github.com/jcupitt)
|
||||
|
||||
* Ensure all `Error` objects contain a `stack` property.
|
||||
[#3653](https://github.com/lovell/sharp/issues/3653)
|
||||
|
||||
* Make `compression` option of `heif` mandatory to help reduce HEIF vs HEIC confusion.
|
||||
[#3740](https://github.com/lovell/sharp/issues/3740)
|
||||
|
||||
* Ensure correct interpretation of 16-bit raw input.
|
||||
[#3808](https://github.com/lovell/sharp/issues/3808)
|
||||
|
||||
* Add support for `miniswhite` when using TIFF output.
|
||||
[#3812](https://github.com/lovell/sharp/pull/3812)
|
||||
[@dnsbty](https://github.com/dnsbty)
|
||||
|
||||
* TypeScript: add missing definition for `withMetadata` boolean.
|
||||
[#3823](https://github.com/lovell/sharp/pull/3823)
|
||||
[@uhthomas](https://github.com/uhthomas)
|
||||
|
||||
* Add more fine-grained control over output metadata.
|
||||
[#3824](https://github.com/lovell/sharp/issues/3824)
|
||||
|
||||
* Ensure multi-page extract remains sequential.
|
||||
[#3837](https://github.com/lovell/sharp/issues/3837)
|
||||
# Changelog
|
||||
|
||||
## v0.32 - *flow*
|
||||
|
||||
Requires libvips v8.14.5
|
||||
|
||||
### v0.32.6 - 18th September 2023
|
||||
|
||||
* Upgrade to libvips v8.14.5 for upstream bug fixes.
|
||||
|
||||
* Ensure composite tile images are fully decoded (regression in 0.32.0).
|
||||
[#3767](https://github.com/lovell/sharp/issues/3767)
|
||||
|
||||
* Ensure `withMetadata` can add ICC profiles to RGB16 output.
|
||||
[#3773](https://github.com/lovell/sharp/issues/3773)
|
||||
|
||||
* Ensure `withMetadata` does not reduce 16-bit images to 8-bit (regression in 0.32.5).
|
||||
[#3773](https://github.com/lovell/sharp/issues/3773)
|
||||
|
||||
* TypeScript: Add definitions for block and unblock.
|
||||
[#3799](https://github.com/lovell/sharp/pull/3799)
|
||||
[@ldrick](https://github.com/ldrick)
|
||||
|
||||
### v0.32.5 - 15th August 2023
|
||||
|
||||
* Upgrade to libvips v8.14.4 for upstream bug fixes.
|
||||
|
||||
* TypeScript: Add missing `WebpPresetEnum` to definitions.
|
||||
[#3748](https://github.com/lovell/sharp/pull/3748)
|
||||
[@pilotso11](https://github.com/pilotso11)
|
||||
|
||||
* Ensure compilation using musl v1.2.4.
|
||||
[#3755](https://github.com/lovell/sharp/pull/3755)
|
||||
[@kleisauke](https://github.com/kleisauke)
|
||||
|
||||
* Ensure resize with a `fit` of `inside` respects 90/270 degree rotation.
|
||||
[#3756](https://github.com/lovell/sharp/issues/3756)
|
||||
|
||||
* TypeScript: Ensure `minSize` property of `WebpOptions` is boolean.
|
||||
[#3758](https://github.com/lovell/sharp/pull/3758)
|
||||
[@sho-xizz](https://github.com/sho-xizz)
|
||||
|
||||
* Ensure `withMetadata` adds default sRGB profile.
|
||||
[#3761](https://github.com/lovell/sharp/issues/3761)
|
||||
|
||||
### v0.32.4 - 21st July 2023
|
||||
|
||||
* Upgrade to libvips v8.14.3 for upstream bug fixes.
|
||||
|
||||
* Expose ability to (un)block low-level libvips operations by name.
|
||||
|
||||
* Prebuilt binaries: restore support for tile-based output.
|
||||
[#3581](https://github.com/lovell/sharp/issues/3581)
|
||||
|
||||
### v0.32.3 - 14th July 2023
|
||||
|
||||
* Expose `preset` option for WebP output.
|
||||
[#3639](https://github.com/lovell/sharp/issues/3639)
|
||||
|
||||
* Ensure decoding remains sequential for all operations (regression in 0.32.2).
|
||||
[#3725](https://github.com/lovell/sharp/issues/3725)
|
||||
|
||||
### v0.32.2 - 11th July 2023
|
||||
|
||||
* Limit HEIF output dimensions to 16384x16384, matches libvips.
|
||||
|
||||
* Ensure exceptions are not thrown when terminating.
|
||||
[#3569](https://github.com/lovell/sharp/issues/3569)
|
||||
|
||||
* Ensure the same access method is used for all inputs (regression in 0.32.0).
|
||||
[#3669](https://github.com/lovell/sharp/issues/3669)
|
||||
|
||||
* Improve detection of jp2 filename extensions.
|
||||
[#3674](https://github.com/lovell/sharp/pull/3674)
|
||||
[@bianjunjie1981](https://github.com/bianjunjie1981)
|
||||
|
||||
* Guard use of smartcrop premultiplied option to prevent warning (regression in 0.32.1).
|
||||
[#3710](https://github.com/lovell/sharp/issues/3710)
|
||||
|
||||
* Prevent over-compute in affine-based rotate before resize.
|
||||
[#3722](https://github.com/lovell/sharp/issues/3722)
|
||||
|
||||
* Allow sequential read for EXIF-based auto-orientation.
|
||||
[#3725](https://github.com/lovell/sharp/issues/3725)
|
||||
|
||||
### v0.32.1 - 27th April 2023
|
||||
|
||||
* Add experimental `unflatten` operation.
|
||||
[#3461](https://github.com/lovell/sharp/pull/3461)
|
||||
[@antonmarsden](https://github.com/antonmarsden)
|
||||
|
||||
* Ensure use of `flip` operation forces random access read (regression in 0.32.0).
|
||||
[#3600](https://github.com/lovell/sharp/issues/3600)
|
||||
|
||||
* Ensure `linear` operation works with 16-bit input (regression in 0.31.3).
|
||||
[#3605](https://github.com/lovell/sharp/issues/3605)
|
||||
|
||||
* Install: ensure proxy URLs are logged correctly.
|
||||
[#3615](https://github.com/lovell/sharp/pull/3615)
|
||||
[@TomWis97](https://github.com/TomWis97)
|
||||
|
||||
* Ensure profile-less CMYK to CMYK roundtrip skips colourspace conversion.
|
||||
[#3620](https://github.com/lovell/sharp/issues/3620)
|
||||
|
||||
* Add support for `modulate` operation when using non-sRGB pipeline colourspace.
|
||||
[#3620](https://github.com/lovell/sharp/issues/3620)
|
||||
|
||||
* Ensure `trim` operation works with CMYK images (regression in 0.31.0).
|
||||
[#3636](https://github.com/lovell/sharp/issues/3636)
|
||||
|
||||
* Install: coerce libc version to semver.
|
||||
[#3641](https://github.com/lovell/sharp/issues/3641)
|
||||
Requires libvips v8.14.2
|
||||
|
||||
### v0.32.0 - 24th March 2023
|
||||
|
1
docs/docute.min.js
vendored
Normal file
@ -1,7 +1,14 @@
|
||||
{
|
||||
"hosting": {
|
||||
"site": "pixelplumbing-sharp",
|
||||
"public": "dist",
|
||||
"public": ".",
|
||||
"ignore": [
|
||||
".*",
|
||||
"build.js",
|
||||
"firebase.json",
|
||||
"image/**",
|
||||
"search-index/**"
|
||||
],
|
||||
"headers": [
|
||||
{
|
||||
"source": "**",
|
||||
@ -11,6 +18,99 @@
|
||||
{ "key": "X-Frame-Options", "value": "SAMEORIGIN" }
|
||||
]
|
||||
}
|
||||
],
|
||||
"redirects": [
|
||||
{
|
||||
"source": "**/install/**",
|
||||
"destination": "/install",
|
||||
"type": 301
|
||||
},
|
||||
{
|
||||
"source": "/page/install",
|
||||
"destination": "/install",
|
||||
"type": 301
|
||||
},
|
||||
{
|
||||
"source": "**/api-constructor/**",
|
||||
"destination": "/api-constructor",
|
||||
"type": 301
|
||||
},
|
||||
{
|
||||
"source": "**/api-input/**",
|
||||
"destination": "/api-input",
|
||||
"type": 301
|
||||
},
|
||||
{
|
||||
"source": "**/api-output/**",
|
||||
"destination": "/api-output",
|
||||
"type": 301
|
||||
},
|
||||
{
|
||||
"source": "**/api-resize/**",
|
||||
"destination": "/api-resize",
|
||||
"type": 301
|
||||
},
|
||||
{
|
||||
"source": "**/api-compsite/**",
|
||||
"destination": "/api-compsite",
|
||||
"type": 301
|
||||
},
|
||||
{
|
||||
"source": "**/api-operation/**",
|
||||
"destination": "/api-operation",
|
||||
"type": 301
|
||||
},
|
||||
{
|
||||
"source": "**/api-colour/**",
|
||||
"destination": "/api-colour",
|
||||
"type": 301
|
||||
},
|
||||
{
|
||||
"source": "**/api-channel/**",
|
||||
"destination": "/api-channel",
|
||||
"type": 301
|
||||
},
|
||||
{
|
||||
"source": "**/api-utility/**",
|
||||
"destination": "/api-utility",
|
||||
"type": 301
|
||||
},
|
||||
{
|
||||
"source": "/page/api",
|
||||
"destination": "/api-constructor",
|
||||
"type": 301
|
||||
},
|
||||
{
|
||||
"source": "**/performance/**",
|
||||
"destination": "/performance",
|
||||
"type": 301
|
||||
},
|
||||
{
|
||||
"source": "/page/performance",
|
||||
"destination": "/performance",
|
||||
"type": 301
|
||||
},
|
||||
{
|
||||
"source": "**/changelog/**",
|
||||
"destination": "/changelog",
|
||||
"type": 301
|
||||
},
|
||||
{
|
||||
"source": "/page/changelog",
|
||||
"destination": "/changelog",
|
||||
"type": 301
|
||||
},
|
||||
{
|
||||
"source": "/en/**",
|
||||
"destination": "/",
|
||||
"type": 301
|
||||
}
|
||||
],
|
||||
"rewrites": [
|
||||
{
|
||||
"source": "**",
|
||||
"destination": "/index.html"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
@ -28,7 +28,7 @@ Name: Brandon Aaron
|
||||
GitHub: https://github.com/brandonaaron
|
||||
|
||||
Name: Andreas Lind
|
||||
GitHub: https://github.com/papandreou
|
||||
GitHub: https://github.com/papandreouGitHub:
|
||||
|
||||
Name: Maurus Cuelenaere
|
||||
GitHub: https://github.com/mcuelenaere
|
||||
@ -261,7 +261,7 @@ GitHub: https://github.com/brahima
|
||||
Name: Anton Marsden
|
||||
GitHub: https://github.com/antonmarsden
|
||||
|
||||
Name: Marcos Casagrande
|
||||
Name: Marcos Casagrande
|
||||
GitHub: https://github.com/marcosc90
|
||||
|
||||
Name: Emanuel Jöbstl
|
||||
@ -272,54 +272,3 @@ GitHub: https://github.com/janaz
|
||||
|
||||
Name: Lachlan Newman
|
||||
GitHub: https://github.com/LachlanNewman
|
||||
|
||||
Name: BJJ
|
||||
GitHub: https://github.com/bianjunjie1981
|
||||
|
||||
Name: Dennis Beatty
|
||||
GitHub: https://github.com/dnsbty
|
||||
|
||||
Name: Ingvar Stepanyan
|
||||
GitHub: https://github.com/RReverser
|
||||
|
||||
Name: Tamás András Horváth
|
||||
GitHub: https://github.com/icetee
|
||||
|
||||
Name: Aaron Che
|
||||
GitHub: https://github.com/yolopunk
|
||||
|
||||
Name: Mert Alev
|
||||
GitHub: https://github.com/mertalev
|
||||
|
||||
Name: Adriaan Meuris
|
||||
GitHub: https://github.com/adriaanmeuris
|
||||
|
||||
Name: Richard Hillmann
|
||||
GitHub: https://github.com/project0
|
||||
|
||||
Name: Pongsatorn Manusopit
|
||||
GitHub: https://github.com/ton11797
|
||||
|
||||
Name: Nathan Keynes
|
||||
GitHub: https://github.com/nkeynes
|
||||
|
||||
Name: Sumit D
|
||||
GitHub: https://github.com/sumitd2
|
||||
|
||||
Name: Caleb Meredith
|
||||
GitHub: https://github.com/calebmer
|
||||
|
||||
Name: Don Denton
|
||||
GitHub: https://github.com/happycollision
|
||||
|
||||
Name: Florent Zabera
|
||||
GitHub: https://github.com/florentzabera
|
||||
|
||||
Name: Quentin Pinçon
|
||||
GitHub: https://github.com/qpincon
|
||||
|
||||
Name: Hans Chen
|
||||
GitHub: https://github.com/hans00
|
||||
|
||||
Name: Thibaut Patel
|
||||
GitHub: https://github.com/tpatel
|
BIN
docs/image/api-resize-fit.png
Normal file
After Width: | Height: | Size: 16 KiB |
BIN
docs/image/sharp-logo-32.png
Normal file
After Width: | Height: | Size: 652 B |
BIN
docs/image/sharp-logo-600.png
Normal file
After Width: | Height: | Size: 2.8 KiB |
Before Width: | Height: | Size: 929 B After Width: | Height: | Size: 929 B |
Before Width: | Height: | Size: 508 B After Width: | Height: | Size: 508 B |
206
docs/index.html
Normal file
371
docs/install.md
Normal file
@ -0,0 +1,371 @@
|
||||
# Installation
|
||||
|
||||
```sh
|
||||
npm install sharp
|
||||
```
|
||||
|
||||
```sh
|
||||
yarn add sharp
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
* Node.js >= 14.15.0
|
||||
|
||||
## Prebuilt binaries
|
||||
|
||||
Ready-compiled sharp and libvips binaries are provided for use on the most common platforms:
|
||||
|
||||
* macOS x64 (>= 10.13)
|
||||
* macOS ARM64
|
||||
* Linux x64 (glibc >= 2.17, musl >= 1.1.24, CPU with SSE4.2)
|
||||
* Linux ARM64 (glibc >= 2.17, musl >= 1.1.24)
|
||||
* Windows x64
|
||||
* Windows x86
|
||||
|
||||
A ~7MB tarball containing libvips and its most commonly used dependencies
|
||||
is downloaded via HTTPS, verified via Subresource Integrity
|
||||
and decompressed into `node_modules/sharp/vendor` during `npm install`.
|
||||
|
||||
This provides support for the
|
||||
JPEG, PNG, WebP, AVIF (limited to 8-bit depth), TIFF, GIF and SVG (input) image formats.
|
||||
|
||||
The following platforms have prebuilt libvips but not sharp:
|
||||
|
||||
* Linux ARMv7 (glibc >= 2.28)
|
||||
* Linux ARMv6 (glibc >= 2.28)
|
||||
* Windows ARM64
|
||||
|
||||
The following platforms require compilation of both libvips and sharp from source:
|
||||
|
||||
* Linux x86
|
||||
* Linux ARMv7 (glibc <= 2.27, musl)
|
||||
* Linux ARMv6 (glibc <= 2.27, musl)
|
||||
* Linux PowerPC
|
||||
* FreeBSD
|
||||
* OpenBSD
|
||||
|
||||
## Common problems
|
||||
|
||||
The architecture and platform of Node.js used for `npm install`
|
||||
must be the same as the architecture and platform of Node.js used at runtime.
|
||||
See the [cross-platform](#cross-platform) section if this is not the case.
|
||||
|
||||
When using npm v6 or earlier, the `npm install --unsafe-perm` flag must be used when installing as `root` or a `sudo` user.
|
||||
|
||||
When using npm v7 or later, the user running `npm install` must own the directory it is run in.
|
||||
|
||||
The `npm install --ignore-scripts=false` flag must be used when `npm` has been configured to ignore installation scripts.
|
||||
|
||||
Check the output of running `npm install --verbose --foreground-scripts sharp` for useful error messages.
|
||||
|
||||
## Apple M1
|
||||
|
||||
Prebuilt sharp and libvips binaries have been provided for macOS on ARM64 since sharp v0.29.0.
|
||||
|
||||
## Cross-platform
|
||||
|
||||
At `npm install` time, prebuilt binaries are automatically selected for the
|
||||
current OS platform and CPU architecture, where available.
|
||||
|
||||
The target platform and/or architecture can be manually selected using the following flags.
|
||||
|
||||
```sh
|
||||
npm install --platform=... --arch=... --arm-version=... sharp
|
||||
```
|
||||
|
||||
* `--platform`: one of `linux`, `darwin` or `win32`.
|
||||
* `--arch`: one of `x64`, `ia32`, `arm` or `arm64`.
|
||||
* `--arm-version`: one of `6`, `7` or `8` (`arm` defaults to `6`, `arm64` defaults to `8`).
|
||||
* `--libc`: one of `glibc` or `musl`. This option only works with platform `linux`, defaults to `glibc`
|
||||
* `--sharp-install-force`: skip version compatibility and Subresource Integrity checks.
|
||||
|
||||
These values can also be set via environment variables,
|
||||
`npm_config_platform`, `npm_config_arch`, `npm_config_arm_version`, `npm_config_libc`
|
||||
and `SHARP_INSTALL_FORCE` respectively.
|
||||
|
||||
For example, if the target machine has a 64-bit ARM CPU and is running Alpine Linux,
|
||||
use the following flags:
|
||||
|
||||
```sh
|
||||
npm install --arch=arm64 --platform=linux --libc=musl sharp
|
||||
```
|
||||
|
||||
If the current machine is Alpine Linux and the target machine is Debian Linux on x64 cpu,
|
||||
use the following flags:
|
||||
|
||||
```sh
|
||||
npm install --arch=x64 --platform=linux --libc=glibc sharp
|
||||
```
|
||||
|
||||
Multiple platforms and architectures can be supported within the same installation tree.
|
||||
The following example for macOS installs x64 binaries then adds (via a rebuild) arm64 binaries:
|
||||
|
||||
```sh
|
||||
npm install --platform=darwin --arch=x64 sharp
|
||||
npm rebuild --platform=darwin --arch=arm64 sharp
|
||||
```
|
||||
|
||||
## Custom libvips
|
||||
|
||||
To use a custom, globally-installed version of libvips instead of the provided binaries,
|
||||
make sure it is at least the version listed under `config.libvips` in the `package.json` file
|
||||
and that it can be located using `pkg-config --modversion vips-cpp`.
|
||||
|
||||
For help compiling libvips and its dependencies, please see
|
||||
[building libvips from source](https://www.libvips.org/install.html#building-libvips-from-source).
|
||||
|
||||
The use of a globally-installed libvips is unsupported on Windows
|
||||
and on macOS when running Node.js under Rosetta.
|
||||
|
||||
## Building from source
|
||||
|
||||
This module will be compiled from source at `npm install` time when:
|
||||
|
||||
* a globally-installed libvips is detected (set the `SHARP_IGNORE_GLOBAL_LIBVIPS` environment variable to skip this),
|
||||
* prebuilt sharp binaries do not exist for the current platform, or
|
||||
* when the `npm install --build-from-source` flag is used.
|
||||
|
||||
Building from source requires:
|
||||
|
||||
* C++11 compiler
|
||||
* [node-gyp](https://github.com/nodejs/node-gyp#installation) and its dependencies
|
||||
|
||||
## Custom prebuilt binaries
|
||||
|
||||
This is an advanced approach that most people will not require.
|
||||
|
||||
### Prebuilt sharp binaries
|
||||
|
||||
To install the prebuilt sharp binaries from a custom URL,
|
||||
set the `sharp_binary_host` npm config option
|
||||
or the `npm_config_sharp_binary_host` environment variable.
|
||||
|
||||
To install the prebuilt sharp binaries from a directory on the local filesystem,
|
||||
set the `sharp_local_prebuilds` npm config option
|
||||
or the `npm_config_sharp_local_prebuilds` environment variable.
|
||||
|
||||
URL example:
|
||||
if `sharp_binary_host` is set to `https://hostname/path`
|
||||
and the sharp version is `1.2.3` then the resultant URL will be
|
||||
`https://hostname/path/v1.2.3/sharp-v1.2.3-napi-v5-platform-arch.tar.gz`.
|
||||
|
||||
Filename example:
|
||||
if `sharp_local_prebuilds` is set to `/path`
|
||||
and the sharp version is `1.2.3` then the resultant filename will be
|
||||
`/path/sharp-v1.2.3-napi-v5-platform-arch.tar.gz`.
|
||||
|
||||
### Prebuilt libvips binaries
|
||||
|
||||
To install the prebuilt libvips binaries from a custom URL,
|
||||
set the `sharp_libvips_binary_host` npm config option
|
||||
or the `npm_config_sharp_libvips_binary_host` environment variable.
|
||||
|
||||
To install the prebuilt libvips binaries from a directory on the local filesystem,
|
||||
set the `sharp_libvips_local_prebuilds` npm config option
|
||||
or the `npm_config_sharp_libvips_local_prebuilds` environment variable.
|
||||
|
||||
The version subpath and filename are appended to these.
|
||||
|
||||
URL example:
|
||||
if `sharp_libvips_binary_host` is set to `https://hostname/path`
|
||||
and the libvips version is `4.5.6` then the resultant URL will be
|
||||
`https://hostname/path/v4.5.6/libvips-4.5.6-platform-arch.tar.br`.
|
||||
|
||||
Filename example:
|
||||
if `sharp_libvips_local_prebuilds` is set to `/path`
|
||||
and the libvips version is `4.5.6` then the resultant filename will be
|
||||
`/path/v4.5.6/libvips-4.5.6-platform-arch.tar.br`.
|
||||
|
||||
See the Chinese mirror below for a further example.
|
||||
|
||||
If these binaries are modified, new integrity hashes can be provided
|
||||
at install time via `npm_package_config_integrity_platform_arch`
|
||||
environment variables, for example set
|
||||
`npm_package_config_integrity_linux_x64` to `sha512-abc...`.
|
||||
|
||||
The integrity hash of a file can be generated via:
|
||||
```sh
|
||||
sha512sum libvips-x.y.z-platform-arch.tar.br | cut -f1 -d' ' | xxd -r -p | base64 -w 0
|
||||
```
|
||||
|
||||
## Chinese mirror
|
||||
|
||||
A mirror site based in China, provided by Alibaba, contains binaries for both sharp and libvips.
|
||||
|
||||
To use this either set the following configuration:
|
||||
|
||||
```sh
|
||||
npm config set sharp_binary_host "https://npmmirror.com/mirrors/sharp"
|
||||
npm config set sharp_libvips_binary_host "https://npmmirror.com/mirrors/sharp-libvips"
|
||||
npm install sharp
|
||||
```
|
||||
|
||||
or set the following environment variables:
|
||||
|
||||
```sh
|
||||
npm_config_sharp_binary_host="https://npmmirror.com/mirrors/sharp" \
|
||||
npm_config_sharp_libvips_binary_host="https://npmmirror.com/mirrors/sharp-libvips" \
|
||||
npm install sharp
|
||||
```
|
||||
|
||||
## FreeBSD
|
||||
|
||||
The `vips` package must be installed before `npm install` is run.
|
||||
|
||||
```sh
|
||||
pkg install -y pkgconf vips
|
||||
```
|
||||
|
||||
```sh
|
||||
cd /usr/ports/graphics/vips/ && make install clean
|
||||
```
|
||||
|
||||
## Linux memory allocator
|
||||
|
||||
The default memory allocator on most glibc-based Linux systems
|
||||
(e.g. Debian, Red Hat) is unsuitable for long-running, multi-threaded
|
||||
processes that involve lots of small memory allocations.
|
||||
|
||||
For this reason, by default, sharp will limit the use of thread-based
|
||||
[concurrency](api-utility#concurrency) when the glibc allocator is
|
||||
detected at runtime.
|
||||
|
||||
To help avoid fragmentation and improve performance on these systems,
|
||||
the use of an alternative memory allocator such as
|
||||
[jemalloc](https://github.com/jemalloc/jemalloc) is recommended.
|
||||
|
||||
Those using musl-based Linux (e.g. Alpine) and non-Linux systems are
|
||||
unaffected.
|
||||
|
||||
## AWS Lambda
|
||||
|
||||
The `node_modules` directory of the
|
||||
[deployment package](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-package.html)
|
||||
must include binaries for the Linux x64 platform.
|
||||
|
||||
When building your deployment package on machines other than Linux x64 (glibc),
|
||||
run the following additional command after `npm install`:
|
||||
|
||||
```sh
|
||||
npm install
|
||||
rm -rf node_modules/sharp
|
||||
SHARP_IGNORE_GLOBAL_LIBVIPS=1 npm install --arch=x64 --platform=linux --libc=glibc sharp
|
||||
```
|
||||
|
||||
To get the best performance select the largest memory available.
|
||||
A 1536 MB function provides ~12x more CPU time than a 128 MB function.
|
||||
|
||||
When integrating with AWS API Gateway, ensure it is configured with the relevant
|
||||
[binary media types](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings.html).
|
||||
|
||||
## Bundlers
|
||||
|
||||
### webpack
|
||||
|
||||
Ensure sharp is excluded from bundling via the
|
||||
[externals](https://webpack.js.org/configuration/externals/)
|
||||
configuration.
|
||||
|
||||
```js
|
||||
externals: {
|
||||
'sharp': 'commonjs sharp'
|
||||
}
|
||||
```
|
||||
|
||||
### esbuild
|
||||
|
||||
Ensure sharp is excluded from bundling via the
|
||||
[external](https://esbuild.github.io/api/#external)
|
||||
configuration.
|
||||
|
||||
```js
|
||||
buildSync({
|
||||
entryPoints: ['app.js'],
|
||||
bundle: true,
|
||||
platform: 'node',
|
||||
external: ['sharp'],
|
||||
})
|
||||
```
|
||||
|
||||
```sh
|
||||
esbuild app.js --bundle --platform=node --external:sharp
|
||||
```
|
||||
|
||||
For `serverless-esbuild`, ensure platform-specific binaries are installed
|
||||
via the `serverless.yml` configuration.
|
||||
|
||||
```yaml
|
||||
custom:
|
||||
esbuild:
|
||||
external:
|
||||
- sharp
|
||||
packagerOptions:
|
||||
scripts:
|
||||
- npm install --arch=x64 --platform=linux sharp
|
||||
```
|
||||
|
||||
## TypeScript
|
||||
|
||||
TypeScript definitions are published as part of
|
||||
the `sharp` package from v0.32.0.
|
||||
|
||||
Previously these were available via the `@types/sharp` package,
|
||||
which is now deprecated.
|
||||
|
||||
When using Typescript, please ensure `devDependencies` includes
|
||||
the `@types/node` package.
|
||||
|
||||
## Fonts
|
||||
|
||||
When creating text images or rendering SVG images that contain text elements,
|
||||
`fontconfig` is used to find the relevant fonts.
|
||||
|
||||
On Windows and macOS systems, all system fonts are available for use.
|
||||
|
||||
On macOS systems using Homebrew, you may need to set the
|
||||
`PANGOCAIRO_BACKEND` environment variable to a value of `fontconfig`
|
||||
to ensure it is used for font discovery instead of Core Text.
|
||||
|
||||
On Linux systems, fonts that include the relevant
|
||||
[`fontconfig` configuration](https://www.freedesktop.org/software/fontconfig/fontconfig-user.html)
|
||||
when installed via package manager are available for use.
|
||||
|
||||
If `fontconfig` configuration is not found, the following error will occur:
|
||||
```
|
||||
Fontconfig error: Cannot load default config file
|
||||
```
|
||||
|
||||
In serverless environments where there is no control over font packages,
|
||||
use the `FONTCONFIG_PATH` environment variable to point to a custom location.
|
||||
|
||||
Embedded SVG fonts are unsupported.
|
||||
|
||||
## Worker threads
|
||||
|
||||
On some platforms, including glibc-based Linux,
|
||||
the main thread must call `require('sharp')`
|
||||
_before_ worker threads are created.
|
||||
This is to ensure shared libraries remain loaded in memory
|
||||
until after all threads are complete.
|
||||
|
||||
Without this, the following error may occur:
|
||||
```
|
||||
Module did not self-register
|
||||
```
|
||||
|
||||
## Known conflicts
|
||||
|
||||
### Canvas and Windows
|
||||
|
||||
The prebuilt binaries provided by `canvas` for Windows
|
||||
from v2.7.0 onwards depend on the Visual C++ Runtime (MSVCRT).
|
||||
These conflict with the binaries provided by sharp,
|
||||
which depend on the more modern Universal C Runtime (UCRT).
|
||||
|
||||
See [Automattic/node-canvas#2155](https://github.com/Automattic/node-canvas/issues/2155).
|
||||
|
||||
If both modules are used in the same Windows process, the following error will occur:
|
||||
```
|
||||
The specified procedure could not be found.
|
||||
```
|
@ -1,17 +0,0 @@
|
||||
{
|
||||
"name": "sharp-docs",
|
||||
"type": "module",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "astro dev",
|
||||
"start": "astro dev",
|
||||
"build": "astro build",
|
||||
"preview": "astro preview",
|
||||
"astro": "astro"
|
||||
},
|
||||
"dependencies": {
|
||||
"@astrojs/starlight": "^0.34.3",
|
||||
"astro": "^5.7.13"
|
||||
}
|
||||
}
|
111
docs/performance.md
Normal file
@ -0,0 +1,111 @@
|
||||
# Performance
|
||||
|
||||
A test to benchmark the performance of this module relative to alternatives.
|
||||
|
||||
Greater libvips performance can be expected with caching enabled (default)
|
||||
and using 8+ core machines, especially those with larger L1/L2 CPU caches.
|
||||
|
||||
The I/O limits of the relevant (de)compression library will generally determine maximum throughput.
|
||||
|
||||
## Contenders
|
||||
|
||||
* [jimp](https://www.npmjs.com/package/jimp) v0.22.7 - Image processing in pure JavaScript.
|
||||
* [imagemagick](https://www.npmjs.com/package/imagemagick) v0.1.3 - Supports filesystem only and "*has been unmaintained for a long time*".
|
||||
* [gm](https://www.npmjs.com/package/gm) v1.25.0 - Fully featured wrapper around GraphicsMagick's `gm` command line utility.
|
||||
* [@squoosh/lib](https://www.npmjs.com/package/@squoosh/lib) v0.4.0 - Image libraries transpiled to WebAssembly, includes GPLv3 code, but "*Project no longer maintained*".
|
||||
* [@squoosh/cli](https://www.npmjs.com/package/@squoosh/cli) v0.7.3 - Command line wrapper around `@squoosh/lib`, avoids GPLv3 by spawning process, but "*Project no longer maintained*".
|
||||
* sharp v0.32.0 / libvips v8.14.2 - Caching within libvips disabled to ensure a fair comparison.
|
||||
|
||||
## Environment
|
||||
|
||||
### AMD64
|
||||
|
||||
* AWS EC2 us-east-2 [c6a.xlarge](https://aws.amazon.com/ec2/instance-types/c6a/) (4x AMD EPYC 7R13)
|
||||
* Ubuntu 22.04 20230303 (ami-0122295b0eb922138)
|
||||
* Node.js 16.19.1
|
||||
|
||||
### ARM64
|
||||
|
||||
* AWS EC2 us-east-2 [c7g.xlarge](https://aws.amazon.com/ec2/instance-types/c7g/) (4x ARM Graviton3)
|
||||
* Ubuntu 22.04 20230303 (ami-0af198159897e7a29)
|
||||
* Node.js 16.19.1
|
||||
|
||||
## Task: JPEG
|
||||
|
||||
Decompress a 2725x2225 JPEG image,
|
||||
resize to 720x588 using Lanczos 3 resampling (where available),
|
||||
then compress to JPEG at a "quality" setting of 80.
|
||||
|
||||
Note: jimp does not support Lanczos 3, bicubic resampling used instead.
|
||||
|
||||
#### Results: JPEG (AMD64)
|
||||
|
||||
| Module | Input | Output | Ops/sec | Speed-up |
|
||||
| :----------------- | :----- | :----- | ------: | -------: |
|
||||
| jimp | buffer | buffer | 0.84 | 1.0 |
|
||||
| squoosh-cli | file | file | 1.07 | 1.3 |
|
||||
| squoosh-lib | buffer | buffer | 1.82 | 2.2 |
|
||||
| gm | buffer | buffer | 8.41 | 10.0 |
|
||||
| gm | file | file | 8.45 | 10.0 |
|
||||
| imagemagick | file | file | 8.77 | 10.4 |
|
||||
| sharp | stream | stream | 36.36 | 43.3 |
|
||||
| sharp | file | file | 38.67 | 46.0 |
|
||||
| sharp | buffer | buffer | 39.44 | 47.0 |
|
||||
|
||||
#### Results: JPEG (ARM64)
|
||||
|
||||
| Module | Input | Output | Ops/sec | Speed-up |
|
||||
| :----------------- | :----- | :----- | ------: | -------: |
|
||||
| jimp | buffer | buffer | 1.02 | 1.0 |
|
||||
| squoosh-cli | file | file | 1.11 | 1.1 |
|
||||
| squoosh-lib | buffer | buffer | 2.08 | 2.0 |
|
||||
| gm | buffer | buffer | 8.80 | 8.6 |
|
||||
| gm | file | file | 10.05 | 9.9 |
|
||||
| imagemagick | file | file | 10.28 | 10.1 |
|
||||
| sharp | stream | stream | 26.87 | 26.3 |
|
||||
| sharp | file | file | 27.88 | 27.3 |
|
||||
| sharp | buffer | buffer | 28.40 | 27.8 |
|
||||
|
||||
## Task: PNG
|
||||
|
||||
Decompress a 2048x1536 RGBA PNG image,
|
||||
premultiply the alpha channel,
|
||||
resize to 720x540 using Lanczos 3 resampling (where available),
|
||||
unpremultiply then compress as PNG with a "default" zlib compression level of 6
|
||||
and without adaptive filtering.
|
||||
|
||||
Note: jimp does not support premultiply/unpremultiply.
|
||||
|
||||
### Results: PNG (AMD64)
|
||||
|
||||
| Module | Input | Output | Ops/sec | Speed-up |
|
||||
| :----------------- | :----- | :----- | ------: | -------: |
|
||||
| squoosh-cli | file | file | 0.40 | 1.0 |
|
||||
| squoosh-lib | buffer | buffer | 0.47 | 1.2 |
|
||||
| gm | file | file | 6.47 | 16.2 |
|
||||
| jimp | buffer | buffer | 6.60 | 16.5 |
|
||||
| imagemagick | file | file | 7.08 | 17.7 |
|
||||
| sharp | file | file | 17.80 | 44.5 |
|
||||
| sharp | buffer | buffer | 18.02 | 45.0 |
|
||||
|
||||
### Results: PNG (ARM64)
|
||||
|
||||
| Module | Input | Output | Ops/sec | Speed-up |
|
||||
| :----------------- | :----- | :----- | ------: | -------: |
|
||||
| squoosh-cli | file | file | 0.40 | 1.0 |
|
||||
| squoosh-lib | buffer | buffer | 0.48 | 1.2 |
|
||||
| gm | file | file | 7.20 | 18.0 |
|
||||
| jimp | buffer | buffer | 7.62 | 19.1 |
|
||||
| imagemagick | file | file | 7.96 | 19.9 |
|
||||
| sharp | file | file | 12.97 | 32.4 |
|
||||
| sharp | buffer | buffer | 13.12 | 45.0 |
|
||||
|
||||
## Running the benchmark test
|
||||
|
||||
Requires Docker.
|
||||
|
||||
```sh
|
||||
git clone https://github.com/lovell/sharp.git
|
||||
cd sharp/test/bench
|
||||
./run-with-docker.sh
|
||||
```
|
@ -1,61 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="998" height="243" viewBox="0 0 998 243">
|
||||
<defs>
|
||||
<g id="placeholder">
|
||||
<rect width="180" height="128" fill="#64bed8"/>
|
||||
<circle cx="61.1" cy="36.8" r="19.3" fill="#ffefa9"/>
|
||||
<circle cx="61.1" cy="36.8" r="18.1" fill="#fdda42"/>
|
||||
<path d="m67.2 34.7 15.2 46L90 57.9l30.4 38 7.8-15.2 7.5 15.4H44z" fill="#6a696f"/>
|
||||
<path d="m82.4 80.7-15.2-46-.3 69h22.9z" fill="#474749"/>
|
||||
<path d="m90.1 58 12.2 15 18.2 23-13.9.1z" fill="#474749"/>
|
||||
<path d="M135.8 96H131l-2.8-15.3z" fill="#474749"/>
|
||||
<path d="M35.2 96h107.1c0 1.7-1.4 3.2-3.2 3.2H38.4a3.2 3.2 0 0 1-3.2-3.2z" fill="#b9c861"/>
|
||||
<path d="m67.2 34.7-.1 31-6.2-3-5.3 2.7z" fill="#fff"/>
|
||||
<path d="m67.2 34.7 7.6 23-7.7 8z" fill="#b3b1b4"/>
|
||||
<rect width="30.8" height="7.7" x="71.1" y="27.2" rx="2.8" ry="4.1" fill="#fff"/>
|
||||
<rect width="30.8" height="7.7" x="82.2" y="34.8" rx="2.8" ry="4.1" fill="#fff"/>
|
||||
<rect width="30.8" height="7.7" x="36.2" y="19.6" rx="2.8" ry="4.1" fill="#fff"/>
|
||||
<path d="m89.6 72.8-7.2 7.9L90 57.9l10 23z" fill="#fff"/>
|
||||
<path d="m90.1 58 10 23 2.2-8z" fill="#b3b1b4"/>
|
||||
<path d="M131.2 85.2 137 68l9 17.2-8 6z" fill="#8da128"/>
|
||||
<rect width="109.4" height="6.8" x="33.9" y="99.1" rx="13.2" ry="11.4" fill="#22b0d6"/>
|
||||
<path d="m137 68-5.8 17.2 6.8 6.1.3-13.7z" fill="#727d2e"/>
|
||||
<rect width="83.3" height="6.8" x="50.8" y="103.6" rx="10" ry="11.4" fill="#22b0d6"/>
|
||||
<rect width=".7" height="18.4" x="138" y="77.6" fill="#585657"/>
|
||||
<rect width=".5" height="5.2" x="2" y="-161.3" fill="#585657" transform="rotate(120)"/>
|
||||
<rect width=".5" height="5.3" x="5.5" y="-163.3" fill="#585657" transform="rotate(120)"/>
|
||||
<rect width=".5" height="4.8" x="-142.4" y="77.7" fill="#585657" transform="rotate(240)"/>
|
||||
<rect width=".5" height="5.1" x="-146" y="75.6" fill="#585657" transform="rotate(240)"/>
|
||||
</g>
|
||||
<pattern id="img" height="100%" width="100%" viewBox="0 0 180 128">
|
||||
<use xlink:href="#placeholder"/>
|
||||
</pattern>
|
||||
<pattern id="img-fill" width="100%" height="100%" viewBox="0 0 180 128" preserveAspectRatio="none">
|
||||
<use xlink:href="#placeholder"/>
|
||||
</pattern>
|
||||
</defs>
|
||||
<rect x="0" y="0" width="998" height="243" fill="#ddd"/>
|
||||
<g id="cover">
|
||||
<rect x="22" y="28" width="180" height="132" fill="url(#img)"/>
|
||||
<rect x="48" y="30" width="128" height="128" fill="none" stroke="#000" stroke-width="4"/>
|
||||
<text x="112" y="85%" dominant-baseline="middle" text-anchor="middle" font-family="sans" font-size="32" font-weight="bold">cover</text>
|
||||
</g>
|
||||
<g id="contain">
|
||||
<rect x="240" y="30" width="128" height="128" fill="url(#img)" stroke="#000" stroke-width="4"/>
|
||||
<text x="304" y="85%" dominant-baseline="middle" text-anchor="middle" font-family="sans" font-size="32" font-weight="bold" fill="#555">contain</text>
|
||||
</g>
|
||||
<g id="fill">
|
||||
<rect x="432" y="30" width="128" height="128" fill="url(#img-fill)" stroke="#000" stroke-width="4"/>
|
||||
<text x="496" y="85%" dominant-baseline="middle" text-anchor="middle" font-family="sans" font-size="32" font-weight="bold">fill</text>
|
||||
</g>
|
||||
<g id="inside">
|
||||
<rect x="624" y="48" width="128" height="92" fill="url(#img)" stroke="#000" stroke-width="4"/>
|
||||
<rect x="624" y="30" width="128" height="128" fill="none" stroke="#000" stroke-width="4" stroke-dasharray="12 4" stroke-dashoffset="6"/>
|
||||
<text x="688" y="85%" dominant-baseline="middle" text-anchor="middle" font-family="sans" font-size="32" font-weight="bold" fill="#555">inside</text>
|
||||
</g>
|
||||
<g id="outside">
|
||||
<rect x="792" y="30" width="176" height="128" fill="url(#img)" stroke="#000" stroke-width="4"/>
|
||||
<rect x="816" y="30" width="128" height="128" fill="none" stroke="#000" stroke-width="4" stroke-dasharray="12 4" stroke-dashoffset="-2"/>
|
||||
<text x="880" y="85%" dominant-baseline="middle" text-anchor="middle" font-family="sans" font-size="32" font-weight="bold">outside</text>
|
||||
</g>
|
||||
</svg>
|
Before Width: | Height: | Size: 4.0 KiB |
@ -1,5 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="86 86 550 550">
|
||||
<!-- Creative Commons CC0 1.0 Universal Public Domain Dedication -->
|
||||
<path fill="none" stroke="#9c0" stroke-width="80" d="M258.411 285.777l200.176-26.8M244.113 466.413L451.44 438.66M451.441 438.66V238.484M451.441 88.363v171.572l178.725-23.917M270.323 255.602V477.22M272.71 634.17V462.591L93.984 486.515"/>
|
||||
<path fill="none" stroke="#090" stroke-width="80" d="M451.441 610.246V438.66l178.725-23.91M269.688 112.59v171.58L90.964 308.093"/>
|
||||
</svg>
|
Before Width: | Height: | Size: 508 B |
@ -1,4 +0,0 @@
|
||||
User-agent: *
|
||||
Disallow:
|
||||
|
||||
Sitemap: https://sharp.pixelplumbing.com/sitemap-index.xml
|
2
docs/robots.txt
Normal file
@ -0,0 +1,2 @@
|
||||
User-agent: *
|
||||
Disallow:
|
1
docs/search-index.json
Normal file
64
docs/search-index/build.js
Normal file
@ -0,0 +1,64 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { extractDescription, extractKeywords, extractParameters } = require('./extract');
|
||||
|
||||
const searchIndex = [];
|
||||
|
||||
// Install
|
||||
const contents = fs.readFileSync(path.join(__dirname, '..', 'install.md'), 'utf8');
|
||||
const matches = contents.matchAll(
|
||||
/## (?<title>[A-Za-z0-9 ]+)\n\n(?<body>[^#]+)/gs
|
||||
);
|
||||
for (const match of matches) {
|
||||
const { title, body } = match.groups;
|
||||
const description = extractDescription(body);
|
||||
|
||||
searchIndex.push({
|
||||
t: title,
|
||||
d: description,
|
||||
k: extractKeywords(`${title} ${description}`),
|
||||
l: `/install#${title.toLowerCase().replace(/ /g, '-')}`
|
||||
});
|
||||
}
|
||||
|
||||
// API
|
||||
[
|
||||
'constructor',
|
||||
'input',
|
||||
'output',
|
||||
'resize',
|
||||
'composite',
|
||||
'operation',
|
||||
'channel',
|
||||
'colour',
|
||||
'utility'
|
||||
].forEach((section) => {
|
||||
const contents = fs.readFileSync(path.join(__dirname, '..', `api-${section}.md`), 'utf8');
|
||||
const matches = contents.matchAll(
|
||||
/## (?<title>[A-Za-z]+)\n(?<firstparagraph>.+?)\n\n.+?(?<parameters>\| Param .+?\n\n)?\*\*Example/gs
|
||||
);
|
||||
for (const match of matches) {
|
||||
const { title, firstparagraph, parameters } = match.groups;
|
||||
const description = firstparagraph.startsWith('###')
|
||||
? 'Constructor'
|
||||
: extractDescription(firstparagraph);
|
||||
const parameterNames = parameters ? extractParameters(parameters) : '';
|
||||
|
||||
searchIndex.push({
|
||||
t: title,
|
||||
d: description,
|
||||
k: extractKeywords(`${title} ${description} ${parameterNames}`),
|
||||
l: `/api-${section}#${title.toLowerCase()}`
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
fs.writeFileSync(
|
||||
path.join(__dirname, '..', 'search-index.json'),
|
||||
JSON.stringify(searchIndex)
|
||||
);
|
34
docs/search-index/extract.js
Normal file
@ -0,0 +1,34 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const stopWords = require('./stop-words');
|
||||
|
||||
const extractDescription = (str) =>
|
||||
str
|
||||
.replace(/### Examples.*/sg, '')
|
||||
.replace(/\(http[^)]+/g, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.replace(/[^A-Za-z0-9_/\-,. ]/g, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.substring(0, 200)
|
||||
.trim();
|
||||
|
||||
const extractParameters = (str) =>
|
||||
[...str.matchAll(/options\.(?<name>[^.`\] ]+)/gs)]
|
||||
.map((match) => match.groups.name)
|
||||
.map((name) => name.replace(/([A-Z])/g, ' $1').toLowerCase())
|
||||
.join(' ');
|
||||
|
||||
const extractKeywords = (str) =>
|
||||
[
|
||||
...new Set(
|
||||
str
|
||||
.split(/[ -/]/)
|
||||
.map((word) => word.toLowerCase().replace(/[^a-z]/g, ''))
|
||||
.filter((word) => word.length > 2 && word.length < 15 && !stopWords.includes(word))
|
||||
)
|
||||
].join(' ');
|
||||
|
||||
module.exports = { extractDescription, extractKeywords, extractParameters };
|
135
docs/search-index/stop-words.js
Normal file
@ -0,0 +1,135 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
module.exports = [
|
||||
'about',
|
||||
'after',
|
||||
'all',
|
||||
'allows',
|
||||
'already',
|
||||
'also',
|
||||
'alternative',
|
||||
'always',
|
||||
'and',
|
||||
'any',
|
||||
'are',
|
||||
'available',
|
||||
'based',
|
||||
'been',
|
||||
'before',
|
||||
'best',
|
||||
'both',
|
||||
'call',
|
||||
'callback',
|
||||
'can',
|
||||
'containing',
|
||||
'contains',
|
||||
'created',
|
||||
'current',
|
||||
'date',
|
||||
'default',
|
||||
'does',
|
||||
'each',
|
||||
'either',
|
||||
'ensure',
|
||||
'entirely',
|
||||
'etc',
|
||||
'every',
|
||||
'except',
|
||||
'following',
|
||||
'for',
|
||||
'from',
|
||||
'get',
|
||||
'gets',
|
||||
'given',
|
||||
'has',
|
||||
'have',
|
||||
'how',
|
||||
'image',
|
||||
'implies',
|
||||
'include',
|
||||
'including',
|
||||
'involve',
|
||||
'its',
|
||||
'last',
|
||||
'least',
|
||||
'lots',
|
||||
'make',
|
||||
'may',
|
||||
'more',
|
||||
'most',
|
||||
'much',
|
||||
'must',
|
||||
'non',
|
||||
'not',
|
||||
'now',
|
||||
'occur',
|
||||
'occurs',
|
||||
'one',
|
||||
'options',
|
||||
'other',
|
||||
'out',
|
||||
'over',
|
||||
'part',
|
||||
'perform',
|
||||
'performs',
|
||||
'please',
|
||||
'pre',
|
||||
'previously',
|
||||
'produce',
|
||||
'provide',
|
||||
'provided',
|
||||
'ready',
|
||||
'requires',
|
||||
'requiresharp',
|
||||
'returned',
|
||||
'run',
|
||||
'same',
|
||||
'see',
|
||||
'set',
|
||||
'sets',
|
||||
'sharp',
|
||||
'should',
|
||||
'since',
|
||||
'site',
|
||||
'some',
|
||||
'specified',
|
||||
'spelling',
|
||||
'such',
|
||||
'support',
|
||||
'supported',
|
||||
'sure',
|
||||
'take',
|
||||
'task',
|
||||
'than',
|
||||
'that',
|
||||
'the',
|
||||
'their',
|
||||
'then',
|
||||
'there',
|
||||
'therefore',
|
||||
'these',
|
||||
'this',
|
||||
'under',
|
||||
'unless',
|
||||
'unmaintained',
|
||||
'unsuitable',
|
||||
'until',
|
||||
'use',
|
||||
'used',
|
||||
'using',
|
||||
'value',
|
||||
'values',
|
||||
'via',
|
||||
'were',
|
||||
'when',
|
||||
'which',
|
||||
'while',
|
||||
'will',
|
||||
'with',
|
||||
'without',
|
||||
'you',
|
||||
'your'
|
||||
];
|
@ -1,5 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="86 86 550 550">
|
||||
<!-- Creative Commons CC0 1.0 Universal Public Domain Dedication -->
|
||||
<path fill="none" stroke="#9c0" stroke-width="80" d="M258.411 285.777l200.176-26.8M244.113 466.413L451.44 438.66M451.441 438.66V238.484M451.441 88.363v171.572l178.725-23.917M270.323 255.602V477.22M272.71 634.17V462.591L93.984 486.515"/>
|
||||
<path fill="none" stroke="#090" stroke-width="80" d="M451.441 610.246V438.66l178.725-23.91M269.688 112.59v171.58L90.964 308.093"/>
|
||||
</svg>
|
Before Width: | Height: | Size: 508 B |
@ -1,7 +0,0 @@
|
||||
import { defineCollection } from 'astro:content';
|
||||
import { docsLoader } from '@astrojs/starlight/loaders';
|
||||
import { docsSchema } from '@astrojs/starlight/schema';
|
||||
|
||||
export const collections = {
|
||||
docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
|
||||
};
|
@ -1,357 +0,0 @@
|
||||
---
|
||||
title: Installation
|
||||
---
|
||||
|
||||
Works with your choice of JavaScript package manager.
|
||||
|
||||
:::caution
|
||||
Please ensure your package manager is configured to install optional dependencies
|
||||
:::
|
||||
|
||||
If a package manager lockfile must support multiple platforms,
|
||||
please see the [cross-platform](#cross-platform) section
|
||||
to help decide which package manager is appropriate.
|
||||
|
||||
```sh
|
||||
npm install sharp
|
||||
```
|
||||
|
||||
```sh
|
||||
pnpm add sharp
|
||||
```
|
||||
|
||||
When using `pnpm`, you may need to add `sharp` to
|
||||
[ignoredBuiltDependencies](https://pnpm.io/settings#ignoredbuiltdependencies)
|
||||
to silence warnings.
|
||||
|
||||
```sh
|
||||
yarn add sharp
|
||||
```
|
||||
|
||||
```sh
|
||||
bun add sharp
|
||||
```
|
||||
|
||||
```sh
|
||||
deno run --allow-ffi ...
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
* Node-API v9 compatible runtime e.g. Node.js ^18.17.0 or >=20.3.0.
|
||||
|
||||
## Prebuilt binaries
|
||||
|
||||
Ready-compiled sharp and libvips binaries are provided for use on the most common platforms:
|
||||
|
||||
* macOS x64 (>= 10.15)
|
||||
* macOS ARM64
|
||||
* Linux ARM (glibc >= 2.31)
|
||||
* Linux ARM64 (glibc >= 2.26, musl >= 1.2.2)
|
||||
* Linux ppc64 (glibc >= 2.31)
|
||||
* Linux s390x (glibc >= 2.31)
|
||||
* Linux x64 (glibc >= 2.26, musl >= 1.2.2, CPU with SSE4.2)
|
||||
* Windows x64
|
||||
* Windows x86
|
||||
* Windows ARM64 (experimental, CPU with ARMv8.4 required for all features)
|
||||
|
||||
This provides support for the
|
||||
JPEG, PNG, WebP, AVIF (limited to 8-bit depth), TIFF, GIF and SVG (input) image formats.
|
||||
|
||||
## Cross-platform
|
||||
|
||||
At install time, package managers will automatically select prebuilt binaries
|
||||
for the current OS platform and CPU architecture, where available.
|
||||
|
||||
Some package managers support multiple platforms and architectures
|
||||
within the same installation tree and/or using the same lockfile.
|
||||
|
||||
### npm v10+
|
||||
|
||||
:::caution
|
||||
npm `package-lock.json` files shared by multiple platforms can cause installation problems due to [npm bug #4828](https://github.com/npm/cli/issues/4828)
|
||||
:::
|
||||
|
||||
Provides limited support via `--os`, `--cpu` and `--libc` flags.
|
||||
|
||||
To support macOS with Intel x64 and ARM64 CPUs:
|
||||
```sh
|
||||
npm install --cpu=x64 --os=darwin sharp
|
||||
npm install --cpu=arm64 --os=darwin sharp
|
||||
```
|
||||
|
||||
When the cross-target is Linux, the C standard library must be specified.
|
||||
|
||||
To support glibc (e.g. Debian) and musl (e.g. Alpine) Linux with Intel x64 CPUs:
|
||||
```sh
|
||||
npm install --cpu=x64 --os=linux --libc=glibc sharp
|
||||
npm install --cpu=x64 --os=linux --libc=musl sharp
|
||||
```
|
||||
|
||||
### yarn v3+
|
||||
|
||||
Use the [supportedArchitectures](https://yarnpkg.com/configuration/yarnrc#supportedArchitectures) configuration.
|
||||
|
||||
### pnpm v8+
|
||||
|
||||
Use the [supportedArchitectures](https://pnpm.io/settings#supportedarchitectures) configuration.
|
||||
|
||||
## Custom libvips
|
||||
|
||||
To use a custom, globally-installed version of libvips instead of the provided binaries,
|
||||
make sure it is at least the version listed under `config.libvips` in the `package.json` file
|
||||
and that it can be located using `pkg-config --modversion vips-cpp`.
|
||||
|
||||
For help compiling libvips and its dependencies, please see
|
||||
[building libvips from source](https://www.libvips.org/install.html#building-libvips-from-source).
|
||||
|
||||
The use of a globally-installed libvips is unsupported on Windows
|
||||
and on macOS when running Node.js under Rosetta.
|
||||
|
||||
## Building from source
|
||||
|
||||
This module will be compiled from source at `npm install` time when:
|
||||
|
||||
* a globally-installed libvips is detected, or
|
||||
* when the `npm install --build-from-source` flag is used.
|
||||
|
||||
The logic to detect a globally-installed libvips can be skipped by setting the
|
||||
`SHARP_IGNORE_GLOBAL_LIBVIPS` (never try to use it) or
|
||||
`SHARP_FORCE_GLOBAL_LIBVIPS` (always try to use it, even when missing or outdated)
|
||||
environment variables.
|
||||
|
||||
Building from source requires:
|
||||
|
||||
* C++17 compiler
|
||||
* [node-addon-api](https://www.npmjs.com/package/node-addon-api) version 7+
|
||||
* [node-gyp](https://github.com/nodejs/node-gyp#installation) version 9+ and its dependencies
|
||||
|
||||
There is an install-time check for these dependencies.
|
||||
If `node-addon-api` or `node-gyp` cannot be found, try adding them via:
|
||||
|
||||
```sh
|
||||
npm install --save node-addon-api node-gyp
|
||||
```
|
||||
|
||||
When using `pnpm`, you may need to add `sharp` to
|
||||
[onlyBuiltDependencies](https://pnpm.io/settings#onlybuiltdependencies)
|
||||
to ensure the installation script can be run.
|
||||
|
||||
For cross-compiling, the `--platform`, `--arch` and `--libc` npm flags
|
||||
(or the `npm_config_platform`, `npm_config_arch` and `npm_config_libc` environment variables)
|
||||
can be used to configure the target environment.
|
||||
|
||||
## WebAssembly
|
||||
|
||||
Experimental support is provided for runtime environments that provide
|
||||
multi-threaded Wasm via Workers.
|
||||
|
||||
Use in web browsers is unsupported.
|
||||
|
||||
Native text rendering is unsupported.
|
||||
|
||||
[Tile-based output](/api-output#tile) is unsupported.
|
||||
|
||||
```sh
|
||||
npm install --cpu=wasm32 sharp
|
||||
```
|
||||
|
||||
## FreeBSD
|
||||
|
||||
The `vips` package must be installed before `npm install` is run.
|
||||
|
||||
```sh
|
||||
pkg install -y pkgconf vips
|
||||
```
|
||||
|
||||
```sh
|
||||
cd /usr/ports/graphics/vips/ && make install clean
|
||||
```
|
||||
|
||||
## Linux memory allocator
|
||||
|
||||
The default memory allocator on most glibc-based Linux systems
|
||||
(e.g. Debian, Red Hat) is unsuitable for long-running, multi-threaded
|
||||
processes that involve lots of small memory allocations.
|
||||
|
||||
For this reason, by default, sharp will limit the use of thread-based
|
||||
[concurrency](/api-utility#concurrency) when the glibc allocator is
|
||||
detected at runtime.
|
||||
|
||||
To help avoid fragmentation and improve performance on these systems,
|
||||
the use of an alternative memory allocator such as
|
||||
[jemalloc](https://github.com/jemalloc/jemalloc) is recommended.
|
||||
|
||||
Those using musl-based Linux (e.g. Alpine) and non-Linux systems are
|
||||
unaffected.
|
||||
|
||||
## AWS Lambda
|
||||
|
||||
The `node_modules` directory of the
|
||||
[deployment package](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-package.html)
|
||||
must include binaries for either the linux-x64 or linux-arm64 platforms
|
||||
depending on the chosen architecture.
|
||||
|
||||
When building your deployment package on a machine that differs from the target architecture,
|
||||
see the [cross-platform](#cross-platform) section to help decide which package manager is appropriate
|
||||
and how to configure it.
|
||||
|
||||
Some package managers use symbolic links
|
||||
but AWS Lambda does not support these within deployment packages.
|
||||
|
||||
To get the best performance select the largest memory available.
|
||||
A 1536 MB function provides ~12x more CPU time than a 128 MB function.
|
||||
|
||||
When integrating with AWS API Gateway, ensure it is configured with the relevant
|
||||
[binary media types](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings.html).
|
||||
|
||||
## Bundlers
|
||||
|
||||
### webpack
|
||||
|
||||
Ensure sharp is excluded from bundling via the
|
||||
[externals](https://webpack.js.org/configuration/externals/)
|
||||
configuration.
|
||||
|
||||
```js
|
||||
externals: {
|
||||
'sharp': 'commonjs sharp'
|
||||
}
|
||||
```
|
||||
|
||||
### esbuild
|
||||
|
||||
Ensure sharp is excluded from bundling via the
|
||||
[external](https://esbuild.github.io/api/#external)
|
||||
configuration.
|
||||
|
||||
```js
|
||||
buildSync({
|
||||
entryPoints: ['app.js'],
|
||||
bundle: true,
|
||||
platform: 'node',
|
||||
external: ['sharp'],
|
||||
})
|
||||
```
|
||||
|
||||
```sh
|
||||
esbuild app.js --bundle --platform=node --external:sharp
|
||||
```
|
||||
|
||||
For `serverless-esbuild`, ensure platform-specific binaries are installed
|
||||
via the `serverless.yml` configuration.
|
||||
|
||||
```yaml
|
||||
custom:
|
||||
esbuild:
|
||||
external:
|
||||
- sharp
|
||||
packagerOptions:
|
||||
scripts:
|
||||
- npm install --os=linux --cpu=x64 sharp
|
||||
```
|
||||
|
||||
### electron
|
||||
|
||||
#### electron-builder
|
||||
|
||||
Ensure `sharp` is unpacked from the ASAR archive file using the
|
||||
[asarUnpack](https://www.electron.build/app-builder-lib.interface.platformspecificbuildoptions#asarunpack)
|
||||
option.
|
||||
|
||||
```json
|
||||
{
|
||||
"build": {
|
||||
"asar": true,
|
||||
"asarUnpack": [
|
||||
"**/node_modules/sharp/**/*",
|
||||
"**/node_modules/@img/**/*"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### electron-forge
|
||||
|
||||
Ensure `sharp` is unpacked from the ASAR archive file using the
|
||||
[unpack](https://js.electronforge.io/interfaces/_electron_forge_maker_squirrel.InternalOptions.Options.html#asar)
|
||||
option.
|
||||
|
||||
```json
|
||||
{
|
||||
"packagerConfig": {
|
||||
"asar": {
|
||||
"unpack": "**/node_modules/{sharp,@img}/**/*"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When using `electron-forge` with [Webpack](#webpack),
|
||||
you may also need to add
|
||||
[forge-externals-plugin](https://www.npmjs.com/package/@timfish/forge-externals-plugin).
|
||||
|
||||
### vite
|
||||
|
||||
Ensure `sharp` is excluded from bundling via the
|
||||
[build.rollupOptions](https://vitejs.dev/config/build-options.html)
|
||||
configuration.
|
||||
|
||||
```js
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig({
|
||||
build: {
|
||||
rollupOptions: {
|
||||
external: [
|
||||
"sharp"
|
||||
]
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## TypeScript
|
||||
|
||||
TypeScript definitions are published as part of
|
||||
the `sharp` package from v0.32.0.
|
||||
|
||||
Previously these were available via the `@types/sharp` package,
|
||||
which is now deprecated.
|
||||
|
||||
When using Typescript, please ensure `devDependencies` includes
|
||||
the `@types/node` package.
|
||||
|
||||
## Fonts
|
||||
|
||||
When creating text images or rendering SVG images that contain text elements,
|
||||
`fontconfig` is used to find the relevant fonts.
|
||||
|
||||
On Windows and macOS systems, all system fonts are available for use.
|
||||
|
||||
On macOS systems using Homebrew, you may need to set the
|
||||
`PANGOCAIRO_BACKEND` environment variable to a value of `fontconfig`
|
||||
to ensure it is used for font discovery instead of Core Text.
|
||||
|
||||
On Linux systems, fonts that include the relevant
|
||||
[`fontconfig` configuration](https://www.freedesktop.org/software/fontconfig/fontconfig-user.html)
|
||||
when installed via package manager are available for use.
|
||||
|
||||
If `fontconfig` configuration is not found, the following error will occur:
|
||||
```
|
||||
Fontconfig error: Cannot load default config file
|
||||
```
|
||||
|
||||
In serverless environments where there is no control over font packages,
|
||||
use the `FONTCONFIG_PATH` environment variable to point to a custom location.
|
||||
|
||||
Embedded SVG fonts are unsupported.
|
||||
|
||||
## Known conflicts
|
||||
|
||||
### Canvas and Windows
|
||||
|
||||
If both `canvas` and `sharp` modules are used in the same Windows process, the following error may occur:
|
||||
```
|
||||
The specified procedure could not be found.
|
||||
```
|
@ -1,137 +0,0 @@
|
||||
---
|
||||
title: Performance
|
||||
---
|
||||
|
||||
## Parallelism and concurrency
|
||||
|
||||
Node.js uses a libuv-managed thread pool when processing asynchronous calls to native modules such as sharp.
|
||||
|
||||
The maximum number of images that sharp can process in parallel is controlled by libuv's
|
||||
[`UV_THREADPOOL_SIZE`](https://nodejs.org/api/cli.html#uv_threadpool_sizesize)
|
||||
environment variable, which defaults to 4.
|
||||
|
||||
When using more than 4 physical CPU cores, set this environment variable
|
||||
before the Node.js process starts to increase the thread pool size.
|
||||
|
||||
```sh
|
||||
export UV_THREADPOOL_SIZE="$(lscpu -p | egrep -v "^#" | sort -u -t, -k 2,4 | wc -l)"
|
||||
```
|
||||
|
||||
libvips uses a glib-managed thread pool to avoid the overhead of spawning new threads.
|
||||
|
||||
The default number of threads used to concurrently process each image is the same as the number of CPU cores,
|
||||
except when using glibc-based Linux without jemalloc, where the default is `1` to help reduce memory fragmentation.
|
||||
|
||||
Use [`sharp.concurrency()`](/api-utility/#concurrency) to manage the number of threads per image.
|
||||
|
||||
To reduce memory fragmentation when using the default Linux glibc memory allocator, set the
|
||||
[`MALLOC_ARENA_MAX`](https://www.gnu.org/software/libc/manual/html_node/Memory-Allocation-Tunables.html)
|
||||
environment variable before the Node.js process starts to reduce the number of memory pools.
|
||||
|
||||
```sh
|
||||
export MALLOC_ARENA_MAX="2"
|
||||
```
|
||||
|
||||
## Benchmark
|
||||
|
||||
A test to benchmark the performance of this module relative to alternatives.
|
||||
|
||||
Greater libvips performance can be expected with caching enabled (default)
|
||||
and using 8+ core machines, especially those with larger L1/L2 CPU caches.
|
||||
|
||||
The I/O limits of the relevant (de)compression library will generally determine maximum throughput.
|
||||
|
||||
### Contenders
|
||||
|
||||
- [jimp](https://www.npmjs.com/package/jimp) v1.6.0 - Image processing in pure JavaScript.
|
||||
- [imagemagick](https://www.npmjs.com/package/imagemagick) v0.1.3 - Supports filesystem only and "_has been unmaintained for a long time_".
|
||||
- [gm](https://www.npmjs.com/package/gm) v1.25.1 - Fully featured wrapper around GraphicsMagick's `gm` command line utility, but "_has been sunset_".
|
||||
- sharp v0.34.3 / libvips v8.17.0 - Caching within libvips disabled to ensure a fair comparison.
|
||||
|
||||
### Environment
|
||||
|
||||
#### AMD64
|
||||
|
||||
- AWS EC2 us-west-2 [c7a.xlarge](https://aws.amazon.com/ec2/instance-types/c7a/) (4x AMD EPYC 9R14)
|
||||
- Ubuntu 25.04
|
||||
- Node.js 24.3.0
|
||||
|
||||
#### ARM64
|
||||
|
||||
- AWS EC2 us-west-2 [c8g.xlarge](https://aws.amazon.com/ec2/instance-types/c8g/) (4x ARM Graviton4)
|
||||
- Ubuntu 25.04
|
||||
- Node.js 24.3.0
|
||||
|
||||
### Task: JPEG
|
||||
|
||||
Decompress a 2725x2225 JPEG image,
|
||||
resize to 720x588 using Lanczos 3 resampling (where available),
|
||||
then compress to JPEG at a "quality" setting of 80.
|
||||
|
||||
Note: jimp does not support Lanczos 3, bicubic resampling used instead.
|
||||
|
||||
#### Results: JPEG (AMD64)
|
||||
|
||||
| Package | I/O | Ops/sec | Speed-up |
|
||||
| :---------- | :----- | ------: | -------: |
|
||||
| jimp | buffer | 2.40 | 1.0 |
|
||||
| jimp | file | 2.60 | 1.1 |
|
||||
| imagemagick | file | 9.70 | 4.0 |
|
||||
| gm | buffer | 11.60 | 4.8 |
|
||||
| gm | file | 11.72 | 4.9 |
|
||||
| sharp | stream | 59.40 | 24.8 |
|
||||
| sharp | file | 62.67 | 26.1 |
|
||||
| sharp | buffer | 64.42 | 26.8 |
|
||||
|
||||
#### Results: JPEG (ARM64)
|
||||
|
||||
| Package | I/O | Ops/sec | Speed-up |
|
||||
| :---------- | :----- | ------: | -------: |
|
||||
| jimp | buffer | 2.24 | 1.0 |
|
||||
| jimp | file | 2.47 | 1.1 |
|
||||
| imagemagick | file | 10.42 | 4.7 |
|
||||
| gm | buffer | 12.80 | 5.7 |
|
||||
| gm | file | 12.88 | 5.7 |
|
||||
| sharp | stream | 45.58 | 20.3 |
|
||||
| sharp | file | 47.99 | 21.4 |
|
||||
| sharp | buffer | 49.20 | 22.0 |
|
||||
|
||||
### Task: PNG
|
||||
|
||||
Decompress a 2048x1536 RGBA PNG image,
|
||||
premultiply the alpha channel,
|
||||
resize to 720x540 using Lanczos 3 resampling (where available),
|
||||
unpremultiply then compress as PNG with a "default" zlib compression level of 6
|
||||
and without adaptive filtering.
|
||||
|
||||
Note: jimp does not support premultiply/unpremultiply.
|
||||
|
||||
#### Results: PNG (AMD64)
|
||||
|
||||
| Package | I/O | Ops/sec | Speed-up |
|
||||
| :---------- | :----- | ------: | -------: |
|
||||
| imagemagick | file | 6.06 | 1.0 |
|
||||
| gm | file | 8.44 | 1.4 |
|
||||
| jimp | buffer | 10.98 | 1.8 |
|
||||
| sharp | file | 28.26 | 4.7 |
|
||||
| sharp | buffer | 28.70 | 4.7 |
|
||||
|
||||
#### Results: PNG (ARM64)
|
||||
|
||||
| Package | I/O | Ops/sec | Speed-up |
|
||||
| :---------- | :----- | ------: | -------: |
|
||||
| imagemagick | file | 7.09 | 1.0 |
|
||||
| gm | file | 8.93 | 1.3 |
|
||||
| jimp | buffer | 10.28 | 1.5 |
|
||||
| sharp | file | 23.81 | 3.4 |
|
||||
| sharp | buffer | 24.19 | 3.4 |
|
||||
|
||||
## Running the benchmark test
|
||||
|
||||
Requires Docker.
|
||||
|
||||
```sh
|
||||
git clone https://github.com/lovell/sharp.git
|
||||
cd sharp/test/bench
|
||||
./run-with-docker.sh
|
||||
```
|
@ -1,45 +0,0 @@
|
||||
@view-transition {
|
||||
navigation: auto;
|
||||
}
|
||||
|
||||
:root {
|
||||
--sl-content-width: 60rem;
|
||||
--sl-color-accent-low: #072d00;
|
||||
--sl-color-accent: #247f00;
|
||||
--sl-color-accent-high: #aad7a0;
|
||||
--sl-color-white: #ffffff;
|
||||
--sl-color-gray-1: #eaf0e8;
|
||||
--sl-color-gray-2: #c5cdc3;
|
||||
--sl-color-gray-3: #99a796;
|
||||
--sl-color-gray-4: #4f5c4d;
|
||||
--sl-color-gray-5: #303c2d;
|
||||
--sl-color-gray-6: #1f2a1c;
|
||||
--sl-color-black: #151a13;
|
||||
}
|
||||
|
||||
:root[data-theme="light"] {
|
||||
--sl-color-accent-low: #c0e2b8;
|
||||
--sl-color-accent: #165800;
|
||||
--sl-color-accent-high: #0d3e00;
|
||||
--sl-color-white: #151a13;
|
||||
--sl-color-gray-1: #1f2a1c;
|
||||
--sl-color-gray-2: #303c2d;
|
||||
--sl-color-gray-3: #4f5c4d;
|
||||
--sl-color-gray-4: #82907f;
|
||||
--sl-color-gray-5: #bdc4bb;
|
||||
--sl-color-gray-6: #eaf0e8;
|
||||
--sl-color-gray-7: #f4f7f3;
|
||||
--sl-color-black: #ffffff;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
background-color: var(--sl-color-gray-6);
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.site-title::after {
|
||||
content: "High performance Node.js image processing";
|
||||
color: var(--sl-color-text);
|
||||
font-size: var(--sl-text-sm);
|
||||
padding-top: 0.3rem;
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
{
|
||||
"extends": "astro/tsconfigs/strict",
|
||||
"include": [".astro/types.d.ts", "**/*"],
|
||||
"exclude": ["dist"]
|
||||
}
|
14
install/can-compile.js
Normal file
@ -0,0 +1,14 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const libvips = require('../lib/libvips');
|
||||
|
||||
try {
|
||||
if (!(libvips.useGlobalLibvips() || libvips.hasVendoredLibvips())) {
|
||||
process.exitCode = 1;
|
||||
}
|
||||
} catch (err) {
|
||||
process.exitCode = 1;
|
||||
}
|
@ -1,41 +0,0 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
try {
|
||||
const { useGlobalLibvips, globalLibvipsVersion, log, spawnRebuild } = require('../lib/libvips');
|
||||
|
||||
const buildFromSource = (msg) => {
|
||||
log(msg);
|
||||
log('Attempting to build from source via node-gyp');
|
||||
try {
|
||||
const addonApi = require('node-addon-api');
|
||||
log(`Found node-addon-api ${addonApi.version || ''}`);
|
||||
} catch (err) {
|
||||
log('Please add node-addon-api to your dependencies');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const gyp = require('node-gyp');
|
||||
log(`Found node-gyp ${gyp().version}`);
|
||||
} catch (err) {
|
||||
log('Please add node-gyp to your dependencies');
|
||||
return;
|
||||
}
|
||||
log('See https://sharp.pixelplumbing.com/install#building-from-source');
|
||||
const status = spawnRebuild();
|
||||
if (status !== 0) {
|
||||
process.exit(status);
|
||||
}
|
||||
};
|
||||
|
||||
if (useGlobalLibvips(log)) {
|
||||
buildFromSource(`Detected globally-installed libvips v${globalLibvipsVersion()}`);
|
||||
} else if (process.env.npm_config_build_from_source) {
|
||||
buildFromSource('Detected --build-from-source flag');
|
||||
}
|
||||
} catch (err) {
|
||||
const summary = err.message.split(/\n/).slice(0, 1);
|
||||
console.log(`sharp: skipping install check: ${summary}`);
|
||||
}
|
40
install/dll-copy.js
Normal file
@ -0,0 +1,40 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const libvips = require('../lib/libvips');
|
||||
const platform = require('../lib/platform');
|
||||
|
||||
const minimumLibvipsVersion = libvips.minimumLibvipsVersion;
|
||||
|
||||
const platformAndArch = platform();
|
||||
|
||||
if (platformAndArch.startsWith('win32')) {
|
||||
const buildReleaseDir = path.join(__dirname, '..', 'build', 'Release');
|
||||
libvips.log(`Creating ${buildReleaseDir}`);
|
||||
try {
|
||||
libvips.mkdirSync(buildReleaseDir);
|
||||
} catch (err) {}
|
||||
const vendorLibDir = path.join(__dirname, '..', 'vendor', minimumLibvipsVersion, platformAndArch, 'lib');
|
||||
libvips.log(`Copying DLLs from ${vendorLibDir} to ${buildReleaseDir}`);
|
||||
try {
|
||||
fs
|
||||
.readdirSync(vendorLibDir)
|
||||
.filter(function (filename) {
|
||||
return /\.dll$/.test(filename);
|
||||
})
|
||||
.forEach(function (filename) {
|
||||
fs.copyFileSync(
|
||||
path.join(vendorLibDir, filename),
|
||||
path.join(buildReleaseDir, filename)
|
||||
);
|
||||
});
|
||||
} catch (err) {
|
||||
libvips.log(err);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
215
install/libvips.js
Normal file
@ -0,0 +1,215 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const stream = require('stream');
|
||||
const zlib = require('zlib');
|
||||
const { createHash } = require('crypto');
|
||||
|
||||
const detectLibc = require('detect-libc');
|
||||
const semverLessThan = require('semver/functions/lt');
|
||||
const semverSatisfies = require('semver/functions/satisfies');
|
||||
const simpleGet = require('simple-get');
|
||||
const tarFs = require('tar-fs');
|
||||
|
||||
const agent = require('../lib/agent');
|
||||
const libvips = require('../lib/libvips');
|
||||
const platform = require('../lib/platform');
|
||||
|
||||
const minimumGlibcVersionByArch = {
|
||||
arm: '2.28',
|
||||
arm64: '2.17',
|
||||
x64: '2.17'
|
||||
};
|
||||
|
||||
const hasSharpPrebuild = [
|
||||
'darwin-x64',
|
||||
'darwin-arm64',
|
||||
'linux-arm64',
|
||||
'linux-x64',
|
||||
'linuxmusl-x64',
|
||||
'linuxmusl-arm64',
|
||||
'win32-ia32',
|
||||
'win32-x64'
|
||||
];
|
||||
|
||||
const { minimumLibvipsVersion, minimumLibvipsVersionLabelled } = libvips;
|
||||
const localLibvipsDir = process.env.npm_config_sharp_libvips_local_prebuilds || '';
|
||||
const distHost = process.env.npm_config_sharp_libvips_binary_host || 'https://github.com/lovell/sharp-libvips/releases/download';
|
||||
const distBaseUrl = process.env.npm_config_sharp_dist_base_url || process.env.SHARP_DIST_BASE_URL || `${distHost}/v${minimumLibvipsVersionLabelled}/`;
|
||||
const installationForced = !!(process.env.npm_config_sharp_install_force || process.env.SHARP_INSTALL_FORCE);
|
||||
|
||||
const fail = function (err) {
|
||||
libvips.log(err);
|
||||
if (err.code === 'EACCES') {
|
||||
libvips.log('Are you trying to install as a root or sudo user?');
|
||||
libvips.log('- For npm <= v6, try again with the "--unsafe-perm" flag');
|
||||
libvips.log('- For npm >= v8, the user must own the directory "npm install" is run in');
|
||||
}
|
||||
libvips.log('Please see https://sharp.pixelplumbing.com/install for required dependencies');
|
||||
process.exit(1);
|
||||
};
|
||||
|
||||
const handleError = function (err) {
|
||||
if (installationForced) {
|
||||
libvips.log(`Installation warning: ${err.message}`);
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
const verifyIntegrity = function (platformAndArch) {
|
||||
const expected = libvips.integrity(platformAndArch);
|
||||
if (installationForced || !expected) {
|
||||
libvips.log(`Integrity check skipped for ${platformAndArch}`);
|
||||
return new stream.PassThrough();
|
||||
}
|
||||
const hash = createHash('sha512');
|
||||
return new stream.Transform({
|
||||
transform: function (chunk, _encoding, done) {
|
||||
hash.update(chunk);
|
||||
done(null, chunk);
|
||||
},
|
||||
flush: function (done) {
|
||||
const digest = `sha512-${hash.digest('base64')}`;
|
||||
if (expected !== digest) {
|
||||
libvips.removeVendoredLibvips();
|
||||
libvips.log(`Integrity expected: ${expected}`);
|
||||
libvips.log(`Integrity received: ${digest}`);
|
||||
done(new Error(`Integrity check failed for ${platformAndArch}`));
|
||||
} else {
|
||||
libvips.log(`Integrity check passed for ${platformAndArch}`);
|
||||
done();
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const extractTarball = function (tarPath, platformAndArch) {
|
||||
const versionedVendorPath = path.join(__dirname, '..', 'vendor', minimumLibvipsVersion, platformAndArch);
|
||||
libvips.mkdirSync(versionedVendorPath);
|
||||
|
||||
const ignoreVendorInclude = hasSharpPrebuild.includes(platformAndArch) && !process.env.npm_config_build_from_source;
|
||||
const ignore = function (name) {
|
||||
return ignoreVendorInclude && name.includes('include/');
|
||||
};
|
||||
|
||||
stream.pipeline(
|
||||
fs.createReadStream(tarPath),
|
||||
verifyIntegrity(platformAndArch),
|
||||
new zlib.BrotliDecompress(),
|
||||
tarFs.extract(versionedVendorPath, { ignore }),
|
||||
function (err) {
|
||||
if (err) {
|
||||
if (/unexpected end of file/.test(err.message)) {
|
||||
fail(new Error(`Please delete ${tarPath} as it is not a valid tarball`));
|
||||
}
|
||||
fail(err);
|
||||
}
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
try {
|
||||
const useGlobalLibvips = libvips.useGlobalLibvips();
|
||||
|
||||
if (useGlobalLibvips) {
|
||||
const globalLibvipsVersion = libvips.globalLibvipsVersion();
|
||||
libvips.log(`Detected globally-installed libvips v${globalLibvipsVersion}`);
|
||||
libvips.log('Building from source via node-gyp');
|
||||
process.exit(1);
|
||||
} else if (libvips.hasVendoredLibvips()) {
|
||||
libvips.log(`Using existing vendored libvips v${minimumLibvipsVersion}`);
|
||||
} else {
|
||||
// Is this arch/platform supported?
|
||||
const arch = process.env.npm_config_arch || process.arch;
|
||||
const platformAndArch = platform();
|
||||
if (arch === 'ia32' && !platformAndArch.startsWith('win32')) {
|
||||
throw new Error(`Intel Architecture 32-bit systems require manual installation of libvips >= ${minimumLibvipsVersion}`);
|
||||
}
|
||||
if (platformAndArch === 'freebsd-x64' || platformAndArch === 'openbsd-x64' || platformAndArch === 'sunos-x64') {
|
||||
throw new Error(`BSD/SunOS systems require manual installation of libvips >= ${minimumLibvipsVersion}`);
|
||||
}
|
||||
// Linux libc version check
|
||||
const libcFamily = detectLibc.familySync();
|
||||
const libcVersion = detectLibc.versionSync();
|
||||
if (libcFamily === detectLibc.GLIBC && libcVersion && minimumGlibcVersionByArch[arch]) {
|
||||
const libcVersionWithoutPatch = libcVersion.split('.').slice(0, 2).join('.');
|
||||
if (semverLessThan(`${libcVersionWithoutPatch}.0`, `${minimumGlibcVersionByArch[arch]}.0`)) {
|
||||
handleError(new Error(`Use with glibc ${libcVersion} requires manual installation of libvips >= ${minimumLibvipsVersion}`));
|
||||
}
|
||||
}
|
||||
if (libcFamily === detectLibc.MUSL && libcVersion) {
|
||||
if (semverLessThan(libcVersion, '1.1.24')) {
|
||||
handleError(new Error(`Use with musl ${libcVersion} requires manual installation of libvips >= ${minimumLibvipsVersion}`));
|
||||
}
|
||||
}
|
||||
// Node.js minimum version check
|
||||
const supportedNodeVersion = process.env.npm_package_engines_node || require('../package.json').engines.node;
|
||||
if (!semverSatisfies(process.versions.node, supportedNodeVersion)) {
|
||||
handleError(new Error(`Expected Node.js version ${supportedNodeVersion} but found ${process.versions.node}`));
|
||||
}
|
||||
// Download to per-process temporary file
|
||||
const tarFilename = ['libvips', minimumLibvipsVersionLabelled, platformAndArch].join('-') + '.tar.br';
|
||||
const tarPathCache = path.join(libvips.cachePath(), tarFilename);
|
||||
if (fs.existsSync(tarPathCache)) {
|
||||
libvips.log(`Using cached ${tarPathCache}`);
|
||||
extractTarball(tarPathCache, platformAndArch);
|
||||
} else if (localLibvipsDir) {
|
||||
// If localLibvipsDir is given try to use binaries from local directory
|
||||
const tarPathLocal = path.join(path.resolve(localLibvipsDir), `v${minimumLibvipsVersionLabelled}`, tarFilename);
|
||||
libvips.log(`Using local libvips from ${tarPathLocal}`);
|
||||
extractTarball(tarPathLocal, platformAndArch);
|
||||
} else {
|
||||
const url = distBaseUrl + tarFilename;
|
||||
libvips.log(`Downloading ${url}`);
|
||||
simpleGet({ url: url, agent: agent(libvips.log) }, function (err, response) {
|
||||
if (err) {
|
||||
fail(err);
|
||||
} else if (response.statusCode === 404) {
|
||||
fail(new Error(`Prebuilt libvips ${minimumLibvipsVersion} binaries are not yet available for ${platformAndArch}`));
|
||||
} else if (response.statusCode !== 200) {
|
||||
fail(new Error(`Status ${response.statusCode} ${response.statusMessage}`));
|
||||
} else {
|
||||
const tarPathTemp = path.join(os.tmpdir(), `${process.pid}-${tarFilename}`);
|
||||
const tmpFileStream = fs.createWriteStream(tarPathTemp);
|
||||
response
|
||||
.on('error', function (err) {
|
||||
tmpFileStream.destroy(err);
|
||||
})
|
||||
.on('close', function () {
|
||||
if (!response.complete) {
|
||||
tmpFileStream.destroy(new Error('Download incomplete (connection was terminated)'));
|
||||
}
|
||||
})
|
||||
.pipe(tmpFileStream);
|
||||
tmpFileStream
|
||||
.on('error', function (err) {
|
||||
// Clean up temporary file
|
||||
try {
|
||||
fs.unlinkSync(tarPathTemp);
|
||||
} catch (e) {}
|
||||
fail(err);
|
||||
})
|
||||
.on('close', function () {
|
||||
try {
|
||||
// Attempt to rename
|
||||
fs.renameSync(tarPathTemp, tarPathCache);
|
||||
} catch (err) {
|
||||
// Fall back to copy and unlink
|
||||
fs.copyFileSync(tarPathTemp, tarPathCache);
|
||||
fs.unlinkSync(tarPathTemp);
|
||||
}
|
||||
extractTarball(tarPathCache, platformAndArch);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
}
|
44
lib/agent.js
Normal file
@ -0,0 +1,44 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const url = require('url');
|
||||
const tunnelAgent = require('tunnel-agent');
|
||||
|
||||
const is = require('./is');
|
||||
|
||||
const proxies = [
|
||||
'HTTPS_PROXY',
|
||||
'https_proxy',
|
||||
'HTTP_PROXY',
|
||||
'http_proxy',
|
||||
'npm_config_https_proxy',
|
||||
'npm_config_proxy'
|
||||
];
|
||||
|
||||
function env (key) {
|
||||
return process.env[key];
|
||||
}
|
||||
|
||||
module.exports = function (log) {
|
||||
try {
|
||||
const proxy = new url.URL(proxies.map(env).find(is.string));
|
||||
const tunnel = proxy.protocol === 'https:'
|
||||
? tunnelAgent.httpsOverHttps
|
||||
: tunnelAgent.httpsOverHttp;
|
||||
const proxyAuth = proxy.username && proxy.password
|
||||
? `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`
|
||||
: null;
|
||||
log(`Via proxy ${proxy.protocol}://${proxy.hostname}:${proxy.port} ${proxyAuth ? 'with' : 'no'} credentials`);
|
||||
return tunnel({
|
||||
proxy: {
|
||||
port: Number(proxy.port),
|
||||
host: proxy.hostname,
|
||||
proxyAuth
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
return null;
|
||||
}
|
||||
};
|
@ -16,7 +16,7 @@ const bool = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove alpha channels, if any. This is a no-op if the image does not have an alpha channel.
|
||||
* Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel.
|
||||
*
|
||||
* See also {@link /api-operation#flatten|flatten}.
|
||||
*
|
||||
@ -158,7 +158,6 @@ function bandbool (boolOp) {
|
||||
|
||||
/**
|
||||
* Decorate the Sharp prototype with channel-related functions.
|
||||
* @module Sharp
|
||||
* @private
|
||||
*/
|
||||
module.exports = function (Sharp) {
|
||||
|
@ -19,7 +19,7 @@ const colourspace = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Tint the image using the provided colour.
|
||||
* Tint the image using the provided chroma while preserving the image luminance.
|
||||
* An alpha channel may be present and will be unchanged by the operation.
|
||||
*
|
||||
* @example
|
||||
@ -27,21 +27,23 @@ const colourspace = {
|
||||
* .tint({ r: 255, g: 240, b: 16 })
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {string|Object} tint - Parsed by the [color](https://www.npmjs.org/package/color) module.
|
||||
* @param {string|Object} rgb - parsed by the [color](https://www.npmjs.org/package/color) module to extract chroma values.
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameter
|
||||
*/
|
||||
function tint (tint) {
|
||||
this._setBackgroundColourOption('tint', tint);
|
||||
function tint (rgb) {
|
||||
const colour = color(rgb);
|
||||
this.options.tintA = colour.a();
|
||||
this.options.tintB = colour.b();
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert to 8-bit greyscale; 256 shades of grey.
|
||||
* This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results.
|
||||
* By default the output image will be web-friendly sRGB and contain three (identical) colour channels.
|
||||
* By default the output image will be web-friendly sRGB and contain three (identical) color channels.
|
||||
* This may be overridden by other sharp operations such as `toColourspace('b-w')`,
|
||||
* which will produce an output image containing one colour channel.
|
||||
* which will produce an output image containing one color channel.
|
||||
* An alpha channel may be present, and will be unchanged by the operation.
|
||||
*
|
||||
* @example
|
||||
@ -68,8 +70,9 @@ function grayscale (grayscale) {
|
||||
* Set the pipeline colourspace.
|
||||
*
|
||||
* The input image will be converted to the provided colourspace at the start of the pipeline.
|
||||
* All operations will use this colourspace before converting to the output colourspace,
|
||||
* as defined by {@link #tocolourspace|toColourspace}.
|
||||
* All operations will use this colourspace before converting to the output colourspace, as defined by {@link toColourspace}.
|
||||
*
|
||||
* This feature is experimental and has not yet been fully-tested with all operations.
|
||||
*
|
||||
* @since 0.29.0
|
||||
*
|
||||
@ -88,7 +91,7 @@ function pipelineColourspace (colourspace) {
|
||||
if (!is.string(colourspace)) {
|
||||
throw is.invalidParameterError('colourspace', 'string', colourspace);
|
||||
}
|
||||
this.options.colourspacePipeline = colourspace;
|
||||
this.options.colourspaceInput = colourspace;
|
||||
return this;
|
||||
}
|
||||
|
||||
@ -134,26 +137,6 @@ function toColorspace (colorspace) {
|
||||
return this.toColourspace(colorspace);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a RGBA colour array from a given value.
|
||||
* @private
|
||||
* @param {string|Object} value
|
||||
* @throws {Error} Invalid value
|
||||
*/
|
||||
function _getBackgroundColourOption (value) {
|
||||
if (is.object(value) || is.string(value)) {
|
||||
const colour = color(value);
|
||||
return [
|
||||
colour.red(),
|
||||
colour.green(),
|
||||
colour.blue(),
|
||||
Math.round(colour.alpha() * 255)
|
||||
];
|
||||
} else {
|
||||
throw is.invalidParameterError('background', 'object or string', value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a colour attribute of the this.options Object.
|
||||
* @private
|
||||
@ -163,13 +146,22 @@ function _getBackgroundColourOption (value) {
|
||||
*/
|
||||
function _setBackgroundColourOption (key, value) {
|
||||
if (is.defined(value)) {
|
||||
this.options[key] = _getBackgroundColourOption(value);
|
||||
if (is.object(value) || is.string(value)) {
|
||||
const colour = color(value);
|
||||
this.options[key] = [
|
||||
colour.red(),
|
||||
colour.green(),
|
||||
colour.blue(),
|
||||
Math.round(colour.alpha() * 255)
|
||||
];
|
||||
} else {
|
||||
throw is.invalidParameterError('background', 'object or string', value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decorate the Sharp prototype with colour-related functions.
|
||||
* @module Sharp
|
||||
* @private
|
||||
*/
|
||||
module.exports = function (Sharp) {
|
||||
@ -183,7 +175,6 @@ module.exports = function (Sharp) {
|
||||
toColourspace,
|
||||
toColorspace,
|
||||
// Private
|
||||
_getBackgroundColourOption,
|
||||
_setBackgroundColourOption
|
||||
});
|
||||
// Class attributes
|
||||
|
@ -46,8 +46,8 @@ const blend = {
|
||||
* The images to composite must be the same size or smaller than the processed image.
|
||||
* If both `top` and `left` options are provided, they take precedence over `gravity`.
|
||||
*
|
||||
* Other operations in the same processing pipeline (e.g. resize, rotate, flip,
|
||||
* flop, extract) will always be applied to the input image before composition.
|
||||
* Any resize or rotate operations in the same processing pipeline
|
||||
* will always be applied to the input image before composition.
|
||||
*
|
||||
* The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`,
|
||||
* `dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`,
|
||||
@ -108,15 +108,14 @@ const blend = {
|
||||
* @param {string} [images[].input.text.align='left'] - text alignment (`'left'`, `'centre'`, `'center'`, `'right'`).
|
||||
* @param {boolean} [images[].input.text.justify=false] - set this to true to apply justification to the text.
|
||||
* @param {number} [images[].input.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified.
|
||||
* @param {boolean} [images[].input.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like `<span foreground="red">Red!</span>`.
|
||||
* @param {boolean} [images[].input.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`.
|
||||
* @param {number} [images[].input.text.spacing=0] - text line height in points. Will use the font line height if none is specified.
|
||||
* @param {Boolean} [images[].autoOrient=false] - set to true to use EXIF orientation data, if present, to orient the image.
|
||||
* @param {String} [images[].blend='over'] - how to blend this image with the image below.
|
||||
* @param {String} [images[].gravity='centre'] - gravity at which to place the overlay.
|
||||
* @param {Number} [images[].top] - the pixel offset from the top edge.
|
||||
* @param {Number} [images[].left] - the pixel offset from the left edge.
|
||||
* @param {Boolean} [images[].tile=false] - set to true to repeat the overlay image across the entire image with the given `gravity`.
|
||||
* @param {Boolean} [images[].premultiplied=false] - set to true to avoid premultiplying the image below. Equivalent to the `--premultiplied` vips option.
|
||||
* @param {Boolean} [images[].premultiplied=false] - set to true to avoid premultipling the image below. Equivalent to the `--premultiplied` vips option.
|
||||
* @param {Number} [images[].density=72] - number representing the DPI for vector overlay image.
|
||||
* @param {Object} [images[].raw] - describes overlay when using raw pixel data.
|
||||
* @param {Number} [images[].raw.width]
|
||||
@ -203,7 +202,6 @@ function composite (images) {
|
||||
|
||||
/**
|
||||
* Decorate the Sharp prototype with composite-related functions.
|
||||
* @module Sharp
|
||||
* @private
|
||||
*/
|
||||
module.exports = function (Sharp) {
|
||||
|
@ -3,10 +3,11 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
const util = require('node:util');
|
||||
const stream = require('node:stream');
|
||||
const util = require('util');
|
||||
const stream = require('stream');
|
||||
const is = require('./is');
|
||||
|
||||
require('./libvips').hasVendoredLibvips();
|
||||
require('./sharp');
|
||||
|
||||
// Use NODE_DEBUG=sharp to enable libvips warnings
|
||||
@ -22,10 +23,6 @@ const debuglog = util.debuglog('sharp');
|
||||
*
|
||||
* Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.
|
||||
*
|
||||
* When loading more than one page/frame of an animated image,
|
||||
* these are combined as a vertically-stacked "toilet roll" image
|
||||
* where the overall height is the `pageHeight` multiplied by the number of `pages`.
|
||||
*
|
||||
* @constructs Sharp
|
||||
*
|
||||
* @emits Sharp#info
|
||||
@ -40,21 +37,19 @@ const debuglog = util.debuglog('sharp');
|
||||
* });
|
||||
*
|
||||
* @example
|
||||
* // Read image data from remote URL,
|
||||
* // Read image data from readableStream,
|
||||
* // resize to 300 pixels wide,
|
||||
* // emit an 'info' event with calculated dimensions
|
||||
* // and finally write image data to writableStream
|
||||
* const { body } = fetch('https://...');
|
||||
* const readableStream = Readable.fromWeb(body);
|
||||
* const transformer = sharp()
|
||||
* var transformer = sharp()
|
||||
* .resize(300)
|
||||
* .on('info', ({ height }) => {
|
||||
* console.log(`Image height is ${height}`);
|
||||
* .on('info', function(info) {
|
||||
* console.log('Image height is ' + info.height);
|
||||
* });
|
||||
* readableStream.pipe(transformer).pipe(writableStream);
|
||||
*
|
||||
* @example
|
||||
* // Create a blank 300x200 PNG image of semi-translucent red pixels
|
||||
* // Create a blank 300x200 PNG image of semi-transluent red pixels
|
||||
* sharp({
|
||||
* create: {
|
||||
* width: 300,
|
||||
@ -121,38 +116,24 @@ const debuglog = util.debuglog('sharp');
|
||||
* }
|
||||
* }).toFile('text_rgba.png');
|
||||
*
|
||||
* @example
|
||||
* // Join four input images as a 2x2 grid with a 4 pixel gutter
|
||||
* const data = await sharp(
|
||||
* [image1, image2, image3, image4],
|
||||
* { join: { across: 2, shim: 4 } }
|
||||
* ).toBuffer();
|
||||
*
|
||||
* @example
|
||||
* // Generate a two-frame animated image from emoji
|
||||
* const images = ['😀', '😛'].map(text => ({
|
||||
* text: { text, width: 64, height: 64, channels: 4, rgba: true }
|
||||
* }));
|
||||
* await sharp(images, { join: { animated: true } }).toFile('out.gif');
|
||||
*
|
||||
* @param {(Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string|Array)} [input] - if present, can be
|
||||
* @param {(Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string)} [input] - if present, can be
|
||||
* a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or
|
||||
* a TypedArray containing raw pixel image data, or
|
||||
* a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file.
|
||||
* An array of inputs can be provided, and these will be joined together.
|
||||
* JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present.
|
||||
* @param {Object} [options] - if present, is an Object with optional attributes.
|
||||
* @param {string} [options.failOn='warning'] - When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort.
|
||||
* @param {string} [options.failOn='warning'] - when to abort processing of invalid pixel data, one of (in order of sensitivity): 'none' (least), 'truncated', 'error' or 'warning' (most), highers level imply lower levels, invalid metadata will always abort.
|
||||
* @param {number|boolean} [options.limitInputPixels=268402689] - Do not process input images where the number of pixels
|
||||
* (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted.
|
||||
* An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF).
|
||||
* @param {boolean} [options.unlimited=false] - Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF).
|
||||
* @param {boolean} [options.autoOrient=false] - Set this to `true` to rotate/flip the image to match EXIF `Orientation`, if any.
|
||||
* @param {boolean} [options.sequentialRead=true] - Set this to `false` to use random access rather than sequential read. Some operations will do this automatically.
|
||||
* @param {number} [options.density=72] - number representing the DPI for vector images in the range 1 to 100000.
|
||||
* @param {number} [options.ignoreIcc=false] - should the embedded ICC profile, if any, be ignored.
|
||||
* @param {number} [options.pages=1] - Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages.
|
||||
* @param {number} [options.page=0] - Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based.
|
||||
* @param {number} [options.subifd=-1] - subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image.
|
||||
* @param {number} [options.level=0] - level to extract from a multi-level input (OpenSlide), zero based.
|
||||
* @param {boolean} [options.animated=false] - Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`.
|
||||
* @param {Object} [options.raw] - describes raw pixel input image data. See `raw()` for pixel ordering.
|
||||
* @param {number} [options.raw.width] - integral number of pixels wide.
|
||||
@ -160,47 +141,27 @@ const debuglog = util.debuglog('sharp');
|
||||
* @param {number} [options.raw.channels] - integral number of channels, between 1 and 4.
|
||||
* @param {boolean} [options.raw.premultiplied] - specifies that the raw input has already been premultiplied, set to `true`
|
||||
* to avoid sharp premultiplying the image. (optional, default `false`)
|
||||
* @param {number} [options.raw.pageHeight] - The pixel height of each page/frame for animated images, must be an integral factor of `raw.height`.
|
||||
* @param {Object} [options.create] - describes a new image to be created.
|
||||
* @param {number} [options.create.width] - integral number of pixels wide.
|
||||
* @param {number} [options.create.height] - integral number of pixels high.
|
||||
* @param {number} [options.create.channels] - integral number of channels, either 3 (RGB) or 4 (RGBA).
|
||||
* @param {string|Object} [options.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
|
||||
* @param {number} [options.create.pageHeight] - The pixel height of each page/frame for animated images, must be an integral factor of `create.height`.
|
||||
* @param {Object} [options.create.noise] - describes a noise to be created.
|
||||
* @param {string} [options.create.noise.type] - type of generated noise, currently only `gaussian` is supported.
|
||||
* @param {number} [options.create.noise.mean=128] - Mean value of pixels in the generated noise.
|
||||
* @param {number} [options.create.noise.sigma=30] - Standard deviation of pixel values in the generated noise.
|
||||
* @param {number} [options.create.noise.mean] - mean of pixels in generated noise.
|
||||
* @param {number} [options.create.noise.sigma] - standard deviation of pixels in generated noise.
|
||||
* @param {Object} [options.text] - describes a new text image to be created.
|
||||
* @param {string} [options.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.
|
||||
* @param {string} [options.text.font] - font name to render with.
|
||||
* @param {string} [options.text.fontfile] - absolute filesystem path to a font file that can be used by `font`.
|
||||
* @param {number} [options.text.width=0] - Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries.
|
||||
* @param {number} [options.text.height=0] - Maximum integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0.
|
||||
* @param {string} [options.text.align='left'] - Alignment style for multi-line text (`'left'`, `'centre'`, `'center'`, `'right'`).
|
||||
* @param {number} [options.text.width=0] - integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries.
|
||||
* @param {number} [options.text.height=0] - integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0.
|
||||
* @param {string} [options.text.align='left'] - text alignment (`'left'`, `'centre'`, `'center'`, `'right'`).
|
||||
* @param {boolean} [options.text.justify=false] - set this to true to apply justification to the text.
|
||||
* @param {number} [options.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified.
|
||||
* @param {boolean} [options.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`.
|
||||
* @param {number} [options.text.spacing=0] - text line height in points. Will use the font line height if none is specified.
|
||||
* @param {string} [options.text.wrap='word'] - word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'.
|
||||
* @param {Object} [options.join] - describes how an array of input images should be joined.
|
||||
* @param {number} [options.join.across=1] - number of images to join horizontally.
|
||||
* @param {boolean} [options.join.animated=false] - set this to `true` to join the images as an animated image.
|
||||
* @param {number} [options.join.shim=0] - number of pixels to insert between joined images.
|
||||
* @param {string|Object} [options.join.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
|
||||
* @param {string} [options.join.halign='left'] - horizontal alignment style for images joined horizontally (`'left'`, `'centre'`, `'center'`, `'right'`).
|
||||
* @param {string} [options.join.valign='top'] - vertical alignment style for images joined vertically (`'top'`, `'centre'`, `'center'`, `'bottom'`).
|
||||
* @param {Object} [options.tiff] - Describes TIFF specific options.
|
||||
* @param {number} [options.tiff.subifd=-1] - Sub Image File Directory to extract for OME-TIFF, defaults to main image.
|
||||
* @param {Object} [options.svg] - Describes SVG specific options.
|
||||
* @param {string} [options.svg.stylesheet] - Custom CSS for SVG input, applied with a User Origin during the CSS cascade.
|
||||
* @param {boolean} [options.svg.highBitdepth=false] - Set to `true` to render SVG input at 32-bits per channel (128-bit) instead of 8-bits per channel (32-bit) RGBA.
|
||||
* @param {Object} [options.pdf] - Describes PDF specific options. Requires the use of a globally-installed libvips compiled with support for PDFium, Poppler, ImageMagick or GraphicsMagick.
|
||||
* @param {string|Object} [options.pdf.background] - Background colour to use when PDF is partially transparent. Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
|
||||
* @param {Object} [options.openSlide] - Describes OpenSlide specific options. Requires the use of a globally-installed libvips compiled with support for OpenSlide.
|
||||
* @param {number} [options.openSlide.level=0] - Level to extract from a multi-level input, zero based.
|
||||
* @param {Object} [options.jp2] - Describes JPEG 2000 specific options. Requires the use of a globally-installed libvips compiled with support for OpenJPEG.
|
||||
* @param {boolean} [options.jp2.oneshot=false] - Set to `true` to decode tiled JPEG 2000 images in a single operation, improving compatibility.
|
||||
* @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'.
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
@ -227,6 +188,7 @@ const Sharp = function (input, options) {
|
||||
canvas: 'crop',
|
||||
position: 0,
|
||||
resizeBackground: [0, 0, 0, 255],
|
||||
useExifOrientation: false,
|
||||
angle: 0,
|
||||
rotationAngle: 0,
|
||||
rotationBackground: [0, 0, 0, 255],
|
||||
@ -251,16 +213,14 @@ const Sharp = function (input, options) {
|
||||
kernel: 'lanczos3',
|
||||
fastShrinkOnLoad: true,
|
||||
// operations
|
||||
tint: [-1, 0, 0, 0],
|
||||
tintA: 128,
|
||||
tintB: 128,
|
||||
flatten: false,
|
||||
flattenBackground: [0, 0, 0],
|
||||
unflatten: false,
|
||||
negate: false,
|
||||
negateAlpha: true,
|
||||
medianSize: 0,
|
||||
blurSigma: 0,
|
||||
precision: 'integer',
|
||||
minAmpl: 0.2,
|
||||
sharpenSigma: 0,
|
||||
sharpenM1: 1,
|
||||
sharpenM2: 2,
|
||||
@ -270,10 +230,7 @@ const Sharp = function (input, options) {
|
||||
threshold: 0,
|
||||
thresholdGrayscale: true,
|
||||
trimBackground: [],
|
||||
trimThreshold: -1,
|
||||
trimLineArt: false,
|
||||
dilateWidth: 0,
|
||||
erodeWidth: 0,
|
||||
trimThreshold: 0,
|
||||
gamma: 0,
|
||||
gammaOut: 0,
|
||||
greyscale: false,
|
||||
@ -294,22 +251,18 @@ const Sharp = function (input, options) {
|
||||
removeAlpha: false,
|
||||
ensureAlpha: -1,
|
||||
colourspace: 'srgb',
|
||||
colourspacePipeline: 'last',
|
||||
colourspaceInput: 'last',
|
||||
composite: [],
|
||||
// output
|
||||
fileOut: '',
|
||||
formatOut: 'input',
|
||||
streamOut: false,
|
||||
keepMetadata: 0,
|
||||
withMetadata: false,
|
||||
withMetadataOrientation: -1,
|
||||
withMetadataDensity: 0,
|
||||
withIccProfile: '',
|
||||
withExif: {},
|
||||
withExifMerge: true,
|
||||
withXmp: '',
|
||||
withMetadataIcc: '',
|
||||
withMetadataStrs: {},
|
||||
resolveWithObject: false,
|
||||
loop: -1,
|
||||
delay: [],
|
||||
// output format
|
||||
jpegQuality: 80,
|
||||
jpegProgressive: false,
|
||||
@ -337,8 +290,6 @@ const Sharp = function (input, options) {
|
||||
webpLossless: false,
|
||||
webpNearLossless: false,
|
||||
webpSmartSubsample: false,
|
||||
webpSmartDeblock: false,
|
||||
webpPreset: 'default',
|
||||
webpEffort: 4,
|
||||
webpMinSize: false,
|
||||
webpMixed: false,
|
||||
@ -347,14 +298,12 @@ const Sharp = function (input, options) {
|
||||
gifDither: 1,
|
||||
gifInterFrameMaxError: 0,
|
||||
gifInterPaletteMaxError: 3,
|
||||
gifKeepDuplicateFrames: false,
|
||||
gifReuse: true,
|
||||
gifProgressive: false,
|
||||
tiffQuality: 80,
|
||||
tiffCompression: 'jpeg',
|
||||
tiffPredictor: 'horizontal',
|
||||
tiffPyramid: false,
|
||||
tiffMiniswhite: false,
|
||||
tiffBitdepth: 8,
|
||||
tiffTile: false,
|
||||
tiffTileHeight: 256,
|
||||
@ -367,7 +316,6 @@ const Sharp = function (input, options) {
|
||||
heifCompression: 'av1',
|
||||
heifEffort: 4,
|
||||
heifChromaSubsampling: '4:4:4',
|
||||
heifBitdepth: 8,
|
||||
jxlDistance: 1,
|
||||
jxlDecodingTier: 0,
|
||||
jxlEffort: 7,
|
||||
@ -388,7 +336,6 @@ const Sharp = function (input, options) {
|
||||
timeoutSeconds: 0,
|
||||
linearA: [],
|
||||
linearB: [],
|
||||
pdfBackground: [255, 255, 255, 255],
|
||||
// Function to notify of libvips warnings
|
||||
debuglog: warning => {
|
||||
this.emit('warning', warning);
|
||||
@ -469,16 +416,13 @@ Object.setPrototypeOf(Sharp, stream.Duplex);
|
||||
function clone () {
|
||||
// Clone existing options
|
||||
const clone = this.constructor.call();
|
||||
const { debuglog, queueListener, ...options } = this.options;
|
||||
clone.options = structuredClone(options);
|
||||
clone.options.debuglog = debuglog;
|
||||
clone.options.queueListener = queueListener;
|
||||
clone.options = Object.assign({}, this.options);
|
||||
// Pass 'finish' event to clone for Stream-based input
|
||||
if (this._isStreamInput()) {
|
||||
this.on('finish', () => {
|
||||
// Clone inherits input data
|
||||
this._flattenBufferIn();
|
||||
clone.options.input.buffer = this.options.input.buffer;
|
||||
clone.options.bufferIn = this.options.bufferIn;
|
||||
clone.emit('finish');
|
||||
});
|
||||
}
|
||||
@ -488,7 +432,6 @@ Object.assign(Sharp.prototype, { clone });
|
||||
|
||||
/**
|
||||
* Export constructor.
|
||||
* @module Sharp
|
||||
* @private
|
||||
*/
|
||||
module.exports = Sharp;
|
||||
|
587
lib/index.d.ts
vendored
@ -40,7 +40,19 @@ import { Duplex } from 'stream';
|
||||
*/
|
||||
declare function sharp(options?: sharp.SharpOptions): sharp.Sharp;
|
||||
declare function sharp(
|
||||
input?: sharp.SharpInput | Array<sharp.SharpInput>,
|
||||
input?:
|
||||
| Buffer
|
||||
| ArrayBuffer
|
||||
| Uint8Array
|
||||
| Uint8ClampedArray
|
||||
| Int8Array
|
||||
| Uint16Array
|
||||
| Int16Array
|
||||
| Uint32Array
|
||||
| Int32Array
|
||||
| Float32Array
|
||||
| Float64Array
|
||||
| string,
|
||||
options?: sharp.SharpOptions,
|
||||
): sharp.Sharp;
|
||||
|
||||
@ -50,35 +62,39 @@ declare namespace sharp {
|
||||
|
||||
/** An Object containing the version numbers of sharp, libvips and its dependencies. */
|
||||
const versions: {
|
||||
aom?: string | undefined;
|
||||
archive?: string | undefined;
|
||||
vips: string;
|
||||
cairo?: string | undefined;
|
||||
cgif?: string | undefined;
|
||||
croco?: string | undefined;
|
||||
exif?: string | undefined;
|
||||
expat?: string | undefined;
|
||||
ffi?: string | undefined;
|
||||
fontconfig?: string | undefined;
|
||||
freetype?: string | undefined;
|
||||
fribidi?: string | undefined;
|
||||
gdkpixbuf?: string | undefined;
|
||||
gif?: string | undefined;
|
||||
glib?: string | undefined;
|
||||
gsf?: string | undefined;
|
||||
harfbuzz?: string | undefined;
|
||||
heif?: string | undefined;
|
||||
highway?: string | undefined;
|
||||
imagequant?: string | undefined;
|
||||
jpeg?: string | undefined;
|
||||
lcms?: string | undefined;
|
||||
mozjpeg?: string | undefined;
|
||||
orc?: string | undefined;
|
||||
pango?: string | undefined;
|
||||
pixman?: string | undefined;
|
||||
png?: string | undefined;
|
||||
"proxy-libintl"?: string | undefined;
|
||||
rsvg?: string | undefined;
|
||||
sharp: string;
|
||||
spng?: string | undefined;
|
||||
sharp?: string | undefined;
|
||||
svg?: string | undefined;
|
||||
tiff?: string | undefined;
|
||||
vips: string;
|
||||
webp?: string | undefined;
|
||||
avif?: string | undefined;
|
||||
heif?: string | undefined;
|
||||
xml?: string | undefined;
|
||||
"zlib-ng"?: string | undefined;
|
||||
zlib?: string | undefined;
|
||||
};
|
||||
|
||||
/** An Object containing the platform and architecture of the current and installed vendored binaries. */
|
||||
const vendor: {
|
||||
current: string;
|
||||
installed: string[];
|
||||
};
|
||||
|
||||
/** An Object containing the available interpolators and their proper values */
|
||||
@ -116,59 +132,13 @@ declare namespace sharp {
|
||||
function counters(): SharpCounters;
|
||||
|
||||
/**
|
||||
* Get and set use of SIMD vector unit instructions. Requires libvips to have been compiled with highway support.
|
||||
* Get and set use of SIMD vector unit instructions. Requires libvips to have been compiled with liborc support.
|
||||
* Improves the performance of resize, blur and sharpen operations by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.
|
||||
* @param enable enable or disable use of SIMD vector unit instructions
|
||||
* @returns true if usage of SIMD vector unit instructions is enabled
|
||||
*/
|
||||
function simd(enable?: boolean): boolean;
|
||||
|
||||
/**
|
||||
* Block libvips operations at runtime.
|
||||
*
|
||||
* This is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable,
|
||||
* which when set will block all "untrusted" operations.
|
||||
*
|
||||
* @since 0.32.4
|
||||
*
|
||||
* @example <caption>Block all TIFF input.</caption>
|
||||
* sharp.block({
|
||||
* operation: ['VipsForeignLoadTiff']
|
||||
* });
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {Array<string>} options.operation - List of libvips low-level operation names to block.
|
||||
*/
|
||||
function block(options: { operation: string[] }): void;
|
||||
|
||||
/**
|
||||
* Unblock libvips operations at runtime.
|
||||
*
|
||||
* This is useful for defining a list of allowed operations.
|
||||
*
|
||||
* @since 0.32.4
|
||||
*
|
||||
* @example <caption>Block all input except WebP from the filesystem.</caption>
|
||||
* sharp.block({
|
||||
* operation: ['VipsForeignLoad']
|
||||
* });
|
||||
* sharp.unblock({
|
||||
* operation: ['VipsForeignLoadWebpFile']
|
||||
* });
|
||||
*
|
||||
* @example <caption>Block all input except JPEG and PNG from a Buffer or Stream.</caption>
|
||||
* sharp.block({
|
||||
* operation: ['VipsForeignLoad']
|
||||
* });
|
||||
* sharp.unblock({
|
||||
* operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer']
|
||||
* });
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {Array<string>} options.operation - List of libvips low-level operation names to unblock.
|
||||
*/
|
||||
function unblock(options: { operation: string[] }): void;
|
||||
|
||||
//#endregion
|
||||
|
||||
const gravity: GravityEnum;
|
||||
@ -229,19 +199,19 @@ declare namespace sharp {
|
||||
//#region Color functions
|
||||
|
||||
/**
|
||||
* Tint the image using the provided colour.
|
||||
* Tint the image using the provided chroma while preserving the image luminance.
|
||||
* An alpha channel may be present and will be unchanged by the operation.
|
||||
* @param tint Parsed by the color module.
|
||||
* @param rgb Parsed by the color module to extract chroma values.
|
||||
* @returns A sharp instance that can be used to chain operations
|
||||
*/
|
||||
tint(tint: Colour | Color): Sharp;
|
||||
tint(rgb: Color): Sharp;
|
||||
|
||||
/**
|
||||
* Convert to 8-bit greyscale; 256 shades of grey.
|
||||
* This is a linear operation.
|
||||
* If the input image is in a non-linear colour space such as sRGB, use gamma() with greyscale() for the best results.
|
||||
* By default the output image will be web-friendly sRGB and contain three (identical) colour channels.
|
||||
* This may be overridden by other sharp operations such as toColourspace('b-w'), which will produce an output image containing one colour channel.
|
||||
* By default the output image will be web-friendly sRGB and contain three (identical) color channels.
|
||||
* This may be overridden by other sharp operations such as toColourspace('b-w'), which will produce an output image containing one color channel.
|
||||
* An alpha channel may be present, and will be unchanged by the operation.
|
||||
* @param greyscale true to enable and false to disable (defaults to true)
|
||||
* @returns A sharp instance that can be used to chain operations
|
||||
@ -331,12 +301,6 @@ declare namespace sharp {
|
||||
*/
|
||||
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.
|
||||
* @returns A sharp instance that can be used to chain operations
|
||||
@ -354,72 +318,24 @@ declare namespace sharp {
|
||||
//#region Operation functions
|
||||
|
||||
/**
|
||||
* Rotate the output image by either an explicit angle
|
||||
* or auto-orient based on the EXIF `Orientation` tag.
|
||||
* Rotate the output image by either an explicit angle or auto-orient based on the EXIF Orientation tag.
|
||||
*
|
||||
* If an angle is provided, it is converted to a valid positive degree rotation.
|
||||
* For example, `-450` will produce a 270 degree rotation.
|
||||
* If an angle is provided, it is converted to a valid positive degree rotation. For example, -450 will produce a 270deg rotation.
|
||||
*
|
||||
* When rotating by an angle other than a multiple of 90,
|
||||
* the background colour can be provided with the `background` option.
|
||||
* When rotating by an angle other than a multiple of 90, the background colour can be provided with the background option.
|
||||
*
|
||||
* If no angle is provided, it is determined from the EXIF data.
|
||||
* Mirroring is supported and may infer the use of a flip operation.
|
||||
* If no angle is provided, it is determined from the EXIF data. Mirroring is supported and may infer the use of a flip operation.
|
||||
*
|
||||
* The use of `rotate` without an angle will remove the EXIF `Orientation` tag, if any.
|
||||
* The use of rotate implies the removal of the EXIF Orientation tag, if any.
|
||||
*
|
||||
* Only one rotation can occur per pipeline (aside from an initial call without
|
||||
* arguments to orient via EXIF data). Previous calls to `rotate` in the same
|
||||
* pipeline will be ignored.
|
||||
*
|
||||
* Multi-page images can only be rotated by 180 degrees.
|
||||
*
|
||||
* Method order is important when rotating, resizing and/or extracting regions,
|
||||
* for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.
|
||||
*
|
||||
* @example
|
||||
* const pipeline = sharp()
|
||||
* .rotate()
|
||||
* .resize(null, 200)
|
||||
* .toBuffer(function (err, outputBuffer, info) {
|
||||
* // outputBuffer contains 200px high JPEG image data,
|
||||
* // auto-rotated using EXIF Orientation tag
|
||||
* // info.width and info.height contain the dimensions of the resized image
|
||||
* });
|
||||
* readableStream.pipe(pipeline);
|
||||
*
|
||||
* @example
|
||||
* const rotateThenResize = await sharp(input)
|
||||
* .rotate(90)
|
||||
* .resize({ width: 16, height: 8, fit: 'fill' })
|
||||
* .toBuffer();
|
||||
* const resizeThenRotate = await sharp(input)
|
||||
* .resize({ width: 16, height: 8, fit: 'fill' })
|
||||
* .rotate(90)
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {number} [angle=auto] angle of rotation.
|
||||
* @param {Object} [options] - if present, is an Object with optional attributes.
|
||||
* @param {string|Object} [options.background="#000000"] parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.
|
||||
* @returns {Sharp}
|
||||
* Method order is important when both rotating and extracting regions, for example rotate(x).extract(y) will produce a different result to extract(y).rotate(x).
|
||||
* @param angle angle of rotation. (optional, default auto)
|
||||
* @param options if present, is an Object with optional attributes.
|
||||
* @throws {Error} Invalid parameters
|
||||
* @returns A sharp instance that can be used to chain operations
|
||||
*/
|
||||
rotate(angle?: number, options?: RotateOptions): Sharp;
|
||||
|
||||
/**
|
||||
* Alias for calling `rotate()` with no arguments, which orients the image based
|
||||
* on EXIF orientsion.
|
||||
*
|
||||
* This operation is aliased to emphasize its purpose, helping to remove any
|
||||
* confusion between rotation and orientation.
|
||||
*
|
||||
* @example
|
||||
* const output = await sharp(input).autoOrient().toBuffer();
|
||||
*
|
||||
* @returns {Sharp}
|
||||
*/
|
||||
autoOrient(): Sharp
|
||||
|
||||
/**
|
||||
* Flip the image about the vertical Y axis. This always occurs after rotation, if any.
|
||||
* The use of flip implies the removal of the EXIF Orientation tag, if any.
|
||||
@ -439,8 +355,8 @@ declare namespace sharp {
|
||||
/**
|
||||
* Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.
|
||||
* You must provide an array of length 4 or a 2x2 affine transformation matrix.
|
||||
* By default, new pixels are filled with a black background. You can provide a background colour with the `background` option.
|
||||
* A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`.
|
||||
* By default, new pixels are filled with a black background. You can provide a background color with the `background` option.
|
||||
* A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolator` Object e.g. `sharp.interpolator.nohalo`.
|
||||
*
|
||||
* In the case of a 2x2 matrix, the transform is:
|
||||
* X = matrix[0, 0] * (x + idx) + matrix[0, 1] * (y + idy) + odx
|
||||
@ -502,23 +418,7 @@ declare namespace sharp {
|
||||
* @throws {Error} Invalid parameters
|
||||
* @returns A sharp instance that can be used to chain operations
|
||||
*/
|
||||
blur(sigma?: number | boolean | BlurOptions): Sharp;
|
||||
|
||||
/**
|
||||
* Expand foreground objects using the dilate morphological operator.
|
||||
* @param {Number} [width=1] dilation width in pixels.
|
||||
* @throws {Error} Invalid parameters
|
||||
* @returns A sharp instance that can be used to chain operations
|
||||
*/
|
||||
dilate(width?: number): Sharp;
|
||||
|
||||
/**
|
||||
* Shrink foreground objects using the erode morphological operator.
|
||||
* @param {Number} [width=1] erosion width in pixels.
|
||||
* @throws {Error} Invalid parameters
|
||||
* @returns A sharp instance that can be used to chain operations
|
||||
*/
|
||||
erode(width?: number): Sharp;
|
||||
blur(sigma?: number | boolean): Sharp;
|
||||
|
||||
/**
|
||||
* Merge alpha transparency channel, if any, with background.
|
||||
@ -527,13 +427,6 @@ declare namespace sharp {
|
||||
*/
|
||||
flatten(flatten?: boolean | FlattenOptions): Sharp;
|
||||
|
||||
/**
|
||||
* Ensure the image has an alpha channel with all white pixel values made fully transparent.
|
||||
* Existing alpha channel values for non-white pixels remain unchanged.
|
||||
* @returns A sharp instance that can be used to chain operations
|
||||
*/
|
||||
unflatten(): Sharp;
|
||||
|
||||
/**
|
||||
* Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of 1/gamma then increasing the encoding (brighten) post-resize at a factor of gamma.
|
||||
* This can improve the perceived brightness of a resized image in non-linear colour spaces.
|
||||
@ -625,11 +518,11 @@ declare namespace sharp {
|
||||
|
||||
/**
|
||||
* Recomb the image with the specified matrix.
|
||||
* @param inputMatrix 3x3 Recombination matrix or 4x4 Recombination matrix
|
||||
* @param inputMatrix 3x3 Recombination matrix
|
||||
* @throws {Error} Invalid parameters
|
||||
* @returns A sharp instance that can be used to chain operations
|
||||
*/
|
||||
recomb(inputMatrix: Matrix3x3 | Matrix4x4): Sharp;
|
||||
recomb(inputMatrix: Matrix3x3): Sharp;
|
||||
|
||||
/**
|
||||
* Transforms the image using brightness, saturation, hue rotation and lightness.
|
||||
@ -693,57 +586,6 @@ declare namespace sharp {
|
||||
*/
|
||||
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;
|
||||
|
||||
/**
|
||||
* Keep all XMP metadata from the input image in the output image.
|
||||
* @returns A sharp instance that can be used to chain operations
|
||||
*/
|
||||
keepXmp(): Sharp;
|
||||
|
||||
/**
|
||||
* Set XMP metadata in the output image.
|
||||
* @param {string} xmp - String containing XMP metadata to be embedded in the output image.
|
||||
* @returns A sharp instance that can be used to chain operations
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
withXmp(xmp: string): Sharp;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
@ -810,6 +652,7 @@ declare namespace sharp {
|
||||
|
||||
/**
|
||||
* Use these AVIF options for output image.
|
||||
* Whilst it is possible to create AVIF images smaller than 16x16 pixels, most web browsers do not display these properly.
|
||||
* @param options Output options.
|
||||
* @throws {Error} Invalid options
|
||||
* @returns A sharp instance that can be used to chain operations
|
||||
@ -867,6 +710,8 @@ declare namespace sharp {
|
||||
* Use tile-based deep zoom (image pyramid) output.
|
||||
* Set the format and options for tile images via the toFormat, jpeg, png or webp functions.
|
||||
* Use a .zip or .szi file extension with toFile to write to a compressed archive file format.
|
||||
*
|
||||
* Warning: multiple sharp instances concurrently producing tile output can expose a possible race condition in some versions of libgsf.
|
||||
* @param tile tile options
|
||||
* @throws {Error} Invalid options
|
||||
* @returns A sharp instance that can be used to chain operations
|
||||
@ -956,36 +801,16 @@ 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.
|
||||
* 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.
|
||||
* @param options trim options
|
||||
* @param trim The specific background colour to trim, the threshold for doing so or an Object with both.
|
||||
* @throws {Error} Invalid parameters
|
||||
* @returns A sharp instance that can be used to chain operations
|
||||
*/
|
||||
trim(options?: TrimOptions): Sharp;
|
||||
trim(trim?: string | number | TrimOptions): Sharp;
|
||||
|
||||
//#endregion
|
||||
}
|
||||
|
||||
type SharpInput = Buffer
|
||||
| ArrayBuffer
|
||||
| Uint8Array
|
||||
| Uint8ClampedArray
|
||||
| Int8Array
|
||||
| Uint16Array
|
||||
| Int16Array
|
||||
| Uint32Array
|
||||
| Int32Array
|
||||
| Float32Array
|
||||
| Float64Array
|
||||
| string;
|
||||
|
||||
interface SharpOptions {
|
||||
/**
|
||||
* Auto-orient based on the EXIF `Orientation` tag, if present.
|
||||
* Mirroring is supported and may infer the use of a flip operation.
|
||||
*
|
||||
* Using this option will remove the EXIF `Orientation` tag, if any.
|
||||
*/
|
||||
autoOrient?: boolean | undefined;
|
||||
/**
|
||||
* When to abort processing of invalid pixel data, one of (in order of sensitivity):
|
||||
* 'none' (least), 'truncated', 'error' or 'warning' (most), highers level imply lower levels, invalid metadata will always abort. (optional, default 'warning')
|
||||
@ -1017,21 +842,9 @@ declare namespace sharp {
|
||||
pages?: number | undefined;
|
||||
/** Page number to start extracting from for multi-page input (GIF, TIFF, PDF), zero based. (optional, default 0) */
|
||||
page?: number | undefined;
|
||||
/** TIFF specific input options */
|
||||
tiff?: TiffInputOptions | undefined;
|
||||
/** SVG specific input options */
|
||||
svg?: SvgInputOptions | undefined;
|
||||
/** PDF specific input options */
|
||||
pdf?: PdfInputOptions | undefined;
|
||||
/** OpenSlide specific input options */
|
||||
openSlide?: OpenSlideInputOptions | undefined;
|
||||
/** JPEG 2000 specific input options */
|
||||
jp2?: Jp2InputOptions | undefined;
|
||||
/** Deprecated: use tiff.subifd instead */
|
||||
/** subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. (optional, default -1) */
|
||||
subifd?: number | undefined;
|
||||
/** Deprecated: use pdf.background instead */
|
||||
pdfBackground?: Colour | Color | undefined;
|
||||
/** Deprecated: use openSlide.level instead */
|
||||
/** Level to extract from a multi-level input (OpenSlide), zero based. (optional, default 0) */
|
||||
level?: number | undefined;
|
||||
/** Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). (optional, default false) */
|
||||
animated?: boolean | undefined;
|
||||
@ -1041,8 +854,6 @@ declare namespace sharp {
|
||||
create?: Create | undefined;
|
||||
/** Describes a new text image to be created. */
|
||||
text?: CreateText | undefined;
|
||||
/** Describes how array of input images should be joined. */
|
||||
join?: Join | undefined;
|
||||
}
|
||||
|
||||
interface CacheOptions {
|
||||
@ -1069,32 +880,25 @@ declare namespace sharp {
|
||||
interface Raw {
|
||||
width: number;
|
||||
height: number;
|
||||
channels: Channels;
|
||||
channels: 1 | 2 | 3 | 4;
|
||||
}
|
||||
|
||||
interface CreateRaw extends Raw {
|
||||
/** Specifies that the raw input has already been premultiplied, set to true to avoid sharp premultiplying the image. (optional, default false) */
|
||||
premultiplied?: boolean | undefined;
|
||||
/** The height of each page/frame for animated images, must be an integral factor of the overall image height. */
|
||||
pageHeight?: number | undefined;
|
||||
}
|
||||
|
||||
type CreateChannels = 3 | 4;
|
||||
|
||||
interface Create {
|
||||
/** Number of pixels wide. */
|
||||
width: number;
|
||||
/** Number of pixels high. */
|
||||
height: number;
|
||||
/** Number of bands, 3 for RGB, 4 for RGBA */
|
||||
channels: CreateChannels;
|
||||
/** Number of bands e.g. 3 for RGB, 4 for RGBA */
|
||||
channels: Channels;
|
||||
/** Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. */
|
||||
background: Colour | Color;
|
||||
background: Color;
|
||||
/** Describes a noise to be created. */
|
||||
noise?: Noise | undefined;
|
||||
/** The height of each page/frame for animated images, must be an integral factor of the overall image height. */
|
||||
pageHeight?: number | undefined;
|
||||
|
||||
}
|
||||
|
||||
interface CreateText {
|
||||
@ -1124,114 +928,44 @@ declare namespace sharp {
|
||||
rgba?: boolean;
|
||||
/** Text line height in points. Will use the font line height if none is specified. (optional, default `0`) */
|
||||
spacing?: number;
|
||||
/** Word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none' */
|
||||
/** Word wrapping style when width is provided, one of: 'word', 'char', 'charWord' (prefer char, fallback to word) or 'none' */
|
||||
wrap?: TextWrap;
|
||||
}
|
||||
|
||||
interface Join {
|
||||
/** Number of images per row. */
|
||||
across?: number | undefined;
|
||||
/** Treat input as frames of an animated image. */
|
||||
animated?: boolean | undefined;
|
||||
/** Space between images, in pixels. */
|
||||
shim?: number | undefined;
|
||||
/** Background colour. */
|
||||
background?: Colour | Color | undefined;
|
||||
/** Horizontal alignment. */
|
||||
halign?: HorizontalAlignment | undefined;
|
||||
/** Vertical alignment. */
|
||||
valign?: VerticalAlignment | undefined;
|
||||
}
|
||||
|
||||
interface TiffInputOptions {
|
||||
/** Sub Image File Directory to extract, defaults to main image. Use -1 for all subifds. */
|
||||
subifd?: number | undefined;
|
||||
}
|
||||
|
||||
interface SvgInputOptions {
|
||||
/** Custom CSS for SVG input, applied with a User Origin during the CSS cascade. */
|
||||
stylesheet?: string | undefined;
|
||||
/** Set to `true` to render SVG input at 32-bits per channel (128-bit) instead of 8-bits per channel (32-bit) RGBA. */
|
||||
highBitdepth?: boolean | undefined;
|
||||
}
|
||||
|
||||
interface PdfInputOptions {
|
||||
/** Background colour to use when PDF is partially transparent. Requires the use of a globally-installed libvips compiled with support for PDFium, Poppler, ImageMagick or GraphicsMagick. */
|
||||
background?: Colour | Color | undefined;
|
||||
}
|
||||
|
||||
interface OpenSlideInputOptions {
|
||||
/** Level to extract from a multi-level input, zero based. (optional, default 0) */
|
||||
level?: number | undefined;
|
||||
}
|
||||
|
||||
interface Jp2InputOptions {
|
||||
/** Set to `true` to load JPEG 2000 images using [oneshot mode](https://github.com/libvips/libvips/issues/4205) */
|
||||
oneshot?: boolean | undefined;
|
||||
}
|
||||
|
||||
interface ExifDir {
|
||||
[k: string]: string;
|
||||
}
|
||||
|
||||
interface Exif {
|
||||
'IFD0'?: ExifDir;
|
||||
'IFD1'?: ExifDir;
|
||||
'IFD2'?: ExifDir;
|
||||
'IFD3'?: ExifDir;
|
||||
}
|
||||
|
||||
interface WriteableMetadata {
|
||||
/** Number of pixels per inch (DPI) */
|
||||
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.
|
||||
*/
|
||||
/** 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.
|
||||
* @deprecated Use `withExif()` or `withExifMerge()` instead.
|
||||
*/
|
||||
exif?: Exif | 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) */
|
||||
density?: number | undefined;
|
||||
}
|
||||
|
||||
interface Metadata {
|
||||
/** Number value of the EXIF Orientation header, if present */
|
||||
orientation?: number | undefined;
|
||||
/** Name of decoder used to decompress image data e.g. jpeg, png, webp, gif, svg */
|
||||
format: keyof FormatEnum;
|
||||
format?: keyof FormatEnum | undefined;
|
||||
/** Total size of image in bytes, for Stream and Buffer input only */
|
||||
size?: number | undefined;
|
||||
/** Number of pixels wide (EXIF orientation is not taken into consideration) */
|
||||
width: number;
|
||||
width?: number | undefined;
|
||||
/** Number of pixels high (EXIF orientation is not taken into consideration) */
|
||||
height: number;
|
||||
/** Any changed metadata after the image orientation is applied. */
|
||||
autoOrient: {
|
||||
/** Number of pixels wide (EXIF orientation is taken into consideration) */
|
||||
width: number;
|
||||
/** Number of pixels high (EXIF orientation is taken into consideration) */
|
||||
height: number;
|
||||
};
|
||||
height?: number | undefined;
|
||||
/** Name of colour space interpretation */
|
||||
space: keyof ColourspaceEnum;
|
||||
space?: keyof ColourspaceEnum | undefined;
|
||||
/** Number of bands e.g. 3 for sRGB, 4 for CMYK */
|
||||
channels: Channels;
|
||||
channels?: Channels | undefined;
|
||||
/** Name of pixel depth format e.g. uchar, char, ushort, float ... */
|
||||
depth: keyof DepthEnum;
|
||||
depth?: string | undefined;
|
||||
/** Number of pixels per inch (DPI), if present */
|
||||
density?: number | undefined;
|
||||
/** String containing JPEG chroma subsampling, 4:2:0 or 4:4:4 for RGB, 4:2:0:4 or 4:4:4:4 for CMYK */
|
||||
chromaSubsampling?: string | undefined;
|
||||
chromaSubsampling: string;
|
||||
/** Boolean indicating whether the image is interlaced using a progressive scan */
|
||||
isProgressive: boolean;
|
||||
/** Boolean indicating whether the image is palette-based (GIF, PNG). */
|
||||
isPalette: boolean;
|
||||
/** Number of bits per sample for each channel (GIF, PNG). */
|
||||
bitsPerSample?: number | undefined;
|
||||
isProgressive?: boolean | undefined;
|
||||
/** Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP */
|
||||
pages?: number | undefined;
|
||||
/** Number of pixels high each page in a multi-page image will be. */
|
||||
@ -1243,9 +977,9 @@ declare namespace sharp {
|
||||
/** Number of the primary page in a HEIF image */
|
||||
pagePrimary?: number | undefined;
|
||||
/** Boolean indicating the presence of an embedded ICC profile */
|
||||
hasProfile: boolean;
|
||||
hasProfile?: boolean | undefined;
|
||||
/** Boolean indicating the presence of an alpha transparency channel */
|
||||
hasAlpha: boolean;
|
||||
hasAlpha?: boolean | undefined;
|
||||
/** Buffer containing raw EXIF data, if present */
|
||||
exif?: Buffer | undefined;
|
||||
/** Buffer containing raw ICC profile data, if present */
|
||||
@ -1254,14 +988,12 @@ declare namespace sharp {
|
||||
iptc?: Buffer | undefined;
|
||||
/** Buffer containing raw XMP data, if present */
|
||||
xmp?: Buffer | undefined;
|
||||
/** String containing XMP data, if valid UTF-8 */
|
||||
xmpAsString?: string | undefined;
|
||||
/** Buffer containing raw TIFFTAG_PHOTOSHOP data, if present */
|
||||
tifftagPhotoshop?: Buffer | undefined;
|
||||
/** The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC) */
|
||||
compression?: 'av1' | 'hevc';
|
||||
/** Default background colour, if present, for PNG (bKGD) and GIF images */
|
||||
background?: { r: number; g: number; b: number } | { gray: number };
|
||||
/** Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value */
|
||||
background?: { r: number; g: number; b: number } | number;
|
||||
/** Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide */
|
||||
levels?: LevelMetadata[] | undefined;
|
||||
/** Number of Sub Image File Directories in an OME-TIFF image */
|
||||
@ -1270,8 +1002,6 @@ declare namespace sharp {
|
||||
resolutionUnit?: 'inch' | 'cm' | undefined;
|
||||
/** String containing format for images loaded via *magick */
|
||||
formatMagick?: string | undefined;
|
||||
/** Array of keyword/text pairs representing PNG text blocks, if present. */
|
||||
comments?: CommentsMetadata[] | undefined;
|
||||
}
|
||||
|
||||
interface LevelMetadata {
|
||||
@ -1279,11 +1009,6 @@ declare namespace sharp {
|
||||
height: number;
|
||||
}
|
||||
|
||||
interface CommentsMetadata {
|
||||
keyword: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
interface Stats {
|
||||
/** Array of channel statistics for each channel in the image. */
|
||||
channels: ChannelStats[];
|
||||
@ -1325,11 +1050,6 @@ declare namespace sharp {
|
||||
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 {
|
||||
/** Quality, integer 1-100 (optional, default 80) */
|
||||
quality?: number | undefined;
|
||||
@ -1394,16 +1114,12 @@ declare namespace sharp {
|
||||
nearLossless?: boolean | undefined;
|
||||
/** Use high quality chroma subsampling (optional, default false) */
|
||||
smartSubsample?: boolean | undefined;
|
||||
/** Auto-adjust the deblocking filter, slow but can improve low contrast edges (optional, default false) */
|
||||
smartDeblock?: boolean | undefined;
|
||||
/** Level of CPU effort to reduce file size, integer 0-6 (optional, default 4) */
|
||||
effort?: number | undefined;
|
||||
/** Prevent use of animation key frames to minimise file size (slow) (optional, default false) */
|
||||
minSize?: boolean;
|
||||
minSize?: number;
|
||||
/** Allow mixture of lossy and lossless animation frames (slow) (optional, default false) */
|
||||
mixed?: boolean;
|
||||
/** Preset options: one of default, photo, picture, drawing, icon, text (optional, default 'default') */
|
||||
preset?: keyof PresetEnum | undefined;
|
||||
}
|
||||
|
||||
interface AvifOptions extends OutputOptions {
|
||||
@ -1415,8 +1131,6 @@ declare namespace sharp {
|
||||
effort?: number | undefined;
|
||||
/** set to '4:2:0' to use chroma subsampling, requires libvips v8.11.0 (optional, default '4:4:4') */
|
||||
chromaSubsampling?: string | undefined;
|
||||
/** Set bitdepth to 8, 10 or 12 bit (optional, default 8) */
|
||||
bitdepth?: 8 | 10 | 12 | undefined;
|
||||
}
|
||||
|
||||
interface HeifOptions extends OutputOptions {
|
||||
@ -1430,8 +1144,6 @@ declare namespace sharp {
|
||||
effort?: number | undefined;
|
||||
/** set to '4:2:0' to use chroma subsampling (optional, default '4:4:4') */
|
||||
chromaSubsampling?: string | undefined;
|
||||
/** Set bitdepth to 8, 10 or 12 bit (optional, default 8) */
|
||||
bitdepth?: 8 | 10 | 12 | undefined;
|
||||
}
|
||||
|
||||
interface GifOptions extends OutputOptions, AnimationOptions {
|
||||
@ -1448,11 +1160,9 @@ declare namespace sharp {
|
||||
/** Level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) (optional, default 1.0) */
|
||||
dither?: number | undefined;
|
||||
/** Maximum inter-frame error for transparency, between 0 (lossless) and 32 (optional, default 0) */
|
||||
interFrameMaxError?: number | undefined;
|
||||
interFrameMaxError?: number;
|
||||
/** Maximum inter-palette error for palette reuse, between 0 and 256 (optional, default 3) */
|
||||
interPaletteMaxError?: number | undefined;
|
||||
/** Keep duplicate frames in the output instead of combining them (optional, default false) */
|
||||
keepDuplicateFrames?: boolean | undefined;
|
||||
interPaletteMaxError?: number;
|
||||
}
|
||||
|
||||
interface TiffOptions extends OutputOptions {
|
||||
@ -1476,8 +1186,6 @@ declare namespace sharp {
|
||||
yres?: number | undefined;
|
||||
/** Reduce bitdepth to 1, 2 or 4 bit (optional, default 8) */
|
||||
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') */
|
||||
resolutionUnit?: 'inch' | 'cm' | undefined;
|
||||
}
|
||||
@ -1505,23 +1213,12 @@ declare namespace sharp {
|
||||
|
||||
interface RotateOptions {
|
||||
/** parsed by the color module to extract values for red, green, blue and alpha. (optional, default "#000000") */
|
||||
background?: Colour | Color | undefined;
|
||||
}
|
||||
|
||||
type Precision = 'integer' | 'float' | 'approximate';
|
||||
|
||||
interface BlurOptions {
|
||||
/** A value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2` */
|
||||
sigma: number;
|
||||
/** A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask. */
|
||||
minAmplitude?: number;
|
||||
/** How accurate the operation should be, one of: integer, float, approximate. (optional, default "integer") */
|
||||
precision?: Precision | undefined;
|
||||
background?: Color | undefined;
|
||||
}
|
||||
|
||||
interface FlattenOptions {
|
||||
/** background colour, parsed by the color module, defaults to black. (optional, default {r:0,g:0,b:0}) */
|
||||
background?: Colour | Color | undefined;
|
||||
background?: Color | undefined;
|
||||
}
|
||||
|
||||
interface NegateOptions {
|
||||
@ -1530,10 +1227,10 @@ declare namespace sharp {
|
||||
}
|
||||
|
||||
interface NormaliseOptions {
|
||||
/** Percentile below which luminance values will be underexposed. */
|
||||
lower?: number | undefined;
|
||||
/** Percentile above which luminance values will be overexposed. */
|
||||
upper?: number | undefined;
|
||||
/** Percentile below which luminance values will be underexposed. */
|
||||
lower?: number | undefined;
|
||||
/** Percentile above which luminance values will be overexposed. */
|
||||
upper?: number | undefined;
|
||||
}
|
||||
|
||||
interface ResizeOptions {
|
||||
@ -1546,7 +1243,7 @@ declare namespace sharp {
|
||||
/** Position, gravity or strategy to use when fit is cover or contain. (optional, default 'centre') */
|
||||
position?: number | string | undefined;
|
||||
/** Background colour when using a fit of contain, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */
|
||||
background?: Colour | Color | undefined;
|
||||
background?: Color | undefined;
|
||||
/** The kernel to use for image reduction. (optional, default 'lanczos3') */
|
||||
kernel?: keyof KernelEnum | undefined;
|
||||
/** Do not enlarge if the width or height are already less than the specified dimensions, equivalent to GraphicsMagick's > geometry option. (optional, default false) */
|
||||
@ -1570,7 +1267,7 @@ declare namespace sharp {
|
||||
|
||||
interface Noise {
|
||||
/** type of generated noise, currently only gaussian is supported. */
|
||||
type: 'gaussian';
|
||||
type?: 'gaussian' | undefined;
|
||||
/** mean of pixels in generated noise. */
|
||||
mean?: number | undefined;
|
||||
/** standard deviation of pixels in generated noise. */
|
||||
@ -1589,26 +1286,24 @@ declare namespace sharp {
|
||||
/** single pixel count to right edge (optional, default 0) */
|
||||
right?: number | undefined;
|
||||
/** background colour, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */
|
||||
background?: Colour | Color | undefined;
|
||||
background?: Color | undefined;
|
||||
/** how the extension is done, one of: "background", "copy", "repeat", "mirror" (optional, default `'background'`) */
|
||||
extendWith?: ExtendWith | undefined;
|
||||
}
|
||||
|
||||
interface TrimOptions {
|
||||
/** Background colour, parsed by the color module, defaults to that of the top-left pixel. (optional) */
|
||||
background?: Colour | Color | undefined;
|
||||
/** Allowed difference from the above colour, a positive number. (optional, default 10) */
|
||||
/** background colour, parsed by the color module, defaults to that of the top-left pixel. (optional) */
|
||||
background?: Color | undefined;
|
||||
/** the allowed difference from the above colour, a positive number. (optional, default `10`) */
|
||||
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 {
|
||||
depth?: 'char' | 'uchar' | 'short' | 'ushort' | 'int' | 'uint' | 'float' | 'complex' | 'double' | 'dpcomplex';
|
||||
}
|
||||
|
||||
/** 1 for grayscale, 2 for grayscale + alpha, 3 for sRGB, 4 for CMYK or RGBA */
|
||||
type Channels = 1 | 2 | 3 | 4;
|
||||
/** 3 for sRGB, 4 for CMYK */
|
||||
type Channels = 3 | 4;
|
||||
|
||||
interface RGBA {
|
||||
r?: number | undefined;
|
||||
@ -1617,8 +1312,7 @@ declare namespace sharp {
|
||||
alpha?: number | undefined;
|
||||
}
|
||||
|
||||
type Colour = string | RGBA;
|
||||
type Color = Colour;
|
||||
type Color = string | RGBA;
|
||||
|
||||
interface Kernel {
|
||||
/** width of the kernel in pixels. */
|
||||
@ -1649,9 +1343,9 @@ declare namespace sharp {
|
||||
grayscale?: boolean | undefined;
|
||||
}
|
||||
|
||||
interface OverlayOptions extends SharpOptions {
|
||||
interface OverlayOptions {
|
||||
/** Buffer containing image data, String containing the path to an image file, or Create object */
|
||||
input?: string | Buffer | { create: Create } | { text: CreateText } | { raw: CreateRaw } | undefined;
|
||||
input?: string | Buffer | { create: Create } | { text: CreateText } | undefined;
|
||||
/** how to blend this image with the image below. (optional, default `'over'`) */
|
||||
blend?: Blend | undefined;
|
||||
/** gravity at which to place the overlay. (optional, default 'centre') */
|
||||
@ -1662,18 +1356,25 @@ declare namespace sharp {
|
||||
left?: number | undefined;
|
||||
/** set to true to repeat the overlay image across the entire image with the given gravity. (optional, default false) */
|
||||
tile?: boolean | undefined;
|
||||
/** number representing the DPI for vector overlay image. (optional, default 72) */
|
||||
density?: number | undefined;
|
||||
/** describes overlay when using raw pixel data. */
|
||||
raw?: Raw | undefined;
|
||||
/** Set to true to avoid premultipling the image below. Equivalent to the --premultiplied vips option. */
|
||||
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) */
|
||||
/** Set to true to read all frames/pages of an animated image. (optional, default false). */
|
||||
animated?: boolean | undefined;
|
||||
/** see sharp() constructor, (optional, default 'warning') */
|
||||
/**
|
||||
* When to abort processing of invalid pixel data, one of (in order of sensitivity):
|
||||
* 'none' (least), 'truncated', 'error' or 'warning' (most), highers level imply lower levels, invalid metadata will always abort. (optional, default 'warning')
|
||||
*/
|
||||
failOn?: FailOnOptions | undefined;
|
||||
/** see sharp() constructor, (optional, default 268402689) */
|
||||
/**
|
||||
* Do not process input images where the number of pixels (width x height) exceeds this limit.
|
||||
* Assumes image dimensions contained in the input metadata can be trusted.
|
||||
* An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). (optional, default 268402689)
|
||||
*/
|
||||
limitInputPixels?: number | boolean | undefined;
|
||||
/** see sharp() constructor, (optional, default false) */
|
||||
autoOrient?: boolean | undefined;
|
||||
}
|
||||
|
||||
interface TileOptions {
|
||||
@ -1745,7 +1446,7 @@ declare namespace sharp {
|
||||
size: number;
|
||||
width: number;
|
||||
height: number;
|
||||
channels: Channels;
|
||||
channels: 1 | 2 | 3 | 4;
|
||||
/** indicating if premultiplication was used */
|
||||
premultiplied: boolean;
|
||||
/** Only defined when using a crop strategy */
|
||||
@ -1761,10 +1462,6 @@ declare namespace sharp {
|
||||
/** When using the attention crop strategy, the focal point of the cropped region */
|
||||
attentionX?: number | undefined;
|
||||
attentionY?: number | undefined;
|
||||
/** Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP */
|
||||
pages?: number | undefined;
|
||||
/** Number of pixels high each page in a multi-page image will be. */
|
||||
pageHeight?: number | undefined;
|
||||
}
|
||||
|
||||
interface AvailableFormatInfo {
|
||||
@ -1787,17 +1484,6 @@ declare namespace sharp {
|
||||
mitchell: 'mitchell';
|
||||
lanczos2: 'lanczos2';
|
||||
lanczos3: 'lanczos3';
|
||||
mks2013: 'mks2013';
|
||||
mks2021: 'mks2021';
|
||||
}
|
||||
|
||||
interface PresetEnum {
|
||||
default: 'default';
|
||||
picture: 'picture';
|
||||
photo: 'photo';
|
||||
drawing: 'drawing';
|
||||
icon: 'icon';
|
||||
text: 'text';
|
||||
}
|
||||
|
||||
interface BoolEnum {
|
||||
@ -1807,49 +1493,18 @@ declare namespace sharp {
|
||||
}
|
||||
|
||||
interface ColourspaceEnum {
|
||||
'b-w': string;
|
||||
cmc: string;
|
||||
cmyk: string;
|
||||
fourier: string;
|
||||
grey16: string;
|
||||
histogram: string;
|
||||
hsv: string;
|
||||
lab: string;
|
||||
labq: string;
|
||||
labs: string;
|
||||
lch: string;
|
||||
matrix: string;
|
||||
multiband: string;
|
||||
rgb: string;
|
||||
rgb16: string;
|
||||
scrgb: string;
|
||||
'b-w': string;
|
||||
bw: string;
|
||||
cmyk: string;
|
||||
srgb: string;
|
||||
xyz: string;
|
||||
yxy: string;
|
||||
}
|
||||
|
||||
interface DepthEnum {
|
||||
char: string;
|
||||
complex: string;
|
||||
double: string;
|
||||
dpcomplex: string;
|
||||
float: string;
|
||||
int: string;
|
||||
short: string;
|
||||
uchar: string;
|
||||
uint: string;
|
||||
ushort: string;
|
||||
}
|
||||
|
||||
type FailOnOptions = 'none' | 'truncated' | 'error' | 'warning';
|
||||
|
||||
type TextAlign = 'left' | 'centre' | 'center' | 'right';
|
||||
|
||||
type TextWrap = 'word' | 'char' | 'word-char' | 'none';
|
||||
|
||||
type HorizontalAlignment = 'left' | 'centre' | 'center' | 'right';
|
||||
|
||||
type VerticalAlignment = 'top' | 'centre' | 'center' | 'bottom';
|
||||
type TextWrap = 'word' | 'char' | 'charWord' | 'none';
|
||||
|
||||
type TileContainer = 'fs' | 'zip';
|
||||
|
||||
@ -1906,9 +1561,7 @@ declare namespace sharp {
|
||||
|
||||
interface FormatEnum {
|
||||
avif: AvailableFormatInfo;
|
||||
dcraw: AvailableFormatInfo;
|
||||
dz: AvailableFormatInfo;
|
||||
exr: AvailableFormatInfo;
|
||||
fits: AvailableFormatInfo;
|
||||
gif: AvailableFormatInfo;
|
||||
heif: AvailableFormatInfo;
|
||||
@ -1922,7 +1575,6 @@ declare namespace sharp {
|
||||
pdf: AvailableFormatInfo;
|
||||
png: AvailableFormatInfo;
|
||||
ppm: AvailableFormatInfo;
|
||||
rad: AvailableFormatInfo;
|
||||
raw: AvailableFormatInfo;
|
||||
svg: AvailableFormatInfo;
|
||||
tiff: AvailableFormatInfo;
|
||||
@ -1957,7 +1609,6 @@ declare namespace sharp {
|
||||
|
||||
type Matrix2x2 = [[number, number], [number, number]];
|
||||
type Matrix3x3 = [[number, number, number], [number, number, number], [number, number, number]];
|
||||
type Matrix4x4 = [[number, number, number, number], [number, number, number, number], [number, number, number, number], [number, number, number, number]];
|
||||
}
|
||||
|
||||
export = sharp;
|
||||
|
299
lib/input.js
@ -3,46 +3,30 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
const color = require('color');
|
||||
const is = require('./is');
|
||||
const sharp = require('./sharp');
|
||||
|
||||
/**
|
||||
* Justification alignment
|
||||
* Justication alignment
|
||||
* @member
|
||||
* @private
|
||||
*/
|
||||
const align = {
|
||||
left: 'low',
|
||||
top: 'low',
|
||||
low: 'low',
|
||||
center: 'centre',
|
||||
centre: 'centre',
|
||||
right: 'high',
|
||||
bottom: 'high',
|
||||
high: 'high'
|
||||
right: 'high'
|
||||
};
|
||||
|
||||
const inputStreamParameters = [
|
||||
// Limits and error handling
|
||||
'failOn', 'limitInputPixels', 'unlimited',
|
||||
// Format-generic
|
||||
'animated', 'autoOrient', 'density', 'ignoreIcc', 'page', 'pages', 'sequentialRead',
|
||||
// Format-specific
|
||||
'jp2', 'openSlide', 'pdf', 'raw', 'svg', 'tiff',
|
||||
// Deprecated
|
||||
'failOnError', 'openSlideLevel', 'pdfBackground', 'tiffSubifd'
|
||||
];
|
||||
|
||||
/**
|
||||
* Extract input options, if any, from an object.
|
||||
* @private
|
||||
*/
|
||||
function _inputOptionsFromObject (obj) {
|
||||
const params = inputStreamParameters
|
||||
.filter(p => is.defined(obj[p]))
|
||||
.map(p => ([p, obj[p]]));
|
||||
return params.length
|
||||
? Object.fromEntries(params)
|
||||
const { raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd } = obj;
|
||||
return [raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd].some(is.defined)
|
||||
? { raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd }
|
||||
: undefined;
|
||||
}
|
||||
|
||||
@ -52,7 +36,6 @@ function _inputOptionsFromObject (obj) {
|
||||
*/
|
||||
function _createInputDescriptor (input, inputOptions, containerOptions) {
|
||||
const inputDescriptor = {
|
||||
autoOrient: false,
|
||||
failOn: 'warning',
|
||||
limitInputPixels: Math.pow(0x3FFF, 2),
|
||||
ignoreIcc: false,
|
||||
@ -88,18 +71,6 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
||||
} else if (!is.defined(input) && !is.defined(inputOptions) && is.object(containerOptions) && containerOptions.allowStream) {
|
||||
// Stream without options
|
||||
inputDescriptor.buffer = [];
|
||||
} else if (Array.isArray(input)) {
|
||||
if (input.length > 1) {
|
||||
// Join images together
|
||||
if (!this.options.joining) {
|
||||
this.options.joining = true;
|
||||
this.options.join = input.map(i => this._createInputDescriptor(i));
|
||||
} else {
|
||||
throw new Error('Recursive join is unsupported');
|
||||
}
|
||||
} else {
|
||||
throw new Error('Expected at least two images to join');
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Unsupported input '${input}' of type ${typeof input}${
|
||||
is.defined(inputOptions) ? ` when also providing options of type ${typeof inputOptions}` : ''
|
||||
@ -122,14 +93,6 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
||||
throw is.invalidParameterError('failOn', 'one of: none, truncated, error, warning', inputOptions.failOn);
|
||||
}
|
||||
}
|
||||
// autoOrient
|
||||
if (is.defined(inputOptions.autoOrient)) {
|
||||
if (is.bool(inputOptions.autoOrient)) {
|
||||
inputDescriptor.autoOrient = inputOptions.autoOrient;
|
||||
} else {
|
||||
throw is.invalidParameterError('autoOrient', 'boolean', inputOptions.autoOrient);
|
||||
}
|
||||
}
|
||||
// Density
|
||||
if (is.defined(inputOptions.density)) {
|
||||
if (is.inRange(inputOptions.density, 1, 100000)) {
|
||||
@ -185,6 +148,8 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
||||
inputDescriptor.rawWidth = inputOptions.raw.width;
|
||||
inputDescriptor.rawHeight = inputOptions.raw.height;
|
||||
inputDescriptor.rawChannels = inputOptions.raw.channels;
|
||||
inputDescriptor.rawPremultiplied = !!inputOptions.raw.premultiplied;
|
||||
|
||||
switch (input.constructor) {
|
||||
case Uint8Array:
|
||||
case Uint8ClampedArray:
|
||||
@ -218,25 +183,6 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
||||
} else {
|
||||
throw new Error('Expected width, height and channels for raw pixel input');
|
||||
}
|
||||
inputDescriptor.rawPremultiplied = false;
|
||||
if (is.defined(inputOptions.raw.premultiplied)) {
|
||||
if (is.bool(inputOptions.raw.premultiplied)) {
|
||||
inputDescriptor.rawPremultiplied = inputOptions.raw.premultiplied;
|
||||
} else {
|
||||
throw is.invalidParameterError('raw.premultiplied', 'boolean', inputOptions.raw.premultiplied);
|
||||
}
|
||||
}
|
||||
inputDescriptor.rawPageHeight = 0;
|
||||
if (is.defined(inputOptions.raw.pageHeight)) {
|
||||
if (is.integer(inputOptions.raw.pageHeight) && inputOptions.raw.pageHeight > 0 && inputOptions.raw.pageHeight <= inputOptions.raw.height) {
|
||||
if (inputOptions.raw.height % inputOptions.raw.pageHeight !== 0) {
|
||||
throw new Error(`Expected raw.height ${inputOptions.raw.height} to be a multiple of raw.pageHeight ${inputOptions.raw.pageHeight}`);
|
||||
}
|
||||
inputDescriptor.rawPageHeight = inputOptions.raw.pageHeight;
|
||||
} else {
|
||||
throw is.invalidParameterError('raw.pageHeight', 'positive integer', inputOptions.raw.pageHeight);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Multi-page input (GIF, TIFF, PDF)
|
||||
if (is.defined(inputOptions.animated)) {
|
||||
@ -260,68 +206,22 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
||||
throw is.invalidParameterError('page', 'integer between 0 and 100000', inputOptions.page);
|
||||
}
|
||||
}
|
||||
// OpenSlide specific options
|
||||
if (is.object(inputOptions.openSlide) && is.defined(inputOptions.openSlide.level)) {
|
||||
if (is.integer(inputOptions.openSlide.level) && is.inRange(inputOptions.openSlide.level, 0, 256)) {
|
||||
inputDescriptor.openSlideLevel = inputOptions.openSlide.level;
|
||||
} else {
|
||||
throw is.invalidParameterError('openSlide.level', 'integer between 0 and 256', inputOptions.openSlide.level);
|
||||
}
|
||||
} else if (is.defined(inputOptions.level)) {
|
||||
// Deprecated
|
||||
// Multi-level input (OpenSlide)
|
||||
if (is.defined(inputOptions.level)) {
|
||||
if (is.integer(inputOptions.level) && is.inRange(inputOptions.level, 0, 256)) {
|
||||
inputDescriptor.openSlideLevel = inputOptions.level;
|
||||
inputDescriptor.level = inputOptions.level;
|
||||
} else {
|
||||
throw is.invalidParameterError('level', 'integer between 0 and 256', inputOptions.level);
|
||||
}
|
||||
}
|
||||
// TIFF specific options
|
||||
if (is.object(inputOptions.tiff) && is.defined(inputOptions.tiff.subifd)) {
|
||||
if (is.integer(inputOptions.tiff.subifd) && is.inRange(inputOptions.tiff.subifd, -1, 100000)) {
|
||||
inputDescriptor.tiffSubifd = inputOptions.tiff.subifd;
|
||||
} else {
|
||||
throw is.invalidParameterError('tiff.subifd', 'integer between -1 and 100000', inputOptions.tiff.subifd);
|
||||
}
|
||||
} else if (is.defined(inputOptions.subifd)) {
|
||||
// Deprecated
|
||||
// Sub Image File Directory (TIFF)
|
||||
if (is.defined(inputOptions.subifd)) {
|
||||
if (is.integer(inputOptions.subifd) && is.inRange(inputOptions.subifd, -1, 100000)) {
|
||||
inputDescriptor.tiffSubifd = inputOptions.subifd;
|
||||
inputDescriptor.subifd = inputOptions.subifd;
|
||||
} else {
|
||||
throw is.invalidParameterError('subifd', 'integer between -1 and 100000', inputOptions.subifd);
|
||||
}
|
||||
}
|
||||
// SVG specific options
|
||||
if (is.object(inputOptions.svg)) {
|
||||
if (is.defined(inputOptions.svg.stylesheet)) {
|
||||
if (is.string(inputOptions.svg.stylesheet)) {
|
||||
inputDescriptor.svgStylesheet = inputOptions.svg.stylesheet;
|
||||
} else {
|
||||
throw is.invalidParameterError('svg.stylesheet', 'string', inputOptions.svg.stylesheet);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.svg.highBitdepth)) {
|
||||
if (is.bool(inputOptions.svg.highBitdepth)) {
|
||||
inputDescriptor.svgHighBitdepth = inputOptions.svg.highBitdepth;
|
||||
} else {
|
||||
throw is.invalidParameterError('svg.highBitdepth', 'boolean', inputOptions.svg.highBitdepth);
|
||||
}
|
||||
}
|
||||
}
|
||||
// PDF specific options
|
||||
if (is.object(inputOptions.pdf) && is.defined(inputOptions.pdf.background)) {
|
||||
inputDescriptor.pdfBackground = this._getBackgroundColourOption(inputOptions.pdf.background);
|
||||
} else if (is.defined(inputOptions.pdfBackground)) {
|
||||
// Deprecated
|
||||
inputDescriptor.pdfBackground = this._getBackgroundColourOption(inputOptions.pdfBackground);
|
||||
}
|
||||
// JPEG 2000 specific options
|
||||
if (is.object(inputOptions.jp2) && is.defined(inputOptions.jp2.oneshot)) {
|
||||
if (is.bool(inputOptions.jp2.oneshot)) {
|
||||
inputDescriptor.jp2Oneshot = inputOptions.jp2.oneshot;
|
||||
} else {
|
||||
throw is.invalidParameterError('jp2.oneshot', 'boolean', inputOptions.jp2.oneshot);
|
||||
}
|
||||
}
|
||||
// Create new image
|
||||
if (is.defined(inputOptions.create)) {
|
||||
if (
|
||||
@ -333,50 +233,39 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
||||
inputDescriptor.createWidth = inputOptions.create.width;
|
||||
inputDescriptor.createHeight = inputOptions.create.height;
|
||||
inputDescriptor.createChannels = inputOptions.create.channels;
|
||||
inputDescriptor.createPageHeight = 0;
|
||||
if (is.defined(inputOptions.create.pageHeight)) {
|
||||
if (is.integer(inputOptions.create.pageHeight) && inputOptions.create.pageHeight > 0 && inputOptions.create.pageHeight <= inputOptions.create.height) {
|
||||
if (inputOptions.create.height % inputOptions.create.pageHeight !== 0) {
|
||||
throw new Error(`Expected create.height ${inputOptions.create.height} to be a multiple of create.pageHeight ${inputOptions.create.pageHeight}`);
|
||||
}
|
||||
inputDescriptor.createPageHeight = inputOptions.create.pageHeight;
|
||||
} else {
|
||||
throw is.invalidParameterError('create.pageHeight', 'positive integer', inputOptions.create.pageHeight);
|
||||
}
|
||||
}
|
||||
// Noise
|
||||
if (is.defined(inputOptions.create.noise)) {
|
||||
if (!is.object(inputOptions.create.noise)) {
|
||||
throw new Error('Expected noise to be an object');
|
||||
}
|
||||
if (inputOptions.create.noise.type !== 'gaussian') {
|
||||
if (!is.inArray(inputOptions.create.noise.type, ['gaussian'])) {
|
||||
throw new Error('Only gaussian noise is supported at the moment');
|
||||
}
|
||||
inputDescriptor.createNoiseType = inputOptions.create.noise.type;
|
||||
if (!is.inRange(inputOptions.create.channels, 1, 4)) {
|
||||
throw is.invalidParameterError('create.channels', 'number between 1 and 4', inputOptions.create.channels);
|
||||
}
|
||||
inputDescriptor.createNoiseMean = 128;
|
||||
if (is.defined(inputOptions.create.noise.mean)) {
|
||||
if (is.number(inputOptions.create.noise.mean) && is.inRange(inputOptions.create.noise.mean, 0, 10000)) {
|
||||
inputDescriptor.createNoiseMean = inputOptions.create.noise.mean;
|
||||
} else {
|
||||
throw is.invalidParameterError('create.noise.mean', 'number between 0 and 10000', inputOptions.create.noise.mean);
|
||||
}
|
||||
inputDescriptor.createNoiseType = inputOptions.create.noise.type;
|
||||
if (is.number(inputOptions.create.noise.mean) && is.inRange(inputOptions.create.noise.mean, 0, 10000)) {
|
||||
inputDescriptor.createNoiseMean = inputOptions.create.noise.mean;
|
||||
} else {
|
||||
throw is.invalidParameterError('create.noise.mean', 'number between 0 and 10000', inputOptions.create.noise.mean);
|
||||
}
|
||||
inputDescriptor.createNoiseSigma = 30;
|
||||
if (is.defined(inputOptions.create.noise.sigma)) {
|
||||
if (is.number(inputOptions.create.noise.sigma) && is.inRange(inputOptions.create.noise.sigma, 0, 10000)) {
|
||||
inputDescriptor.createNoiseSigma = inputOptions.create.noise.sigma;
|
||||
} else {
|
||||
throw is.invalidParameterError('create.noise.sigma', 'number between 0 and 10000', inputOptions.create.noise.sigma);
|
||||
}
|
||||
if (is.number(inputOptions.create.noise.sigma) && is.inRange(inputOptions.create.noise.sigma, 0, 10000)) {
|
||||
inputDescriptor.createNoiseSigma = inputOptions.create.noise.sigma;
|
||||
} else {
|
||||
throw is.invalidParameterError('create.noise.sigma', 'number between 0 and 10000', inputOptions.create.noise.sigma);
|
||||
}
|
||||
} else if (is.defined(inputOptions.create.background)) {
|
||||
if (!is.inRange(inputOptions.create.channels, 3, 4)) {
|
||||
throw is.invalidParameterError('create.channels', 'number between 3 and 4', inputOptions.create.channels);
|
||||
}
|
||||
inputDescriptor.createBackground = this._getBackgroundColourOption(inputOptions.create.background);
|
||||
const background = color(inputOptions.create.background);
|
||||
inputDescriptor.createBackground = [
|
||||
background.red(),
|
||||
background.green(),
|
||||
background.blue(),
|
||||
Math.round(background.alpha() * 255)
|
||||
];
|
||||
} else {
|
||||
throw new Error('Expected valid noise or background to create a new input image');
|
||||
}
|
||||
@ -407,17 +296,17 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.text.width)) {
|
||||
if (is.integer(inputOptions.text.width) && inputOptions.text.width > 0) {
|
||||
if (is.number(inputOptions.text.width)) {
|
||||
inputDescriptor.textWidth = inputOptions.text.width;
|
||||
} else {
|
||||
throw is.invalidParameterError('text.width', 'positive integer', inputOptions.text.width);
|
||||
throw is.invalidParameterError('text.textWidth', 'number', inputOptions.text.width);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.text.height)) {
|
||||
if (is.integer(inputOptions.text.height) && inputOptions.text.height > 0) {
|
||||
if (is.number(inputOptions.text.height)) {
|
||||
inputDescriptor.textHeight = inputOptions.text.height;
|
||||
} else {
|
||||
throw is.invalidParameterError('text.height', 'positive integer', inputOptions.text.height);
|
||||
throw is.invalidParameterError('text.height', 'number', inputOptions.text.height);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.text.align)) {
|
||||
@ -435,10 +324,10 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.text.dpi)) {
|
||||
if (is.integer(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 1000000)) {
|
||||
if (is.number(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 100000)) {
|
||||
inputDescriptor.textDpi = inputOptions.text.dpi;
|
||||
} else {
|
||||
throw is.invalidParameterError('text.dpi', 'integer between 1 and 1000000', inputOptions.text.dpi);
|
||||
throw is.invalidParameterError('text.dpi', 'number between 1 and 100000', inputOptions.text.dpi);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.text.rgba)) {
|
||||
@ -449,17 +338,17 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.text.spacing)) {
|
||||
if (is.integer(inputOptions.text.spacing) && is.inRange(inputOptions.text.spacing, -1000000, 1000000)) {
|
||||
if (is.number(inputOptions.text.spacing)) {
|
||||
inputDescriptor.textSpacing = inputOptions.text.spacing;
|
||||
} else {
|
||||
throw is.invalidParameterError('text.spacing', 'integer between -1000000 and 1000000', inputOptions.text.spacing);
|
||||
throw is.invalidParameterError('text.spacing', 'number', inputOptions.text.spacing);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.text.wrap)) {
|
||||
if (is.string(inputOptions.text.wrap) && is.inArray(inputOptions.text.wrap, ['word', 'char', 'word-char', 'none'])) {
|
||||
if (is.string(inputOptions.text.wrap) && is.inArray(inputOptions.text.wrap, ['word', 'char', 'wordChar', 'none'])) {
|
||||
inputDescriptor.textWrap = inputOptions.text.wrap;
|
||||
} else {
|
||||
throw is.invalidParameterError('text.wrap', 'one of: word, char, word-char, none', inputOptions.text.wrap);
|
||||
throw is.invalidParameterError('text.wrap', 'one of: word, char, wordChar, none', inputOptions.text.wrap);
|
||||
}
|
||||
}
|
||||
delete inputDescriptor.buffer;
|
||||
@ -467,51 +356,6 @@ function _createInputDescriptor (input, inputOptions, containerOptions) {
|
||||
throw new Error('Expected a valid string to create an image with text.');
|
||||
}
|
||||
}
|
||||
// Join images together
|
||||
if (is.defined(inputOptions.join)) {
|
||||
if (is.defined(this.options.join)) {
|
||||
if (is.defined(inputOptions.join.animated)) {
|
||||
if (is.bool(inputOptions.join.animated)) {
|
||||
inputDescriptor.joinAnimated = inputOptions.join.animated;
|
||||
} else {
|
||||
throw is.invalidParameterError('join.animated', 'boolean', inputOptions.join.animated);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.join.across)) {
|
||||
if (is.integer(inputOptions.join.across) && is.inRange(inputOptions.join.across, 1, 1000000)) {
|
||||
inputDescriptor.joinAcross = inputOptions.join.across;
|
||||
} else {
|
||||
throw is.invalidParameterError('join.across', 'integer between 1 and 100000', inputOptions.join.across);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.join.shim)) {
|
||||
if (is.integer(inputOptions.join.shim) && is.inRange(inputOptions.join.shim, 0, 1000000)) {
|
||||
inputDescriptor.joinShim = inputOptions.join.shim;
|
||||
} else {
|
||||
throw is.invalidParameterError('join.shim', 'integer between 0 and 100000', inputOptions.join.shim);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.join.background)) {
|
||||
inputDescriptor.joinBackground = this._getBackgroundColourOption(inputOptions.join.background);
|
||||
}
|
||||
if (is.defined(inputOptions.join.halign)) {
|
||||
if (is.string(inputOptions.join.halign) && is.string(this.constructor.align[inputOptions.join.halign])) {
|
||||
inputDescriptor.joinHalign = this.constructor.align[inputOptions.join.halign];
|
||||
} else {
|
||||
throw is.invalidParameterError('join.halign', 'valid alignment', inputOptions.join.halign);
|
||||
}
|
||||
}
|
||||
if (is.defined(inputOptions.join.valign)) {
|
||||
if (is.string(inputOptions.join.valign) && is.string(this.constructor.align[inputOptions.join.valign])) {
|
||||
inputDescriptor.joinValign = this.constructor.align[inputOptions.join.valign];
|
||||
} else {
|
||||
throw is.invalidParameterError('join.valign', 'valid alignment', inputOptions.join.valign);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw new Error('Expected input to be an array of images to join');
|
||||
}
|
||||
}
|
||||
} else if (is.defined(inputOptions)) {
|
||||
throw new Error('Invalid input options ' + inputOptions);
|
||||
}
|
||||
@ -586,8 +430,6 @@ function _isStreamInput () {
|
||||
* - `density`: Number of pixels per inch (DPI), if present
|
||||
* - `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK
|
||||
* - `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan
|
||||
* - `isPalette`: Boolean indicating whether the image is palette-based (GIF, PNG).
|
||||
* - `bitsPerSample`: Number of bits per sample for each channel (GIF, PNG, HEIF).
|
||||
* - `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP
|
||||
* - `pageHeight`: Number of pixels high each page in a multi-page image will be.
|
||||
* - `loop`: Number of times to loop an animated image, zero refers to a continuous loop.
|
||||
@ -595,7 +437,7 @@ function _isStreamInput () {
|
||||
* - `pagePrimary`: Number of the primary page in a HEIF image
|
||||
* - `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide
|
||||
* - `subifds`: Number of Sub Image File Directories in an OME-TIFF image
|
||||
* - `background`: Default background colour, if present, for PNG (bKGD) and GIF images
|
||||
* - `background`: Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value
|
||||
* - `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC)
|
||||
* - `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present
|
||||
* - `hasProfile`: Boolean indicating the presence of an embedded ICC profile
|
||||
@ -605,10 +447,8 @@ function _isStreamInput () {
|
||||
* - `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present
|
||||
* - `iptc`: Buffer containing raw IPTC data, if present
|
||||
* - `xmp`: Buffer containing raw XMP data, if present
|
||||
* - `xmpAsString`: String containing XMP data, if valid UTF-8.
|
||||
* - `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present
|
||||
* - `formatMagick`: String containing format for images loaded via *magick
|
||||
* - `comments`: Array of keyword/text pairs representing PNG text blocks, if present.
|
||||
*
|
||||
* @example
|
||||
* const metadata = await sharp(input).metadata();
|
||||
@ -628,35 +468,28 @@ function _isStreamInput () {
|
||||
* });
|
||||
*
|
||||
* @example
|
||||
* // Get dimensions taking EXIF Orientation into account.
|
||||
* const { autoOrient } = await sharp(input).metadata();
|
||||
* const { width, height } = autoOrient;
|
||||
* // Based on EXIF rotation metadata, get the right-side-up width and height:
|
||||
*
|
||||
* const size = getNormalSize(await sharp(input).metadata());
|
||||
*
|
||||
* function getNormalSize({ width, height, orientation }) {
|
||||
* return (orientation || 0) >= 5
|
||||
* ? { width: height, height: width }
|
||||
* : { width, height };
|
||||
* }
|
||||
*
|
||||
* @param {Function} [callback] - called with the arguments `(err, metadata)`
|
||||
* @returns {Promise<Object>|Sharp}
|
||||
*/
|
||||
function metadata (callback) {
|
||||
const stack = Error();
|
||||
if (is.fn(callback)) {
|
||||
if (this._isStreamInput()) {
|
||||
this.on('finish', () => {
|
||||
this._flattenBufferIn();
|
||||
sharp.metadata(this.options, (err, metadata) => {
|
||||
if (err) {
|
||||
callback(is.nativeError(err, stack));
|
||||
} else {
|
||||
callback(null, metadata);
|
||||
}
|
||||
});
|
||||
sharp.metadata(this.options, callback);
|
||||
});
|
||||
} else {
|
||||
sharp.metadata(this.options, (err, metadata) => {
|
||||
if (err) {
|
||||
callback(is.nativeError(err, stack));
|
||||
} else {
|
||||
callback(null, metadata);
|
||||
}
|
||||
});
|
||||
sharp.metadata(this.options, callback);
|
||||
}
|
||||
return this;
|
||||
} else {
|
||||
@ -666,7 +499,7 @@ function metadata (callback) {
|
||||
this._flattenBufferIn();
|
||||
sharp.metadata(this.options, (err, metadata) => {
|
||||
if (err) {
|
||||
reject(is.nativeError(err, stack));
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(metadata);
|
||||
}
|
||||
@ -682,7 +515,7 @@ function metadata (callback) {
|
||||
return new Promise((resolve, reject) => {
|
||||
sharp.metadata(this.options, (err, metadata) => {
|
||||
if (err) {
|
||||
reject(is.nativeError(err, stack));
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(metadata);
|
||||
}
|
||||
@ -738,27 +571,14 @@ function metadata (callback) {
|
||||
* @returns {Promise<Object>}
|
||||
*/
|
||||
function stats (callback) {
|
||||
const stack = Error();
|
||||
if (is.fn(callback)) {
|
||||
if (this._isStreamInput()) {
|
||||
this.on('finish', () => {
|
||||
this._flattenBufferIn();
|
||||
sharp.stats(this.options, (err, stats) => {
|
||||
if (err) {
|
||||
callback(is.nativeError(err, stack));
|
||||
} else {
|
||||
callback(null, stats);
|
||||
}
|
||||
});
|
||||
sharp.stats(this.options, callback);
|
||||
});
|
||||
} else {
|
||||
sharp.stats(this.options, (err, stats) => {
|
||||
if (err) {
|
||||
callback(is.nativeError(err, stack));
|
||||
} else {
|
||||
callback(null, stats);
|
||||
}
|
||||
});
|
||||
sharp.stats(this.options, callback);
|
||||
}
|
||||
return this;
|
||||
} else {
|
||||
@ -768,7 +588,7 @@ function stats (callback) {
|
||||
this._flattenBufferIn();
|
||||
sharp.stats(this.options, (err, stats) => {
|
||||
if (err) {
|
||||
reject(is.nativeError(err, stack));
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(stats);
|
||||
}
|
||||
@ -779,7 +599,7 @@ function stats (callback) {
|
||||
return new Promise((resolve, reject) => {
|
||||
sharp.stats(this.options, (err, stats) => {
|
||||
if (err) {
|
||||
reject(is.nativeError(err, stack));
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(stats);
|
||||
}
|
||||
@ -791,7 +611,6 @@ function stats (callback) {
|
||||
|
||||
/**
|
||||
* Decorate the Sharp prototype with input-related functions.
|
||||
* @module Sharp
|
||||
* @private
|
||||
*/
|
||||
module.exports = function (Sharp) {
|
||||
|
42
lib/is.js
@ -137,33 +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 = {
|
||||
defined,
|
||||
object,
|
||||
plainObject,
|
||||
fn,
|
||||
bool,
|
||||
buffer,
|
||||
typedArray,
|
||||
arrayBuffer,
|
||||
string,
|
||||
number,
|
||||
integer,
|
||||
inRange,
|
||||
inArray,
|
||||
invalidParameterError,
|
||||
nativeError
|
||||
defined: defined,
|
||||
object: object,
|
||||
plainObject: plainObject,
|
||||
fn: fn,
|
||||
bool: bool,
|
||||
buffer: buffer,
|
||||
typedArray: typedArray,
|
||||
arrayBuffer: arrayBuffer,
|
||||
string: string,
|
||||
number: number,
|
||||
integer: integer,
|
||||
inRange: inRange,
|
||||
inArray: inArray,
|
||||
invalidParameterError: invalidParameterError
|
||||
};
|
||||
|
188
lib/libvips.js
@ -3,32 +3,53 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
const { spawnSync } = require('node:child_process');
|
||||
const { createHash } = require('node:crypto');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const spawnSync = require('child_process').spawnSync;
|
||||
const semverCoerce = require('semver/functions/coerce');
|
||||
const semverGreaterThanOrEqualTo = require('semver/functions/gte');
|
||||
const semverSatisfies = require('semver/functions/satisfies');
|
||||
const detectLibc = require('detect-libc');
|
||||
|
||||
const { config, engines, optionalDependencies } = require('../package.json');
|
||||
const platform = require('./platform');
|
||||
const { config } = require('../package.json');
|
||||
|
||||
const minimumLibvipsVersionLabelled = process.env.npm_package_config_libvips || /* istanbul ignore next */
|
||||
const env = process.env;
|
||||
const minimumLibvipsVersionLabelled = env.npm_package_config_libvips || /* istanbul ignore next */
|
||||
config.libvips;
|
||||
const minimumLibvipsVersion = semverCoerce(minimumLibvipsVersionLabelled).version;
|
||||
|
||||
const prebuiltPlatforms = [
|
||||
'darwin-arm64', 'darwin-x64',
|
||||
'linux-arm', 'linux-arm64', 'linux-ppc64', 'linux-s390x', 'linux-x64',
|
||||
'linuxmusl-arm64', 'linuxmusl-x64',
|
||||
'win32-arm64', 'win32-ia32', 'win32-x64'
|
||||
];
|
||||
|
||||
const spawnSyncOptions = {
|
||||
encoding: 'utf8',
|
||||
shell: true
|
||||
};
|
||||
|
||||
const log = (item) => {
|
||||
const vendorPath = path.join(__dirname, '..', 'vendor', minimumLibvipsVersion, platform());
|
||||
|
||||
const mkdirSync = function (dirPath) {
|
||||
try {
|
||||
fs.mkdirSync(dirPath, { recursive: true });
|
||||
} catch (err) {
|
||||
/* istanbul ignore next */
|
||||
if (err.code !== 'EEXIST') {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const cachePath = function () {
|
||||
const npmCachePath = env.npm_config_cache || /* istanbul ignore next */
|
||||
(env.APPDATA ? path.join(env.APPDATA, 'npm-cache') : path.join(os.homedir(), '.npm'));
|
||||
mkdirSync(npmCachePath);
|
||||
const libvipsCachePath = path.join(npmCachePath, '_libvips');
|
||||
mkdirSync(libvipsCachePath);
|
||||
return libvipsCachePath;
|
||||
};
|
||||
|
||||
const integrity = function (platformAndArch) {
|
||||
return env[`npm_package_config_integrity_${platformAndArch.replace('-', '_')}`] || config.integrity[platformAndArch];
|
||||
};
|
||||
|
||||
const log = function (item) {
|
||||
if (item instanceof Error) {
|
||||
console.error(`sharp: Installation error: ${item.message}`);
|
||||
} else {
|
||||
@ -36,70 +57,7 @@ const log = (item) => {
|
||||
}
|
||||
};
|
||||
|
||||
/* istanbul ignore next */
|
||||
const runtimeLibc = () => detectLibc.isNonGlibcLinuxSync() ? detectLibc.familySync() : '';
|
||||
|
||||
const runtimePlatformArch = () => `${process.platform}${runtimeLibc()}-${process.arch}`;
|
||||
|
||||
/* istanbul ignore next */
|
||||
const buildPlatformArch = () => {
|
||||
if (isEmscripten()) {
|
||||
return 'wasm32';
|
||||
}
|
||||
/* eslint camelcase: ["error", { allow: ["^npm_config_"] }] */
|
||||
const { npm_config_arch, npm_config_platform, npm_config_libc } = process.env;
|
||||
const libc = typeof npm_config_libc === 'string' ? npm_config_libc : runtimeLibc();
|
||||
return `${npm_config_platform || process.platform}${libc}-${npm_config_arch || process.arch}`;
|
||||
};
|
||||
|
||||
const buildSharpLibvipsIncludeDir = () => {
|
||||
try {
|
||||
return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/include`);
|
||||
} catch {
|
||||
try {
|
||||
return require('@img/sharp-libvips-dev/include');
|
||||
} catch {}
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
return '';
|
||||
};
|
||||
|
||||
const buildSharpLibvipsCPlusPlusDir = () => {
|
||||
try {
|
||||
return require('@img/sharp-libvips-dev/cplusplus');
|
||||
} catch {}
|
||||
/* istanbul ignore next */
|
||||
return '';
|
||||
};
|
||||
|
||||
const buildSharpLibvipsLibDir = () => {
|
||||
try {
|
||||
return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/lib`);
|
||||
} catch {
|
||||
try {
|
||||
return require(`@img/sharp-libvips-${buildPlatformArch()}/lib`);
|
||||
} catch {}
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
return '';
|
||||
};
|
||||
|
||||
const isUnsupportedNodeRuntime = () => {
|
||||
/* istanbul ignore next */
|
||||
if (process.release?.name === 'node' && process.versions) {
|
||||
if (!semverSatisfies(process.versions.node, engines.node)) {
|
||||
return { found: process.versions.node, expected: engines.node };
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/* istanbul ignore next */
|
||||
const isEmscripten = () => {
|
||||
const { CC } = process.env;
|
||||
return Boolean(CC && CC.endsWith('/emcc'));
|
||||
};
|
||||
|
||||
const isRosetta = () => {
|
||||
const isRosetta = function () {
|
||||
/* istanbul ignore next */
|
||||
if (process.platform === 'darwin' && process.arch === 'x64') {
|
||||
const translated = spawnSync('sysctl sysctl.proc_translated', spawnSyncOptions).stdout;
|
||||
@ -108,32 +66,12 @@ const isRosetta = () => {
|
||||
return false;
|
||||
};
|
||||
|
||||
const sha512 = (s) => createHash('sha512').update(s).digest('hex');
|
||||
|
||||
const yarnLocator = () => {
|
||||
try {
|
||||
const identHash = sha512(`imgsharp-libvips-${buildPlatformArch()}`);
|
||||
const npmVersion = semverCoerce(optionalDependencies[`@img/sharp-libvips-${buildPlatformArch()}`], {
|
||||
includePrerelease: true
|
||||
}).version;
|
||||
return sha512(`${identHash}npm:${npmVersion}`).slice(0, 10);
|
||||
} catch {}
|
||||
return '';
|
||||
};
|
||||
|
||||
/* istanbul ignore next */
|
||||
const spawnRebuild = () =>
|
||||
spawnSync(`node-gyp rebuild --directory=src ${isEmscripten() ? '--nodedir=emscripten' : ''}`, {
|
||||
...spawnSyncOptions,
|
||||
stdio: 'inherit'
|
||||
}).status;
|
||||
|
||||
const globalLibvipsVersion = () => {
|
||||
const globalLibvipsVersion = function () {
|
||||
if (process.platform !== 'win32') {
|
||||
const globalLibvipsVersion = spawnSync('pkg-config --modversion vips-cpp', {
|
||||
...spawnSyncOptions,
|
||||
env: {
|
||||
...process.env,
|
||||
...env,
|
||||
PKG_CONFIG_PATH: pkgConfigPath()
|
||||
}
|
||||
}).stdout;
|
||||
@ -144,8 +82,18 @@ const globalLibvipsVersion = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const hasVendoredLibvips = function () {
|
||||
return fs.existsSync(vendorPath);
|
||||
};
|
||||
|
||||
/* istanbul ignore next */
|
||||
const pkgConfigPath = () => {
|
||||
const removeVendoredLibvips = function () {
|
||||
const rm = fs.rmSync ? fs.rmSync : fs.rmdirSync;
|
||||
rm(vendorPath, { recursive: true, maxRetries: 3, force: true });
|
||||
};
|
||||
|
||||
/* istanbul ignore next */
|
||||
const pkgConfigPath = function () {
|
||||
if (process.platform !== 'win32') {
|
||||
const brewPkgConfigPath = spawnSync(
|
||||
'which brew >/dev/null 2>&1 && brew environment --plain | grep PKG_CONFIG_LIBDIR | cut -d" " -f2',
|
||||
@ -153,7 +101,7 @@ const pkgConfigPath = () => {
|
||||
).stdout || '';
|
||||
return [
|
||||
brewPkgConfigPath.trim(),
|
||||
process.env.PKG_CONFIG_PATH,
|
||||
env.PKG_CONFIG_PATH,
|
||||
'/usr/local/lib/pkgconfig',
|
||||
'/usr/lib/pkgconfig',
|
||||
'/usr/local/libdata/pkgconfig',
|
||||
@ -164,23 +112,14 @@ const pkgConfigPath = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const skipSearch = (status, reason, logger) => {
|
||||
if (logger) {
|
||||
logger(`Detected ${reason}, skipping search for globally-installed libvips`);
|
||||
}
|
||||
return status;
|
||||
};
|
||||
|
||||
const useGlobalLibvips = (logger) => {
|
||||
if (Boolean(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS) === true) {
|
||||
return skipSearch(false, 'SHARP_IGNORE_GLOBAL_LIBVIPS', logger);
|
||||
}
|
||||
if (Boolean(process.env.SHARP_FORCE_GLOBAL_LIBVIPS) === true) {
|
||||
return skipSearch(true, 'SHARP_FORCE_GLOBAL_LIBVIPS', logger);
|
||||
const useGlobalLibvips = function () {
|
||||
if (Boolean(env.SHARP_IGNORE_GLOBAL_LIBVIPS) === true) {
|
||||
return false;
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
if (isRosetta()) {
|
||||
return skipSearch(false, 'Rosetta', logger);
|
||||
log('Detected Rosetta, skipping search for globally-installed libvips');
|
||||
return false;
|
||||
}
|
||||
const globalVipsVersion = globalLibvipsVersion();
|
||||
return !!globalVipsVersion && /* istanbul ignore next */
|
||||
@ -189,17 +128,14 @@ const useGlobalLibvips = (logger) => {
|
||||
|
||||
module.exports = {
|
||||
minimumLibvipsVersion,
|
||||
prebuiltPlatforms,
|
||||
buildPlatformArch,
|
||||
buildSharpLibvipsIncludeDir,
|
||||
buildSharpLibvipsCPlusPlusDir,
|
||||
buildSharpLibvipsLibDir,
|
||||
isUnsupportedNodeRuntime,
|
||||
runtimePlatformArch,
|
||||
minimumLibvipsVersionLabelled,
|
||||
cachePath,
|
||||
integrity,
|
||||
log,
|
||||
yarnLocator,
|
||||
spawnRebuild,
|
||||
globalLibvipsVersion,
|
||||
hasVendoredLibvips,
|
||||
removeVendoredLibvips,
|
||||
pkgConfigPath,
|
||||
useGlobalLibvips
|
||||
useGlobalLibvips,
|
||||
mkdirSync
|
||||
};
|
||||
|
248
lib/operation.js
@ -3,40 +3,42 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
const color = require('color');
|
||||
const is = require('./is');
|
||||
|
||||
/**
|
||||
* How accurate an operation should be.
|
||||
* @member
|
||||
* @private
|
||||
*/
|
||||
const vipsPrecision = {
|
||||
integer: 'integer',
|
||||
float: 'float',
|
||||
approximate: 'approximate'
|
||||
};
|
||||
|
||||
/**
|
||||
* Rotate the output image.
|
||||
* Rotate the output image by either an explicit angle
|
||||
* or auto-orient based on the EXIF `Orientation` tag.
|
||||
*
|
||||
* The provided angle is converted to a valid positive degree rotation.
|
||||
* For example, `-450` will produce a 270 degree rotation.
|
||||
* If an angle is provided, it is converted to a valid positive degree rotation.
|
||||
* For example, `-450` will produce a 270deg rotation.
|
||||
*
|
||||
* When rotating by an angle other than a multiple of 90,
|
||||
* the background colour can be provided with the `background` option.
|
||||
*
|
||||
* For backwards compatibility, if no angle is provided, `.autoOrient()` will be called.
|
||||
* If no angle is provided, it is determined from the EXIF data.
|
||||
* Mirroring is supported and may infer the use of a flip operation.
|
||||
*
|
||||
* Only one rotation can occur per pipeline (aside from an initial call without
|
||||
* arguments to orient via EXIF data). Previous calls to `rotate` in the same
|
||||
* pipeline will be ignored.
|
||||
* The use of `rotate` implies the removal of the EXIF `Orientation` tag, if any.
|
||||
*
|
||||
* Multi-page images can only be rotated by 180 degrees.
|
||||
* Only one rotation can occur per pipeline.
|
||||
* Previous calls to `rotate` in the same pipeline will be ignored.
|
||||
*
|
||||
* Method order is important when rotating, resizing and/or extracting regions,
|
||||
* for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.
|
||||
*
|
||||
* @example
|
||||
* const pipeline = sharp()
|
||||
* .rotate()
|
||||
* .resize(null, 200)
|
||||
* .toBuffer(function (err, outputBuffer, info) {
|
||||
* // outputBuffer contains 200px high JPEG image data,
|
||||
* // auto-rotated using EXIF Orientation tag
|
||||
* // info.width and info.height contain the dimensions of the resized image
|
||||
* });
|
||||
* readableStream.pipe(pipeline);
|
||||
*
|
||||
* @example
|
||||
* const rotateThenResize = await sharp(input)
|
||||
* .rotate(90)
|
||||
* .resize({ width: 16, height: 8, fit: 'fill' })
|
||||
@ -53,20 +55,23 @@ const vipsPrecision = {
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function rotate (angle, options) {
|
||||
if (!is.defined(angle)) {
|
||||
return this.autoOrient();
|
||||
}
|
||||
if (this.options.angle || this.options.rotationAngle) {
|
||||
if (this.options.useExifOrientation || this.options.angle || this.options.rotationAngle) {
|
||||
this.options.debuglog('ignoring previous rotate options');
|
||||
this.options.angle = 0;
|
||||
this.options.rotationAngle = 0;
|
||||
}
|
||||
if (is.integer(angle) && !(angle % 90)) {
|
||||
if (!is.defined(angle)) {
|
||||
this.options.useExifOrientation = true;
|
||||
} else if (is.integer(angle) && !(angle % 90)) {
|
||||
this.options.angle = angle;
|
||||
} else if (is.number(angle)) {
|
||||
this.options.rotationAngle = angle;
|
||||
if (is.object(options) && options.background) {
|
||||
this._setBackgroundColourOption('rotationBackground', options.background);
|
||||
const backgroundColour = color(options.background);
|
||||
this.options.rotationBackground = [
|
||||
backgroundColour.red(),
|
||||
backgroundColour.green(),
|
||||
backgroundColour.blue(),
|
||||
Math.round(backgroundColour.alpha() * 255)
|
||||
];
|
||||
}
|
||||
} else {
|
||||
throw is.invalidParameterError('angle', 'numeric', angle);
|
||||
@ -75,38 +80,8 @@ function rotate (angle, options) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-orient based on the EXIF `Orientation` tag, then remove the tag.
|
||||
* Mirroring is supported and may infer the use of a flip operation.
|
||||
*
|
||||
* Previous or subsequent use of `rotate(angle)` and either `flip()` or `flop()`
|
||||
* will logically occur after auto-orientation, regardless of call order.
|
||||
*
|
||||
* @example
|
||||
* const output = await sharp(input).autoOrient().toBuffer();
|
||||
*
|
||||
* @example
|
||||
* const pipeline = sharp()
|
||||
* .autoOrient()
|
||||
* .resize(null, 200)
|
||||
* .toBuffer(function (err, outputBuffer, info) {
|
||||
* // outputBuffer contains 200px high JPEG image data,
|
||||
* // auto-oriented using EXIF Orientation tag
|
||||
* // info.width and info.height contain the dimensions of the resized image
|
||||
* });
|
||||
* readableStream.pipe(pipeline);
|
||||
*
|
||||
* @returns {Sharp}
|
||||
*/
|
||||
function autoOrient () {
|
||||
this.options.input.autoOrient = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirror the image vertically (up-down) about the x-axis.
|
||||
* This always occurs before rotation, if any.
|
||||
*
|
||||
* This operation does not work correctly with multi-page images.
|
||||
* Flip the image about the vertical Y axis. This always occurs before rotation, if any.
|
||||
* The use of `flip` implies the removal of the EXIF `Orientation` tag, if any.
|
||||
*
|
||||
* @example
|
||||
* const output = await sharp(input).flip().toBuffer();
|
||||
@ -120,8 +95,8 @@ function flip (flip) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirror the image horizontally (left-right) about the y-axis.
|
||||
* This always occurs before rotation, if any.
|
||||
* Flop the image about the horizontal X axis. This always occurs before rotation, if any.
|
||||
* The use of `flop` implies the removal of the EXIF `Orientation` tag, if any.
|
||||
*
|
||||
* @example
|
||||
* const output = await sharp(input).flop().toBuffer();
|
||||
@ -138,8 +113,8 @@ function flop (flop) {
|
||||
* Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.
|
||||
*
|
||||
* You must provide an array of length 4 or a 2x2 affine transformation matrix.
|
||||
* By default, new pixels are filled with a black background. You can provide a background colour with the `background` option.
|
||||
* A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`.
|
||||
* By default, new pixels are filled with a black background. You can provide a background color with the `background` option.
|
||||
* A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolator` Object e.g. `sharp.interpolator.nohalo`.
|
||||
*
|
||||
* In the case of a 2x2 matrix, the transform is:
|
||||
* - X = `matrix[0, 0]` \* (x + `idx`) + `matrix[0, 1]` \* (y + `idy`) + `odx`
|
||||
@ -156,7 +131,7 @@ function flop (flop) {
|
||||
* const pipeline = sharp()
|
||||
* .affine([[1, 0.3], [0.1, 0.7]], {
|
||||
* background: 'white',
|
||||
* interpolator: sharp.interpolators.nohalo
|
||||
* interpolate: sharp.interpolators.nohalo
|
||||
* })
|
||||
* .toBuffer((err, outputBuffer, info) => {
|
||||
* // outputBuffer contains the transformed image
|
||||
@ -388,97 +363,23 @@ function median (size) {
|
||||
* .blur(5)
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {Object|number|Boolean} [options]
|
||||
* @param {number} [options.sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
|
||||
* @param {string} [options.precision='integer'] How accurate the operation should be, one of: integer, float, approximate.
|
||||
* @param {number} [options.minAmplitude=0.2] A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask.
|
||||
* @param {number} [sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function blur (options) {
|
||||
let sigma;
|
||||
if (is.number(options)) {
|
||||
sigma = options;
|
||||
} else if (is.plainObject(options)) {
|
||||
if (!is.number(options.sigma)) {
|
||||
throw is.invalidParameterError('options.sigma', 'number between 0.3 and 1000', sigma);
|
||||
}
|
||||
sigma = options.sigma;
|
||||
if ('precision' in options) {
|
||||
if (is.string(vipsPrecision[options.precision])) {
|
||||
this.options.precision = vipsPrecision[options.precision];
|
||||
} else {
|
||||
throw is.invalidParameterError('precision', 'one of: integer, float, approximate', options.precision);
|
||||
}
|
||||
}
|
||||
if ('minAmplitude' in options) {
|
||||
if (is.number(options.minAmplitude) && is.inRange(options.minAmplitude, 0.001, 1)) {
|
||||
this.options.minAmpl = options.minAmplitude;
|
||||
} else {
|
||||
throw is.invalidParameterError('minAmplitude', 'number between 0.001 and 1', options.minAmplitude);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!is.defined(options)) {
|
||||
function blur (sigma) {
|
||||
if (!is.defined(sigma)) {
|
||||
// No arguments: default to mild blur
|
||||
this.options.blurSigma = -1;
|
||||
} else if (is.bool(options)) {
|
||||
} else if (is.bool(sigma)) {
|
||||
// Boolean argument: apply mild blur?
|
||||
this.options.blurSigma = options ? -1 : 0;
|
||||
this.options.blurSigma = sigma ? -1 : 0;
|
||||
} else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) {
|
||||
// Numeric argument: specific sigma
|
||||
this.options.blurSigma = sigma;
|
||||
} else {
|
||||
throw is.invalidParameterError('sigma', 'number between 0.3 and 1000', sigma);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand foreground objects using the dilate morphological operator.
|
||||
*
|
||||
* @example
|
||||
* const output = await sharp(input)
|
||||
* .dilate()
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {Number} [width=1] dilation width in pixels.
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function dilate (width) {
|
||||
if (!is.defined(width)) {
|
||||
this.options.dilateWidth = 1;
|
||||
} else if (is.integer(width) && width > 0) {
|
||||
this.options.dilateWidth = width;
|
||||
} else {
|
||||
throw is.invalidParameterError('dilate', 'positive integer', dilate);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shrink foreground objects using the erode morphological operator.
|
||||
*
|
||||
* @example
|
||||
* const output = await sharp(input)
|
||||
* .erode()
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {Number} [width=1] erosion width in pixels.
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function erode (width) {
|
||||
if (!is.defined(width)) {
|
||||
this.options.erodeWidth = 1;
|
||||
} else if (is.integer(width) && width > 0) {
|
||||
this.options.erodeWidth = width;
|
||||
} else {
|
||||
throw is.invalidParameterError('erode', 'positive integer', erode);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
@ -504,32 +405,6 @@ function flatten (options) {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the image has an alpha channel
|
||||
* with all white pixel values made fully transparent.
|
||||
*
|
||||
* Existing alpha channel values for non-white pixels remain unchanged.
|
||||
*
|
||||
* This feature is experimental and the API may change.
|
||||
*
|
||||
* @since 0.32.1
|
||||
*
|
||||
* @example
|
||||
* await sharp(rgbInput)
|
||||
* .unflatten()
|
||||
* .toBuffer();
|
||||
*
|
||||
* @example
|
||||
* await sharp(rgbInput)
|
||||
* .threshold(128, { grayscale: false }) // converter bright pixels to white
|
||||
* .unflatten()
|
||||
* .toBuffer();
|
||||
*/
|
||||
function unflatten () {
|
||||
this.options.unflatten = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of `1/gamma`
|
||||
* then increasing the encoding (brighten) post-resize at a factor of `gamma`.
|
||||
@ -865,7 +740,7 @@ function linear (a, b) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Recombine the image with the specified matrix.
|
||||
* Recomb the image with the specified matrix.
|
||||
*
|
||||
* @since 0.21.1
|
||||
*
|
||||
@ -878,26 +753,28 @@ function linear (a, b) {
|
||||
* ])
|
||||
* .raw()
|
||||
* .toBuffer(function(err, data, info) {
|
||||
* // data contains the raw pixel data after applying the matrix
|
||||
* // data contains the raw pixel data after applying the recomb
|
||||
* // With this example input, a sepia filter has been applied
|
||||
* });
|
||||
*
|
||||
* @param {Array<Array<number>>} inputMatrix - 3x3 or 4x4 Recombination matrix
|
||||
* @param {Array<Array<number>>} inputMatrix - 3x3 Recombination matrix
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function recomb (inputMatrix) {
|
||||
if (!Array.isArray(inputMatrix)) {
|
||||
throw is.invalidParameterError('inputMatrix', 'array', inputMatrix);
|
||||
if (!Array.isArray(inputMatrix) || inputMatrix.length !== 3 ||
|
||||
inputMatrix[0].length !== 3 ||
|
||||
inputMatrix[1].length !== 3 ||
|
||||
inputMatrix[2].length !== 3
|
||||
) {
|
||||
// must pass in a kernel
|
||||
throw new Error('Invalid recombination matrix');
|
||||
}
|
||||
if (inputMatrix.length !== 3 && inputMatrix.length !== 4) {
|
||||
throw is.invalidParameterError('inputMatrix', '3x3 or 4x4 array', inputMatrix.length);
|
||||
}
|
||||
const recombMatrix = inputMatrix.flat().map(Number);
|
||||
if (recombMatrix.length !== 9 && recombMatrix.length !== 16) {
|
||||
throw is.invalidParameterError('inputMatrix', 'cardinality of 9 or 16', recombMatrix.length);
|
||||
}
|
||||
this.options.recombMatrix = recombMatrix;
|
||||
this.options.recombMatrix = [
|
||||
inputMatrix[0][0], inputMatrix[0][1], inputMatrix[0][2],
|
||||
inputMatrix[1][0], inputMatrix[1][1], inputMatrix[1][2],
|
||||
inputMatrix[2][0], inputMatrix[2][1], inputMatrix[2][2]
|
||||
].map(Number);
|
||||
return this;
|
||||
}
|
||||
|
||||
@ -933,7 +810,7 @@ function recomb (inputMatrix) {
|
||||
* .toBuffer();
|
||||
*
|
||||
* @example
|
||||
* // decrease brightness and saturation while also hue-rotating by 90 degrees
|
||||
* // decreate brightness and saturation while also hue-rotating by 90 degrees
|
||||
* const output = await sharp(input)
|
||||
* .modulate({
|
||||
* brightness: 0.5,
|
||||
@ -986,23 +863,18 @@ function modulate (options) {
|
||||
|
||||
/**
|
||||
* Decorate the Sharp prototype with operation-related functions.
|
||||
* @module Sharp
|
||||
* @private
|
||||
*/
|
||||
module.exports = function (Sharp) {
|
||||
Object.assign(Sharp.prototype, {
|
||||
autoOrient,
|
||||
rotate,
|
||||
flip,
|
||||
flop,
|
||||
affine,
|
||||
sharpen,
|
||||
erode,
|
||||
dilate,
|
||||
median,
|
||||
blur,
|
||||
flatten,
|
||||
unflatten,
|
||||
gamma,
|
||||
negate,
|
||||
normalise,
|
||||
|
434
lib/output.js
@ -3,7 +3,7 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
const path = require('node:path');
|
||||
const path = require('path');
|
||||
const is = require('./is');
|
||||
const sharp = require('./sharp');
|
||||
|
||||
@ -29,7 +29,7 @@ const formats = new Map([
|
||||
['jxl', 'jxl']
|
||||
]);
|
||||
|
||||
const jp2Regex = /\.(jp[2x]|j2[kc])$/i;
|
||||
const jp2Regex = /\.jp[2x]|j2[kc]$/i;
|
||||
|
||||
const errJp2Save = () => new Error('JP2 output requires libvips with support for OpenJPEG');
|
||||
|
||||
@ -43,7 +43,7 @@ const bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math
|
||||
* Note that raw pixel data is only supported for buffer output.
|
||||
*
|
||||
* By default all metadata will be removed, which includes EXIF-based orientation.
|
||||
* See {@link #withmetadata|withMetadata} for control over this.
|
||||
* See {@link withMetadata} for control over this.
|
||||
*
|
||||
* The caller is responsible for ensuring directory structures and permissions exist.
|
||||
*
|
||||
@ -65,7 +65,6 @@ const bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math
|
||||
* `channels` and `premultiplied` (indicating if premultiplication was used).
|
||||
* When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
|
||||
* When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region.
|
||||
* Animated output will also contain `pageHeight` and `pages`.
|
||||
* May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.
|
||||
* @returns {Promise<Object>} - when no callback is provided
|
||||
* @throws {Error} Invalid parameters
|
||||
@ -76,7 +75,7 @@ function toFile (fileOut, callback) {
|
||||
err = new Error('Missing output file path');
|
||||
} else if (is.string(this.options.input.file) && path.resolve(this.options.input.file) === path.resolve(fileOut)) {
|
||||
err = new Error('Cannot use same file for input and output');
|
||||
} else if (jp2Regex.test(path.extname(fileOut)) && !this.constructor.format.jp2k.output.file) {
|
||||
} else if (jp2Regex.test(fileOut) && !this.constructor.format.jp2k.output.file) {
|
||||
err = errJp2Save();
|
||||
}
|
||||
if (err) {
|
||||
@ -87,8 +86,7 @@ function toFile (fileOut, callback) {
|
||||
}
|
||||
} else {
|
||||
this.options.fileOut = fileOut;
|
||||
const stack = Error();
|
||||
return this._pipeline(callback, stack);
|
||||
return this._pipeline(callback);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
@ -97,12 +95,12 @@ function toFile (fileOut, callback) {
|
||||
* Write output to a Buffer.
|
||||
* JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.
|
||||
*
|
||||
* Use {@link #toformat|toFormat} or one of the format-specific functions such as {@link jpeg}, {@link png} etc. to set the output format.
|
||||
* Use {@link toFormat} or one of the format-specific functions such as {@link jpeg}, {@link png} etc. to set the output format.
|
||||
*
|
||||
* If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output.
|
||||
*
|
||||
* By default all metadata will be removed, which includes EXIF-based orientation.
|
||||
* See {@link #withmetadata|withMetadata} for control over this.
|
||||
* See {@link withMetadata} for control over this.
|
||||
*
|
||||
* `callback`, if present, gets three arguments `(err, data, info)` where:
|
||||
* - `err` is an error, if any.
|
||||
@ -110,7 +108,6 @@ function toFile (fileOut, callback) {
|
||||
* - `info` contains the output image `format`, `size` (bytes), `width`, `height`,
|
||||
* `channels` and `premultiplied` (indicating if premultiplication was used).
|
||||
* When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
|
||||
* Animated output will also contain `pageHeight` and `pages`.
|
||||
* May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.
|
||||
*
|
||||
* A `Promise` is returned when `callback` is not provided.
|
||||
@ -160,241 +157,35 @@ function toBuffer (options, callback) {
|
||||
this.options.resolveWithObject = false;
|
||||
}
|
||||
this.options.fileOut = '';
|
||||
const stack = Error();
|
||||
return this._pipeline(is.fn(options) ? options : callback, stack);
|
||||
return this._pipeline(is.fn(options) ? options : callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep all EXIF metadata from the input image in the output image.
|
||||
* Include all metadata (EXIF, XMP, IPTC) from the input image in the output image.
|
||||
* This will also convert to and add a web-friendly sRGB ICC profile unless a custom
|
||||
* output profile is provided.
|
||||
*
|
||||
* The default behaviour, when `withMetadata` is not used, is to convert to the device-independent
|
||||
* sRGB colour space and strip all metadata, including the removal of any ICC profile.
|
||||
*
|
||||
* EXIF metadata is unsupported for TIFF output.
|
||||
*
|
||||
* @since 0.33.0
|
||||
*
|
||||
* @example
|
||||
* const outputWithExif = await sharp(inputWithExif)
|
||||
* .keepExif()
|
||||
* .toBuffer();
|
||||
*
|
||||
* @returns {Sharp}
|
||||
*/
|
||||
function keepExif () {
|
||||
this.options.keepMetadata |= 0b00001;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set EXIF metadata in the output image, ignoring any EXIF in the input image.
|
||||
*
|
||||
* @since 0.33.0
|
||||
*
|
||||
* @example
|
||||
* const dataWithExif = await sharp(input)
|
||||
* .withExif({
|
||||
* IFD0: {
|
||||
* Copyright: 'The National Gallery'
|
||||
* },
|
||||
* IFD3: {
|
||||
* GPSLatitudeRef: 'N',
|
||||
* GPSLatitude: '51/1 30/1 3230/100',
|
||||
* GPSLongitudeRef: 'W',
|
||||
* GPSLongitude: '0/1 7/1 4366/100'
|
||||
* }
|
||||
* })
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {Object<string, Object<string, string>>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function withExif (exif) {
|
||||
if (is.object(exif)) {
|
||||
for (const [ifd, entries] of Object.entries(exif)) {
|
||||
if (is.object(entries)) {
|
||||
for (const [k, v] of Object.entries(entries)) {
|
||||
if (is.string(v)) {
|
||||
this.options.withExif[`exif-${ifd.toLowerCase()}-${k}`] = v;
|
||||
} else {
|
||||
throw is.invalidParameterError(`${ifd}.${k}`, 'string', v);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw is.invalidParameterError(ifd, 'object', entries);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw is.invalidParameterError('exif', 'object', exif);
|
||||
}
|
||||
this.options.withExifMerge = false;
|
||||
return this.keepExif();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update EXIF metadata from the input image in the output image.
|
||||
*
|
||||
* @since 0.33.0
|
||||
*
|
||||
* @example
|
||||
* const dataWithMergedExif = await sharp(inputWithExif)
|
||||
* .withExifMerge({
|
||||
* IFD0: {
|
||||
* Copyright: 'The National Gallery'
|
||||
* }
|
||||
* })
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {Object<string, Object<string, string>>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function withExifMerge (exif) {
|
||||
this.withExif(exif);
|
||||
this.options.withExifMerge = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep ICC profile from the input image in the output image.
|
||||
*
|
||||
* Where necessary, will attempt to convert the output colour space to match the profile.
|
||||
*
|
||||
* @since 0.33.0
|
||||
*
|
||||
* @example
|
||||
* const outputWithIccProfile = await sharp(inputWithIccProfile)
|
||||
* .keepIccProfile()
|
||||
* .toBuffer();
|
||||
*
|
||||
* @returns {Sharp}
|
||||
*/
|
||||
function keepIccProfile () {
|
||||
this.options.keepMetadata |= 0b01000;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform using an ICC profile and attach to the output image.
|
||||
*
|
||||
* This can either be an absolute filesystem path or
|
||||
* built-in profile name (`srgb`, `p3`, `cmyk`).
|
||||
*
|
||||
* @since 0.33.0
|
||||
*
|
||||
* @example
|
||||
* const outputWithP3 = await sharp(input)
|
||||
* .withIccProfile('p3')
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {string} icc - Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk).
|
||||
* @param {Object} [options]
|
||||
* @param {number} [options.attach=true] Should the ICC profile be included in the output image metadata?
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function withIccProfile (icc, options) {
|
||||
if (is.string(icc)) {
|
||||
this.options.withIccProfile = icc;
|
||||
} else {
|
||||
throw is.invalidParameterError('icc', 'string', icc);
|
||||
}
|
||||
this.keepIccProfile();
|
||||
if (is.object(options)) {
|
||||
if (is.defined(options.attach)) {
|
||||
if (is.bool(options.attach)) {
|
||||
if (!options.attach) {
|
||||
this.options.keepMetadata &= ~0b01000;
|
||||
}
|
||||
} else {
|
||||
throw is.invalidParameterError('attach', 'boolean', options.attach);
|
||||
}
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep XMP metadata from the input image in the output image.
|
||||
*
|
||||
* @since 0.34.3
|
||||
*
|
||||
* @example
|
||||
* const outputWithXmp = await sharp(inputWithXmp)
|
||||
* .keepXmp()
|
||||
* .toBuffer();
|
||||
*
|
||||
* @returns {Sharp}
|
||||
*/
|
||||
function keepXmp () {
|
||||
this.options.keepMetadata |= 0b00010;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set XMP metadata in the output image.
|
||||
*
|
||||
* Supported by PNG, JPEG, WebP, and TIFF output.
|
||||
*
|
||||
* @since 0.34.3
|
||||
*
|
||||
* @example
|
||||
* const xmpString = `
|
||||
* <?xml version="1.0"?>
|
||||
* <x:xmpmeta xmlns:x="adobe:ns:meta/">
|
||||
* <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
* <rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||
* <dc:creator><rdf:Seq><rdf:li>John Doe</rdf:li></rdf:Seq></dc:creator>
|
||||
* </rdf:Description>
|
||||
* </rdf:RDF>
|
||||
* </x:xmpmeta>`;
|
||||
*
|
||||
* const data = await sharp(input)
|
||||
* .withXmp(xmpString)
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {string} xmp String containing XMP metadata to be embedded in the output image.
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function withXmp (xmp) {
|
||||
if (is.string(xmp) && xmp.length > 0) {
|
||||
this.options.withXmp = xmp;
|
||||
this.options.keepMetadata |= 0b00010;
|
||||
} else {
|
||||
throw is.invalidParameterError('xmp', 'non-empty string', xmp);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image.
|
||||
*
|
||||
* The default behaviour, when `keepMetadata` is not used, is to convert to the device-independent
|
||||
* sRGB colour space and strip all metadata, including the removal of any ICC profile.
|
||||
*
|
||||
* @since 0.33.0
|
||||
*
|
||||
* @example
|
||||
* const outputWithMetadata = await sharp(inputWithMetadata)
|
||||
* .keepMetadata()
|
||||
* .toBuffer();
|
||||
*
|
||||
* @returns {Sharp}
|
||||
*/
|
||||
function keepMetadata () {
|
||||
this.options.keepMetadata = 0b11111;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep most metadata (EXIF, XMP, IPTC) from the input image in the output image.
|
||||
*
|
||||
* This will also convert to and add a web-friendly sRGB ICC profile if appropriate.
|
||||
*
|
||||
* Allows orientation and density to be set or updated.
|
||||
*
|
||||
* @example
|
||||
* const outputSrgbWithMetadata = await sharp(inputRgbWithMetadata)
|
||||
* sharp('input.jpg')
|
||||
* .withMetadata()
|
||||
* .toFile('output-with-metadata.jpg')
|
||||
* .then(info => { ... });
|
||||
*
|
||||
* @example
|
||||
* // Set "IFD0-Copyright" in output EXIF metadata
|
||||
* const data = await sharp(input)
|
||||
* .withMetadata({
|
||||
* exif: {
|
||||
* IFD0: {
|
||||
* Copyright: 'Wernham Hogg'
|
||||
* }
|
||||
* }
|
||||
* })
|
||||
* .toBuffer();
|
||||
*
|
||||
* @example
|
||||
@ -404,14 +195,15 @@ function keepMetadata () {
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @param {number} [options.orientation] Used to update the EXIF `Orientation` tag, integer between 1 and 8.
|
||||
* @param {number} [options.orientation] value between 1 and 8, used to update the EXIF `Orientation` tag.
|
||||
* @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).
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function withMetadata (options) {
|
||||
this.keepMetadata();
|
||||
this.withIccProfile('srgb');
|
||||
this.options.withMetadata = is.bool(options) ? options : true;
|
||||
if (is.object(options)) {
|
||||
if (is.defined(options.orientation)) {
|
||||
if (is.integer(options.orientation) && is.inRange(options.orientation, 1, 8)) {
|
||||
@ -428,10 +220,30 @@ function withMetadata (options) {
|
||||
}
|
||||
}
|
||||
if (is.defined(options.icc)) {
|
||||
this.withIccProfile(options.icc);
|
||||
if (is.string(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)) {
|
||||
this.withExifMerge(options.exif);
|
||||
if (is.object(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;
|
||||
@ -559,14 +371,10 @@ function jpeg (options) {
|
||||
/**
|
||||
* Use these PNG options for output image.
|
||||
*
|
||||
* By default, PNG output is full colour at 8 bits per pixel.
|
||||
*
|
||||
* By default, PNG output is full colour at 8 or 16 bits per pixel.
|
||||
* Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel.
|
||||
* Set `palette` to `true` for slower, indexed PNG output.
|
||||
*
|
||||
* For 16 bits per pixel output, convert to `rgb16` via
|
||||
* {@link /api-colour#tocolourspace|toColourspace}.
|
||||
*
|
||||
* @example
|
||||
* // Convert any input to full colour PNG output
|
||||
* const data = await sharp(input)
|
||||
@ -579,13 +387,6 @@ function jpeg (options) {
|
||||
* .png({ palette: true })
|
||||
* .toBuffer();
|
||||
*
|
||||
* @example
|
||||
* // Output 16 bits per pixel RGB(A)
|
||||
* const data = await sharp(input)
|
||||
* .toColourspace('rgb16')
|
||||
* .png()
|
||||
* .toBuffer();
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @param {boolean} [options.progressive=false] - use progressive (interlace) scan
|
||||
* @param {number} [options.compressionLevel=6] - zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest)
|
||||
@ -676,8 +477,6 @@ function png (options) {
|
||||
* @param {boolean} [options.lossless=false] - use lossless compression mode
|
||||
* @param {boolean} [options.nearLossless=false] - use near_lossless compression mode
|
||||
* @param {boolean} [options.smartSubsample=false] - use high quality chroma subsampling
|
||||
* @param {boolean} [options.smartDeblock=false] - auto-adjust the deblocking filter, can improve low contrast edges (slow)
|
||||
* @param {string} [options.preset='default'] - named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text
|
||||
* @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 6 (slowest)
|
||||
* @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation
|
||||
* @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)
|
||||
@ -712,16 +511,6 @@ function webp (options) {
|
||||
if (is.defined(options.smartSubsample)) {
|
||||
this._setBooleanOption('webpSmartSubsample', options.smartSubsample);
|
||||
}
|
||||
if (is.defined(options.smartDeblock)) {
|
||||
this._setBooleanOption('webpSmartDeblock', options.smartDeblock);
|
||||
}
|
||||
if (is.defined(options.preset)) {
|
||||
if (is.string(options.preset) && is.inArray(options.preset, ['default', 'photo', 'picture', 'drawing', 'icon', 'text'])) {
|
||||
this.options.webpPreset = options.preset;
|
||||
} else {
|
||||
throw is.invalidParameterError('preset', 'one of: default, photo, picture, drawing, icon, text', options.preset);
|
||||
}
|
||||
}
|
||||
if (is.defined(options.effort)) {
|
||||
if (is.integer(options.effort) && is.inRange(options.effort, 0, 6)) {
|
||||
this.options.webpEffort = options.effort;
|
||||
@ -782,7 +571,6 @@ function webp (options) {
|
||||
* @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most)
|
||||
* @param {number} [options.interFrameMaxError=0] - maximum inter-frame error for transparency, between 0 (lossless) and 32
|
||||
* @param {number} [options.interPaletteMaxError=3] - maximum inter-palette error for palette reuse, between 0 and 256
|
||||
* @param {boolean} [options.keepDuplicateFrames=false] - keep duplicate frames in the output instead of combining them
|
||||
* @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation
|
||||
* @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)
|
||||
* @param {boolean} [options.force=true] - force GIF output, otherwise attempt to use input format
|
||||
@ -833,19 +621,11 @@ function gif (options) {
|
||||
throw is.invalidParameterError('interPaletteMaxError', 'number between 0.0 and 256.0', options.interPaletteMaxError);
|
||||
}
|
||||
}
|
||||
if (is.defined(options.keepDuplicateFrames)) {
|
||||
if (is.bool(options.keepDuplicateFrames)) {
|
||||
this._setBooleanOption('gifKeepDuplicateFrames', options.keepDuplicateFrames);
|
||||
} else {
|
||||
throw is.invalidParameterError('keepDuplicateFrames', 'boolean', options.keepDuplicateFrames);
|
||||
}
|
||||
}
|
||||
}
|
||||
trySetAnimationOptions(options, this.options);
|
||||
return this._updateFormatOut('gif', options);
|
||||
}
|
||||
|
||||
/* istanbul ignore next */
|
||||
/**
|
||||
* Use these JP2 options for output image.
|
||||
*
|
||||
@ -879,6 +659,7 @@ function gif (options) {
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid options
|
||||
*/
|
||||
/* istanbul ignore next */
|
||||
function jp2 (options) {
|
||||
if (!this.constructor.format.jp2k.output.buffer) {
|
||||
throw errJp2Save();
|
||||
@ -959,8 +740,7 @@ function trySetAnimationOptions (source, target) {
|
||||
/**
|
||||
* Use these TIFF options for output image.
|
||||
*
|
||||
* The `density` can be set in pixels/inch via {@link #withmetadata|withMetadata}
|
||||
* instead of providing `xres` and `yres` in pixels/mm.
|
||||
* The `density` can be set in pixels/inch via {@link withMetadata} instead of providing `xres` and `yres` in pixels/mm.
|
||||
*
|
||||
* @example
|
||||
* // Convert SVG input to LZW-compressed, 1 bit per pixel TIFF output
|
||||
@ -985,7 +765,6 @@ function trySetAnimationOptions (source, target) {
|
||||
* @param {number} [options.yres=1.0] - vertical resolution in pixels/mm
|
||||
* @param {string} [options.resolutionUnit='inch'] - resolution unit options: inch, cm
|
||||
* @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}
|
||||
* @throws {Error} Invalid options
|
||||
*/
|
||||
@ -1023,10 +802,6 @@ function tiff (options) {
|
||||
throw is.invalidParameterError('tileHeight', 'integer greater than zero', options.tileHeight);
|
||||
}
|
||||
}
|
||||
// miniswhite
|
||||
if (is.defined(options.miniswhite)) {
|
||||
this._setBooleanOption('tiffMiniswhite', options.miniswhite);
|
||||
}
|
||||
// pyramid
|
||||
if (is.defined(options.pyramid)) {
|
||||
this._setBooleanOption('tiffPyramid', options.pyramid);
|
||||
@ -1077,11 +852,10 @@ function tiff (options) {
|
||||
/**
|
||||
* Use these AVIF options for output image.
|
||||
*
|
||||
* AVIF image sequences are not supported.
|
||||
* Prebuilt binaries support a bitdepth of 8 only.
|
||||
* Whilst it is possible to create AVIF images smaller than 16x16 pixels,
|
||||
* most web browsers do not display these properly.
|
||||
*
|
||||
* This feature is experimental on the Windows ARM64 platform
|
||||
* and requires a CPU with ARM64v8.4 or later.
|
||||
* AVIF image sequences are not supported.
|
||||
*
|
||||
* @example
|
||||
* const data = await sharp(input)
|
||||
@ -1100,7 +874,6 @@ function tiff (options) {
|
||||
* @param {boolean} [options.lossless=false] - use lossless compression
|
||||
* @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 {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid options
|
||||
*/
|
||||
@ -1121,23 +894,17 @@ function avif (options) {
|
||||
*
|
||||
* @since 0.23.0
|
||||
*
|
||||
* @param {Object} options - output options
|
||||
* @param {string} options.compression - compression format: av1, hevc
|
||||
* @param {Object} [options] - output options
|
||||
* @param {number} [options.quality=50] - quality, integer 1-100
|
||||
* @param {string} [options.compression='av1'] - compression format: av1, hevc
|
||||
* @param {boolean} [options.lossless=false] - use lossless compression
|
||||
* @param {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 {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid options
|
||||
*/
|
||||
function heif (options) {
|
||||
if (is.object(options)) {
|
||||
if (is.string(options.compression) && is.inArray(options.compression, ['av1', 'hevc'])) {
|
||||
this.options.heifCompression = options.compression;
|
||||
} else {
|
||||
throw is.invalidParameterError('compression', 'one of: av1, hevc', options.compression);
|
||||
}
|
||||
if (is.defined(options.quality)) {
|
||||
if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {
|
||||
this.options.heifQuality = options.quality;
|
||||
@ -1152,6 +919,13 @@ function heif (options) {
|
||||
throw is.invalidParameterError('lossless', 'boolean', options.lossless);
|
||||
}
|
||||
}
|
||||
if (is.defined(options.compression)) {
|
||||
if (is.string(options.compression) && is.inArray(options.compression, ['av1', 'hevc'])) {
|
||||
this.options.heifCompression = options.compression;
|
||||
} else {
|
||||
throw is.invalidParameterError('compression', 'one of: av1, hevc', options.compression);
|
||||
}
|
||||
}
|
||||
if (is.defined(options.effort)) {
|
||||
if (is.integer(options.effort) && is.inRange(options.effort, 0, 9)) {
|
||||
this.options.heifEffort = options.effort;
|
||||
@ -1166,18 +940,6 @@ function heif (options) {
|
||||
throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);
|
||||
}
|
||||
}
|
||||
if (is.defined(options.bitdepth)) {
|
||||
if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [8, 10, 12])) {
|
||||
if (options.bitdepth !== 8 && this.constructor.versions.heif) {
|
||||
throw is.invalidParameterError('bitdepth when using prebuilt binaries', 8, options.bitdepth);
|
||||
}
|
||||
this.options.heifBitdepth = options.bitdepth;
|
||||
} else {
|
||||
throw is.invalidParameterError('bitdepth', '8, 10 or 12', options.bitdepth);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw is.invalidParameterError('options', 'Object', options);
|
||||
}
|
||||
return this._updateFormatOut('heif', options);
|
||||
}
|
||||
@ -1191,6 +953,8 @@ function heif (options) {
|
||||
* The prebuilt binaries do not include this - see
|
||||
* {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}.
|
||||
*
|
||||
* Image metadata (EXIF, XMP) is unsupported.
|
||||
*
|
||||
* @since 0.31.3
|
||||
*
|
||||
* @param {Object} [options] - output options
|
||||
@ -1198,9 +962,7 @@ function heif (options) {
|
||||
* @param {number} [options.quality] - calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified
|
||||
* @param {number} [options.decodingTier=0] - target decode speed tier, between 0 (highest quality) and 4 (lowest quality)
|
||||
* @param {boolean} [options.lossless=false] - use lossless compression
|
||||
* @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 9 (slowest)
|
||||
* @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation
|
||||
* @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)
|
||||
* @param {number} [options.effort=7] - CPU effort, between 3 (fastest) and 9 (slowest)
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid options
|
||||
*/
|
||||
@ -1237,14 +999,13 @@ function jxl (options) {
|
||||
}
|
||||
}
|
||||
if (is.defined(options.effort)) {
|
||||
if (is.integer(options.effort) && is.inRange(options.effort, 1, 9)) {
|
||||
if (is.integer(options.effort) && is.inRange(options.effort, 3, 9)) {
|
||||
this.options.jxlEffort = options.effort;
|
||||
} else {
|
||||
throw is.invalidParameterError('effort', 'integer between 1 and 9', options.effort);
|
||||
throw is.invalidParameterError('effort', 'integer between 3 and 9', options.effort);
|
||||
}
|
||||
}
|
||||
}
|
||||
trySetAnimationOptions(options, this.options);
|
||||
return this._updateFormatOut('jxl', options);
|
||||
}
|
||||
|
||||
@ -1270,7 +1031,6 @@ function jxl (options) {
|
||||
*
|
||||
* @param {Object} [options] - output options
|
||||
* @param {string} [options.depth='uchar'] - bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid options
|
||||
*/
|
||||
function raw (options) {
|
||||
@ -1296,6 +1056,10 @@ function raw (options) {
|
||||
*
|
||||
* The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`.
|
||||
*
|
||||
* Requires libvips compiled with support for libgsf.
|
||||
* The prebuilt binaries do not include this - see
|
||||
* {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}.
|
||||
*
|
||||
* @example
|
||||
* sharp('input.tiff')
|
||||
* .png()
|
||||
@ -1324,7 +1088,7 @@ function raw (options) {
|
||||
* @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} [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. 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 {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 {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 {boolean} [options.centre=false] centre image in tile.
|
||||
@ -1505,8 +1269,7 @@ function _read () {
|
||||
/* istanbul ignore else */
|
||||
if (!this.options.streamOut) {
|
||||
this.options.streamOut = true;
|
||||
const stack = Error();
|
||||
this._pipeline(undefined, stack);
|
||||
this._pipeline();
|
||||
}
|
||||
}
|
||||
|
||||
@ -1515,30 +1278,18 @@ function _read () {
|
||||
* Supports callback, stream and promise variants
|
||||
* @private
|
||||
*/
|
||||
function _pipeline (callback, stack) {
|
||||
function _pipeline (callback) {
|
||||
if (typeof callback === 'function') {
|
||||
// output=file/buffer
|
||||
if (this._isStreamInput()) {
|
||||
// output=file/buffer, input=stream
|
||||
this.on('finish', () => {
|
||||
this._flattenBufferIn();
|
||||
sharp.pipeline(this.options, (err, data, info) => {
|
||||
if (err) {
|
||||
callback(is.nativeError(err, stack));
|
||||
} else {
|
||||
callback(null, data, info);
|
||||
}
|
||||
});
|
||||
sharp.pipeline(this.options, callback);
|
||||
});
|
||||
} else {
|
||||
// output=file/buffer, input=file/buffer
|
||||
sharp.pipeline(this.options, (err, data, info) => {
|
||||
if (err) {
|
||||
callback(is.nativeError(err, stack));
|
||||
} else {
|
||||
callback(null, data, info);
|
||||
}
|
||||
});
|
||||
sharp.pipeline(this.options, callback);
|
||||
}
|
||||
return this;
|
||||
} else if (this.options.streamOut) {
|
||||
@ -1549,7 +1300,7 @@ function _pipeline (callback, stack) {
|
||||
this._flattenBufferIn();
|
||||
sharp.pipeline(this.options, (err, data, info) => {
|
||||
if (err) {
|
||||
this.emit('error', is.nativeError(err, stack));
|
||||
this.emit('error', err);
|
||||
} else {
|
||||
this.emit('info', info);
|
||||
this.push(data);
|
||||
@ -1565,7 +1316,7 @@ function _pipeline (callback, stack) {
|
||||
// output=stream, input=file/buffer
|
||||
sharp.pipeline(this.options, (err, data, info) => {
|
||||
if (err) {
|
||||
this.emit('error', is.nativeError(err, stack));
|
||||
this.emit('error', err);
|
||||
} else {
|
||||
this.emit('info', info);
|
||||
this.push(data);
|
||||
@ -1584,7 +1335,7 @@ function _pipeline (callback, stack) {
|
||||
this._flattenBufferIn();
|
||||
sharp.pipeline(this.options, (err, data, info) => {
|
||||
if (err) {
|
||||
reject(is.nativeError(err, stack));
|
||||
reject(err);
|
||||
} else {
|
||||
if (this.options.resolveWithObject) {
|
||||
resolve({ data, info });
|
||||
@ -1600,10 +1351,10 @@ function _pipeline (callback, stack) {
|
||||
return new Promise((resolve, reject) => {
|
||||
sharp.pipeline(this.options, (err, data, info) => {
|
||||
if (err) {
|
||||
reject(is.nativeError(err, stack));
|
||||
reject(err);
|
||||
} else {
|
||||
if (this.options.resolveWithObject) {
|
||||
resolve({ data, info });
|
||||
resolve({ data: data, info: info });
|
||||
} else {
|
||||
resolve(data);
|
||||
}
|
||||
@ -1616,7 +1367,6 @@ function _pipeline (callback, stack) {
|
||||
|
||||
/**
|
||||
* Decorate the Sharp prototype with output-related functions.
|
||||
* @module Sharp
|
||||
* @private
|
||||
*/
|
||||
module.exports = function (Sharp) {
|
||||
@ -1624,14 +1374,6 @@ module.exports = function (Sharp) {
|
||||
// Public
|
||||
toFile,
|
||||
toBuffer,
|
||||
keepExif,
|
||||
withExif,
|
||||
withExifMerge,
|
||||
keepIccProfile,
|
||||
withIccProfile,
|
||||
keepXmp,
|
||||
withXmp,
|
||||
keepMetadata,
|
||||
withMetadata,
|
||||
toFormat,
|
||||
jpeg,
|
||||
|
30
lib/platform.js
Normal file
@ -0,0 +1,30 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
const detectLibc = require('detect-libc');
|
||||
|
||||
const env = process.env;
|
||||
|
||||
module.exports = function () {
|
||||
const arch = env.npm_config_arch || process.arch;
|
||||
const platform = env.npm_config_platform || process.platform;
|
||||
const libc = process.env.npm_config_libc ||
|
||||
/* istanbul ignore next */
|
||||
(detectLibc.isNonGlibcLinuxSync() ? detectLibc.familySync() : '');
|
||||
const libcId = platform !== 'linux' || libc === detectLibc.GLIBC ? '' : libc;
|
||||
|
||||
const platformId = [`${platform}${libcId}`];
|
||||
|
||||
if (arch === 'arm') {
|
||||
const fallback = process.versions.electron ? '7' : '6';
|
||||
platformId.push(`armv${env.npm_config_arm_version || process.config.variables.arm_version || fallback}`);
|
||||
} else if (arch === 'arm64') {
|
||||
platformId.push(`arm64v${env.npm_config_arm_version || '8'}`);
|
||||
} else {
|
||||
platformId.push(arch);
|
||||
}
|
||||
|
||||
return platformId.join('-');
|
||||
};
|
114
lib/resize.js
@ -68,13 +68,10 @@ const strategy = {
|
||||
*/
|
||||
const kernel = {
|
||||
nearest: 'nearest',
|
||||
linear: 'linear',
|
||||
cubic: 'cubic',
|
||||
mitchell: 'mitchell',
|
||||
lanczos2: 'lanczos2',
|
||||
lanczos3: 'lanczos3',
|
||||
mks2013: 'mks2013',
|
||||
mks2021: 'mks2021'
|
||||
lanczos3: 'lanczos3'
|
||||
};
|
||||
|
||||
/**
|
||||
@ -107,7 +104,7 @@ const mapFitToCanvas = {
|
||||
* @private
|
||||
*/
|
||||
function isRotationExpected (options) {
|
||||
return (options.angle % 360) !== 0 || options.input.autoOrient === true || options.rotationAngle !== 0;
|
||||
return (options.angle % 360) !== 0 || options.useExifOrientation === true || options.rotationAngle !== 0;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -129,7 +126,7 @@ function isResizeExpected (options) {
|
||||
*
|
||||
* Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property.
|
||||
*
|
||||
* <img alt="Examples of various values for the fit property when resizing" width="100%" style="aspect-ratio: 998/243" src="/api-resize-fit.svg">
|
||||
* <img alt="Examples of various values for the fit property when resizing" width="100%" style="aspect-ratio: 998/243" src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/api-resize-fit.png">
|
||||
*
|
||||
* When using a **fit** of `cover` or `contain`, the default **position** is `centre`. Other options are:
|
||||
* - `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`.
|
||||
@ -138,23 +135,17 @@ 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.
|
||||
*
|
||||
* The strategy-based approach initially resizes so one dimension is at its target length
|
||||
* The experimental strategy-based approach resizes so one dimension is at its target length
|
||||
* then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.
|
||||
* - `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29).
|
||||
* - `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
|
||||
*
|
||||
* Possible downsizing kernels are:
|
||||
* Possible interpolation kernels are:
|
||||
* - `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation).
|
||||
* - `linear`: Use a [triangle filter](https://en.wikipedia.org/wiki/Triangular_function).
|
||||
* - `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline).
|
||||
* - `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf).
|
||||
* - `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`.
|
||||
* - `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
|
||||
* - `mks2013`: Use a [Magic Kernel Sharp](https://johncostella.com/magic/mks.pdf) 2013 kernel, as adopted by Facebook.
|
||||
* - `mks2021`: Use a Magic Kernel Sharp 2021 kernel, with more accurate (reduced) sharpening than the 2013 version.
|
||||
*
|
||||
* When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators.
|
||||
* Downsampling kernels without a matching upsampling interpolator map to `cubic`.
|
||||
*
|
||||
* Only one resize can occur per pipeline.
|
||||
* Previous calls to `resize` in the same pipeline will be ignored.
|
||||
@ -248,7 +239,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.position='centre'] - A position, gravity or strategy to use when `fit` is `cover` or `contain`.
|
||||
* @param {String|Object} [options.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency.
|
||||
* @param {String} [options.kernel='lanczos3'] - The kernel to use for image reduction and the inferred interpolator to use for upsampling. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load.
|
||||
* @param {String} [options.kernel='lanczos3'] - The kernel to use for image reduction. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load.
|
||||
* @param {Boolean} [options.withoutEnlargement=false] - Do not scale up if the width *or* height are already less than the target dimensions, equivalent to GraphicsMagick's `>` geometry option. This may result in output dimensions smaller than the target dimensions.
|
||||
* @param {Boolean} [options.withoutReduction=false] - Do not scale down if the width *or* height are already greater than the target dimensions, equivalent to GraphicsMagick's `<` geometry option. This may still result in a crop to reach the target dimensions.
|
||||
* @param {Boolean} [options.fastShrinkOnLoad=true] - Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern or round-down of an auto-scaled dimension.
|
||||
@ -259,9 +250,6 @@ function resize (widthOrOptions, height, options) {
|
||||
if (isResizeExpected(this.options)) {
|
||||
this.options.debuglog('ignoring previous resize options');
|
||||
}
|
||||
if (this.options.widthPost !== -1) {
|
||||
this.options.debuglog('operation order will be: extract, resize, extract');
|
||||
}
|
||||
if (is.defined(widthOrOptions)) {
|
||||
if (is.object(widthOrOptions) && !is.defined(options)) {
|
||||
options = widthOrOptions;
|
||||
@ -449,7 +437,7 @@ function extend (extend) {
|
||||
*
|
||||
* - Use `extract` before `resize` for pre-resize extraction.
|
||||
* - Use `extract` after `resize` for post-resize extraction.
|
||||
* - Use `extract` twice and `resize` once for extract-then-resize-then-extract in a fixed operation order.
|
||||
* - Use `extract` before and after for both.
|
||||
*
|
||||
* @example
|
||||
* sharp(input)
|
||||
@ -503,67 +491,70 @@ function extract (options) {
|
||||
*
|
||||
* If the result of this operation would trim an image to nothing then no change is made.
|
||||
*
|
||||
* The `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` properties.
|
||||
* The `info` response Object, obtained from callback of `.toFile()` or `.toBuffer()`,
|
||||
* will contain `trimOffsetLeft` and `trimOffsetTop` properties.
|
||||
*
|
||||
* @example
|
||||
* // Trim pixels with a colour similar to that of the top-left pixel.
|
||||
* await sharp(input)
|
||||
* sharp(input)
|
||||
* .trim()
|
||||
* .toFile(output);
|
||||
*
|
||||
* .toFile(output, function(err, info) {
|
||||
* ...
|
||||
* });
|
||||
* @example
|
||||
* // Trim pixels with the exact same colour as that of the top-left pixel.
|
||||
* await sharp(input)
|
||||
* .trim({
|
||||
* threshold: 0
|
||||
* })
|
||||
* .toFile(output);
|
||||
*
|
||||
* sharp(input)
|
||||
* .trim(0)
|
||||
* .toFile(output, function(err, info) {
|
||||
* ...
|
||||
* });
|
||||
* @example
|
||||
* // Assume input is line art and trim only pixels with a similar colour to red.
|
||||
* const output = await sharp(input)
|
||||
* .trim({
|
||||
* background: "#FF0000",
|
||||
* lineArt: true
|
||||
* })
|
||||
* .toBuffer();
|
||||
*
|
||||
* // Trim only pixels with a similar colour to red.
|
||||
* sharp(input)
|
||||
* .trim("#FF0000")
|
||||
* .toFile(output, function(err, info) {
|
||||
* ...
|
||||
* });
|
||||
* @example
|
||||
* // Trim all "yellow-ish" pixels, being more lenient with the higher threshold.
|
||||
* const output = await sharp(input)
|
||||
* sharp(input)
|
||||
* .trim({
|
||||
* background: "yellow",
|
||||
* threshold: 42,
|
||||
* })
|
||||
* .toBuffer();
|
||||
* .toFile(output, function(err, info) {
|
||||
* ...
|
||||
* });
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @param {string|Object} [options.background='top-left pixel'] - Background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel.
|
||||
* @param {number} [options.threshold=10] - Allowed difference from the above colour, a positive number.
|
||||
* @param {boolean} [options.lineArt=false] - Does the input more closely resemble line art (e.g. vector) rather than being photographic?
|
||||
* @param {string|number|Object} trim - the specific background colour to trim, the threshold for doing so or an Object with both.
|
||||
* @param {string|Object} [trim.background='top-left pixel'] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel.
|
||||
* @param {number} [trim.threshold=10] - the allowed difference from the above colour, a positive number.
|
||||
* @returns {Sharp}
|
||||
* @throws {Error} Invalid parameters
|
||||
*/
|
||||
function trim (options) {
|
||||
this.options.trimThreshold = 10;
|
||||
if (is.defined(options)) {
|
||||
if (is.object(options)) {
|
||||
if (is.defined(options.background)) {
|
||||
this._setBackgroundColourOption('trimBackground', options.background);
|
||||
}
|
||||
if (is.defined(options.threshold)) {
|
||||
if (is.number(options.threshold) && options.threshold >= 0) {
|
||||
this.options.trimThreshold = options.threshold;
|
||||
} else {
|
||||
throw is.invalidParameterError('threshold', 'positive number', options.threshold);
|
||||
}
|
||||
}
|
||||
if (is.defined(options.lineArt)) {
|
||||
this._setBooleanOption('trimLineArt', options.lineArt);
|
||||
}
|
||||
function trim (trim) {
|
||||
if (!is.defined(trim)) {
|
||||
this.options.trimThreshold = 10;
|
||||
} else if (is.string(trim)) {
|
||||
this._setBackgroundColourOption('trimBackground', trim);
|
||||
this.options.trimThreshold = 10;
|
||||
} else if (is.number(trim)) {
|
||||
if (trim >= 0) {
|
||||
this.options.trimThreshold = trim;
|
||||
} else {
|
||||
throw is.invalidParameterError('trim', 'object', options);
|
||||
throw is.invalidParameterError('threshold', 'positive number', trim);
|
||||
}
|
||||
} else if (is.object(trim)) {
|
||||
this._setBackgroundColourOption('trimBackground', trim.background);
|
||||
if (!is.defined(trim.threshold)) {
|
||||
this.options.trimThreshold = 10;
|
||||
} else if (is.number(trim.threshold) && trim.threshold >= 0) {
|
||||
this.options.trimThreshold = trim.threshold;
|
||||
} else {
|
||||
throw is.invalidParameterError('threshold', 'positive number', trim);
|
||||
}
|
||||
} else {
|
||||
throw is.invalidParameterError('trim', 'string, number or object', trim);
|
||||
}
|
||||
if (isRotationExpected(this.options)) {
|
||||
this.options.rotateBeforePreExtract = true;
|
||||
@ -573,7 +564,6 @@ function trim (options) {
|
||||
|
||||
/**
|
||||
* Decorate the Sharp prototype with resize-related functions.
|
||||
* @module Sharp
|
||||
* @private
|
||||
*/
|
||||
module.exports = function (Sharp) {
|
||||
|
130
lib/sharp.js
@ -3,120 +3,36 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
// Inspects the runtime environment and exports the relevant sharp.node binary
|
||||
|
||||
const { familySync, versionSync } = require('detect-libc');
|
||||
|
||||
const { runtimePlatformArch, isUnsupportedNodeRuntime, prebuiltPlatforms, minimumLibvipsVersion } = require('./libvips');
|
||||
const runtimePlatform = runtimePlatformArch();
|
||||
|
||||
const paths = [
|
||||
`../src/build/Release/sharp-${runtimePlatform}.node`,
|
||||
'../src/build/Release/sharp-wasm32.node',
|
||||
`@img/sharp-${runtimePlatform}/sharp.node`,
|
||||
'@img/sharp-wasm32/sharp.node'
|
||||
];
|
||||
|
||||
let path, sharp;
|
||||
const errors = [];
|
||||
for (path of paths) {
|
||||
try {
|
||||
sharp = require(path);
|
||||
break;
|
||||
} catch (err) {
|
||||
/* istanbul ignore next */
|
||||
errors.push(err);
|
||||
}
|
||||
}
|
||||
const platformAndArch = require('./platform')();
|
||||
|
||||
/* istanbul ignore next */
|
||||
if (sharp && path.startsWith('@img/sharp-linux-x64') && !sharp._isUsingX64V2()) {
|
||||
const err = new Error('Prebuilt binaries for linux-x64 require v2 microarchitecture');
|
||||
err.code = 'Unsupported CPU';
|
||||
errors.push(err);
|
||||
sharp = null;
|
||||
}
|
||||
|
||||
/* istanbul ignore next */
|
||||
if (sharp) {
|
||||
module.exports = sharp;
|
||||
} else {
|
||||
const [isLinux, isMacOs, isWindows] = ['linux', 'darwin', 'win32'].map(os => runtimePlatform.startsWith(os));
|
||||
|
||||
const help = [`Could not load the "sharp" module using the ${runtimePlatform} runtime`];
|
||||
errors.forEach(err => {
|
||||
if (err.code !== 'MODULE_NOT_FOUND') {
|
||||
help.push(`${err.code}: ${err.message}`);
|
||||
}
|
||||
});
|
||||
const messages = errors.map(err => err.message).join(' ');
|
||||
help.push('Possible solutions:');
|
||||
// Common error messages
|
||||
if (isUnsupportedNodeRuntime()) {
|
||||
const { found, expected } = isUnsupportedNodeRuntime();
|
||||
help.push(
|
||||
'- Please upgrade Node.js:',
|
||||
` Found ${found}`,
|
||||
` Requires ${expected}`
|
||||
);
|
||||
} else if (prebuiltPlatforms.includes(runtimePlatform)) {
|
||||
const [os, cpu] = runtimePlatform.split('-');
|
||||
const libc = os.endsWith('musl') ? ' --libc=musl' : '';
|
||||
help.push(
|
||||
'- Ensure optional dependencies can be installed:',
|
||||
' npm install --include=optional sharp',
|
||||
'- Ensure your package manager supports multi-platform installation:',
|
||||
' See https://sharp.pixelplumbing.com/install#cross-platform',
|
||||
'- Add platform-specific dependencies:',
|
||||
` npm install --os=${os.replace('musl', '')}${libc} --cpu=${cpu} sharp`
|
||||
);
|
||||
try {
|
||||
module.exports = require(`../build/Release/sharp-${platformAndArch}.node`);
|
||||
} catch (err) {
|
||||
// Bail early if bindings aren't available
|
||||
const help = ['', 'Something went wrong installing the "sharp" module', '', err.message, '', 'Possible solutions:'];
|
||||
if (/dylib/.test(err.message) && /Incompatible library version/.test(err.message)) {
|
||||
help.push('- Update Homebrew: "brew update && brew upgrade vips"');
|
||||
} else {
|
||||
const [platform, arch] = platformAndArch.split('-');
|
||||
if (platform === 'linux' && /Module did not self-register/.test(err.message)) {
|
||||
help.push('- Using worker threads? See https://sharp.pixelplumbing.com/install#worker-threads');
|
||||
}
|
||||
help.push(
|
||||
`- Manually install libvips >= ${minimumLibvipsVersion}`,
|
||||
'- Add experimental WebAssembly-based dependencies:',
|
||||
' npm install --cpu=wasm32 sharp',
|
||||
' npm install @img/sharp-wasm32'
|
||||
);
|
||||
}
|
||||
if (isLinux && /(symbol not found|CXXABI_)/i.test(messages)) {
|
||||
try {
|
||||
const { config } = require(`@img/sharp-libvips-${runtimePlatform}/package`);
|
||||
const libcFound = `${familySync()} ${versionSync()}`;
|
||||
const libcRequires = `${config.musl ? 'musl' : 'glibc'} ${config.musl || config.glibc}`;
|
||||
help.push(
|
||||
'- Update your OS:',
|
||||
` Found ${libcFound}`,
|
||||
` Requires ${libcRequires}`
|
||||
);
|
||||
} catch (errEngines) {}
|
||||
}
|
||||
if (isLinux && /\/snap\/core[0-9]{2}/.test(messages)) {
|
||||
help.push(
|
||||
'- Remove the Node.js Snap, which does not support native modules',
|
||||
' snap remove node'
|
||||
);
|
||||
}
|
||||
if (isMacOs && /Incompatible library version/.test(messages)) {
|
||||
help.push(
|
||||
'- Update Homebrew:',
|
||||
' brew update && brew upgrade vips'
|
||||
);
|
||||
}
|
||||
if (errors.some(err => err.code === 'ERR_DLOPEN_DISABLED')) {
|
||||
help.push('- Run Node.js without using the --no-addons flag');
|
||||
}
|
||||
// Link to installation docs
|
||||
if (isWindows && /The specified procedure could not be found/.test(messages)) {
|
||||
help.push(
|
||||
'- Using the canvas package on Windows?',
|
||||
' See https://sharp.pixelplumbing.com/install#canvas-and-windows',
|
||||
'- Check for outdated versions of sharp in the dependency tree:',
|
||||
' npm ls sharp'
|
||||
'- Install with verbose logging and look for errors: "npm install --ignore-scripts=false --foreground-scripts --verbose sharp"',
|
||||
`- Install for the current ${platformAndArch} runtime: "npm install --platform=${platform} --arch=${arch} sharp"`
|
||||
);
|
||||
}
|
||||
help.push(
|
||||
'- Consult the installation documentation:',
|
||||
' See https://sharp.pixelplumbing.com/install'
|
||||
'- Consult the installation documentation: https://sharp.pixelplumbing.com/install'
|
||||
);
|
||||
// Check loaded
|
||||
if (process.platform === 'win32' || /symbol/.test(err.message)) {
|
||||
const loadedModule = Object.keys(require.cache).find((i) => /[\\/]build[\\/]Release[\\/]sharp(.*)\.node$/.test(i));
|
||||
if (loadedModule) {
|
||||
const [, loadedPackage] = loadedModule.match(/node_modules[\\/]([^\\/]+)[\\/]/);
|
||||
help.push(`- Ensure the version of sharp aligns with the ${loadedPackage} package: "npm ls sharp"`);
|
||||
}
|
||||
}
|
||||
throw new Error(help.join('\n'));
|
||||
}
|
||||
|
146
lib/utility.js
@ -3,16 +3,15 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
const events = require('node:events');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const events = require('events');
|
||||
const detectLibc = require('detect-libc');
|
||||
|
||||
const is = require('./is');
|
||||
const { runtimePlatformArch } = require('./libvips');
|
||||
const platformAndArch = require('./platform')();
|
||||
const sharp = require('./sharp');
|
||||
|
||||
const runtimePlatform = runtimePlatformArch();
|
||||
const libvipsVersion = sharp.libvipsVersion();
|
||||
|
||||
/**
|
||||
* An Object containing nested boolean values representing the available input and output formats/methods.
|
||||
* @member
|
||||
@ -47,40 +46,33 @@ const interpolators = {
|
||||
};
|
||||
|
||||
/**
|
||||
* An Object containing the version numbers of sharp, libvips
|
||||
* and (when using prebuilt binaries) its dependencies.
|
||||
*
|
||||
* An Object containing the version numbers of sharp, libvips and its dependencies.
|
||||
* @member
|
||||
* @example
|
||||
* console.log(sharp.versions);
|
||||
*/
|
||||
let versions = {
|
||||
vips: libvipsVersion.semver
|
||||
vips: sharp.libvipsVersion()
|
||||
};
|
||||
/* istanbul ignore next */
|
||||
if (!libvipsVersion.isGlobal) {
|
||||
if (!libvipsVersion.isWasm) {
|
||||
try {
|
||||
versions = require(`@img/sharp-${runtimePlatform}/versions`);
|
||||
} catch (_) {
|
||||
try {
|
||||
versions = require(`@img/sharp-libvips-${runtimePlatform}/versions`);
|
||||
} catch (_) {}
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
versions = require('@img/sharp-wasm32/versions');
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
try {
|
||||
versions = require(`../vendor/${versions.vips}/${platformAndArch}/versions.json`);
|
||||
} catch (_err) { /* ignore */ }
|
||||
versions.sharp = require('../package.json').version;
|
||||
|
||||
/* istanbul ignore next */
|
||||
if (versions.heif && format.heif) {
|
||||
// Prebuilt binaries provide AV1
|
||||
format.heif.input.fileSuffix = ['.avif'];
|
||||
format.heif.output.alias = ['avif'];
|
||||
}
|
||||
/**
|
||||
* An Object containing the platform and architecture
|
||||
* of the current and installed vendored binaries.
|
||||
* @member
|
||||
* @example
|
||||
* console.log(sharp.vendor);
|
||||
*/
|
||||
const vendor = {
|
||||
current: platformAndArch,
|
||||
installed: []
|
||||
};
|
||||
try {
|
||||
vendor.installed = fs.readdirSync(path.join(__dirname, `../vendor/${versions.vips}`));
|
||||
} catch (_err) { /* ignore */ }
|
||||
|
||||
/**
|
||||
* Gets or, when options are provided, sets the limits of _libvips'_ operation cache.
|
||||
@ -135,9 +127,15 @@ cache(true);
|
||||
* e.g. libaom manages its own 4 threads when encoding AVIF images,
|
||||
* and these are independent of the value set here.
|
||||
*
|
||||
* :::note
|
||||
* Further {@link /performance|control over performance} is available.
|
||||
* :::
|
||||
* The maximum number of images that sharp can process in parallel
|
||||
* is controlled by libuv's `UV_THREADPOOL_SIZE` environment variable,
|
||||
* which defaults to 4.
|
||||
*
|
||||
* https://nodejs.org/api/cli.html#uv_threadpool_sizesize
|
||||
*
|
||||
* For example, by default, a machine with 8 CPU cores will process
|
||||
* 4 images in parallel and use up to 8 threads per image,
|
||||
* so there will be up to 32 concurrent threads.
|
||||
*
|
||||
* @example
|
||||
* const threads = sharp.concurrency(); // 4
|
||||
@ -154,9 +152,6 @@ function concurrency (concurrency) {
|
||||
if (detectLibc.familySync() === detectLibc.GLIBC && !sharp._isUsingJemalloc()) {
|
||||
// Reduce default concurrency to 1 when using glibc memory allocator
|
||||
sharp.concurrency(1);
|
||||
} else if (detectLibc.familySync() === detectLibc.MUSL && sharp.concurrency() === 1024) {
|
||||
// Reduce default concurrency when musl thread over-subscription detected
|
||||
sharp.concurrency(require('node:os').availableParallelism());
|
||||
}
|
||||
|
||||
/**
|
||||
@ -187,17 +182,17 @@ function counters () {
|
||||
|
||||
/**
|
||||
* Get and set use of SIMD vector unit instructions.
|
||||
* Requires libvips to have been compiled with highway support.
|
||||
* Requires libvips to have been compiled with liborc support.
|
||||
*
|
||||
* Improves the performance of `resize`, `blur` and `sharpen` operations
|
||||
* by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.
|
||||
*
|
||||
* @example
|
||||
* const simd = sharp.simd();
|
||||
* // simd is `true` if the runtime use of highway is currently enabled
|
||||
* // simd is `true` if the runtime use of liborc is currently enabled
|
||||
* @example
|
||||
* const simd = sharp.simd(false);
|
||||
* // prevent libvips from using highway at runtime
|
||||
* // prevent libvips from using liborc at runtime
|
||||
*
|
||||
* @param {boolean} [simd=true]
|
||||
* @returns {boolean}
|
||||
@ -205,76 +200,10 @@ function counters () {
|
||||
function simd (simd) {
|
||||
return sharp.simd(is.bool(simd) ? simd : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Block libvips operations at runtime.
|
||||
*
|
||||
* This is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable,
|
||||
* which when set will block all "untrusted" operations.
|
||||
*
|
||||
* @since 0.32.4
|
||||
*
|
||||
* @example <caption>Block all TIFF input.</caption>
|
||||
* sharp.block({
|
||||
* operation: ['VipsForeignLoadTiff']
|
||||
* });
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {Array<string>} options.operation - List of libvips low-level operation names to block.
|
||||
*/
|
||||
function block (options) {
|
||||
if (is.object(options)) {
|
||||
if (Array.isArray(options.operation) && options.operation.every(is.string)) {
|
||||
sharp.block(options.operation, true);
|
||||
} else {
|
||||
throw is.invalidParameterError('operation', 'Array<string>', options.operation);
|
||||
}
|
||||
} else {
|
||||
throw is.invalidParameterError('options', 'object', options);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unblock libvips operations at runtime.
|
||||
*
|
||||
* This is useful for defining a list of allowed operations.
|
||||
*
|
||||
* @since 0.32.4
|
||||
*
|
||||
* @example <caption>Block all input except WebP from the filesystem.</caption>
|
||||
* sharp.block({
|
||||
* operation: ['VipsForeignLoad']
|
||||
* });
|
||||
* sharp.unblock({
|
||||
* operation: ['VipsForeignLoadWebpFile']
|
||||
* });
|
||||
*
|
||||
* @example <caption>Block all input except JPEG and PNG from a Buffer or Stream.</caption>
|
||||
* sharp.block({
|
||||
* operation: ['VipsForeignLoad']
|
||||
* });
|
||||
* sharp.unblock({
|
||||
* operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer']
|
||||
* });
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {Array<string>} options.operation - List of libvips low-level operation names to unblock.
|
||||
*/
|
||||
function unblock (options) {
|
||||
if (is.object(options)) {
|
||||
if (Array.isArray(options.operation) && options.operation.every(is.string)) {
|
||||
sharp.block(options.operation, false);
|
||||
} else {
|
||||
throw is.invalidParameterError('operation', 'Array<string>', options.operation);
|
||||
}
|
||||
} else {
|
||||
throw is.invalidParameterError('options', 'object', options);
|
||||
}
|
||||
}
|
||||
simd(true);
|
||||
|
||||
/**
|
||||
* Decorate the Sharp class with utility-related functions.
|
||||
* @module Sharp
|
||||
* @private
|
||||
*/
|
||||
module.exports = function (Sharp) {
|
||||
@ -285,7 +214,6 @@ module.exports = function (Sharp) {
|
||||
Sharp.format = format;
|
||||
Sharp.interpolators = interpolators;
|
||||
Sharp.versions = versions;
|
||||
Sharp.vendor = vendor;
|
||||
Sharp.queue = queue;
|
||||
Sharp.block = block;
|
||||
Sharp.unblock = unblock;
|
||||
};
|
||||
|
@ -1,40 +0,0 @@
|
||||
{
|
||||
"name": "@img/sharp-darwin-arm64",
|
||||
"version": "0.34.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with macOS 64-bit ARM",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/darwin-arm64"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-darwin-arm64": "1.2.0"
|
||||
},
|
||||
"files": [
|
||||
"lib"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
"./sharp.node": "./lib/sharp-darwin-arm64.node",
|
||||
"./package": "./package.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"cpu": [
|
||||
"arm64"
|
||||
]
|
||||
}
|
@ -1,40 +0,0 @@
|
||||
{
|
||||
"name": "@img/sharp-darwin-x64",
|
||||
"version": "0.34.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with macOS x64",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/darwin-x64"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-darwin-x64": "1.2.0"
|
||||
},
|
||||
"files": [
|
||||
"lib"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
"./sharp.node": "./lib/sharp-darwin-x64.node",
|
||||
"./package": "./package.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
]
|
||||
}
|
@ -1,64 +0,0 @@
|
||||
// Copyright 2013 Lovell Fuller and others.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
'use strict';
|
||||
|
||||
// Populate the npm package for the current platform with the local build
|
||||
|
||||
const { copyFileSync, cpSync, readFileSync, writeFileSync, appendFileSync } = require('node:fs');
|
||||
const { basename, join } = require('node:path');
|
||||
|
||||
const { buildPlatformArch } = require('../lib/libvips');
|
||||
|
||||
const licensing = `
|
||||
## Licensing
|
||||
|
||||
Copyright 2013 Lovell Fuller and others.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0)
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
`;
|
||||
|
||||
const platform = buildPlatformArch();
|
||||
const destDir = join(__dirname, platform);
|
||||
console.log(`Populating npm package for platform: ${platform}`);
|
||||
|
||||
// Copy binaries
|
||||
const releaseDir = join(__dirname, '..', 'src', 'build', 'Release');
|
||||
const libDir = join(destDir, 'lib');
|
||||
cpSync(releaseDir, libDir, {
|
||||
recursive: true,
|
||||
filter: (file) => {
|
||||
const name = basename(file);
|
||||
return name === 'Release' ||
|
||||
(name.startsWith('sharp-') && name.includes('.node')) ||
|
||||
(name.startsWith('libvips-') && name.endsWith('.dll'));
|
||||
}
|
||||
});
|
||||
|
||||
// Generate README
|
||||
const { name, description } = require(`./${platform}/package.json`);
|
||||
writeFileSync(join(destDir, 'README.md'), `# \`${name}\`\n\n${description}.\n${licensing}`);
|
||||
|
||||
// Copy Apache-2.0 LICENSE
|
||||
copyFileSync(join(__dirname, '..', 'LICENSE'), join(destDir, 'LICENSE'));
|
||||
|
||||
// Copy files for packages without an explicit sharp-libvips dependency (Windows, wasm)
|
||||
if (platform.startsWith('win') || platform.startsWith('wasm')) {
|
||||
const libvipsPlatform = platform === 'wasm32' ? 'dev-wasm32' : platform;
|
||||
const sharpLibvipsDir = join(require(`@img/sharp-libvips-${libvipsPlatform}/lib`), '..');
|
||||
// Copy versions.json
|
||||
copyFileSync(join(sharpLibvipsDir, 'versions.json'), join(destDir, 'versions.json'));
|
||||
// Append third party licensing to README
|
||||
const readme = readFileSync(join(sharpLibvipsDir, 'README.md'), { encoding: 'utf-8' });
|
||||
const thirdParty = readme.substring(readme.indexOf('\nThis software contains'));
|
||||
appendFileSync(join(destDir, 'README.md'), thirdParty);
|
||||
}
|
@ -1,46 +0,0 @@
|
||||
{
|
||||
"name": "@img/sharp-linux-arm",
|
||||
"version": "0.34.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Linux (glibc) ARM (32-bit)",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/linux-arm"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-linux-arm": "1.2.0"
|
||||
},
|
||||
"files": [
|
||||
"lib"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
"./sharp.node": "./lib/sharp-linux-arm.node",
|
||||
"./package": "./package.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"config": {
|
||||
"glibc": ">=2.31"
|
||||
},
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"cpu": [
|
||||
"arm"
|
||||
]
|
||||
}
|
@ -1,46 +0,0 @@
|
||||
{
|
||||
"name": "@img/sharp-linux-arm64",
|
||||
"version": "0.34.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Linux (glibc) 64-bit ARM",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/linux-arm64"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-linux-arm64": "1.2.0"
|
||||
},
|
||||
"files": [
|
||||
"lib"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
"./sharp.node": "./lib/sharp-linux-arm64.node",
|
||||
"./package": "./package.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"config": {
|
||||
"glibc": ">=2.26"
|
||||
},
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"cpu": [
|
||||
"arm64"
|
||||
]
|
||||
}
|
@ -1,46 +0,0 @@
|
||||
{
|
||||
"name": "@img/sharp-linux-ppc64",
|
||||
"version": "0.34.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Linux (glibc) ppc64",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/linux-ppc64"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-linux-ppc64": "1.2.0"
|
||||
},
|
||||
"files": [
|
||||
"lib"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
"./sharp.node": "./lib/sharp-linux-ppc64.node",
|
||||
"./package": "./package.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"config": {
|
||||
"glibc": ">=2.31"
|
||||
},
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
]
|
||||
}
|
@ -1,46 +0,0 @@
|
||||
{
|
||||
"name": "@img/sharp-linux-s390x",
|
||||
"version": "0.34.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Linux (glibc) s390x",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/linux-s390x"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-linux-s390x": "1.2.0"
|
||||
},
|
||||
"files": [
|
||||
"lib"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
"./sharp.node": "./lib/sharp-linux-s390x.node",
|
||||
"./package": "./package.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"config": {
|
||||
"glibc": ">=2.31"
|
||||
},
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"cpu": [
|
||||
"s390x"
|
||||
]
|
||||
}
|
@ -1,46 +0,0 @@
|
||||
{
|
||||
"name": "@img/sharp-linux-x64",
|
||||
"version": "0.34.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Linux (glibc) x64",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/linux-x64"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-linux-x64": "1.2.0"
|
||||
},
|
||||
"files": [
|
||||
"lib"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
"./sharp.node": "./lib/sharp-linux-x64.node",
|
||||
"./package": "./package.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"config": {
|
||||
"glibc": ">=2.26"
|
||||
},
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
]
|
||||
}
|
@ -1,46 +0,0 @@
|
||||
{
|
||||
"name": "@img/sharp-linuxmusl-arm64",
|
||||
"version": "0.34.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Linux (musl) 64-bit ARM",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/linuxmusl-arm64"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-linuxmusl-arm64": "1.2.0"
|
||||
},
|
||||
"files": [
|
||||
"lib"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
"./sharp.node": "./lib/sharp-linuxmusl-arm64.node",
|
||||
"./package": "./package.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"config": {
|
||||
"musl": ">=1.2.2"
|
||||
},
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"cpu": [
|
||||
"arm64"
|
||||
]
|
||||
}
|
@ -1,46 +0,0 @@
|
||||
{
|
||||
"name": "@img/sharp-linuxmusl-x64",
|
||||
"version": "0.34.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Linux (musl) x64",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/linuxmusl-x64"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-linuxmusl-x64": "1.2.0"
|
||||
},
|
||||
"files": [
|
||||
"lib"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
"./sharp.node": "./lib/sharp-linuxmusl-x64.node",
|
||||
"./package": "./package.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"config": {
|
||||
"musl": ">=1.2.2"
|
||||
},
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
]
|
||||
}
|
@ -1,20 +0,0 @@
|
||||
{
|
||||
"name": "@img/sharp",
|
||||
"version": "0.34.3-rc.0",
|
||||
"private": "true",
|
||||
"workspaces": [
|
||||
"darwin-arm64",
|
||||
"darwin-x64",
|
||||
"linux-arm",
|
||||
"linux-arm64",
|
||||
"linux-ppc64",
|
||||
"linux-s390x",
|
||||
"linux-x64",
|
||||
"linuxmusl-arm64",
|
||||
"linuxmusl-x64",
|
||||
"wasm32",
|
||||
"win32-arm64",
|
||||
"win32-ia32",
|
||||
"win32-x64"
|
||||
]
|
||||
}
|
@ -1,39 +0,0 @@
|
||||
{
|
||||
"name": "@img/sharp-wasm32",
|
||||
"version": "0.34.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with wasm32",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/wasm32"
|
||||
},
|
||||
"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"files": [
|
||||
"lib",
|
||||
"versions.json"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
"./sharp.node": "./lib/sharp-wasm32.node.js",
|
||||
"./package": "./package.json",
|
||||
"./versions": "./versions.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@emnapi/runtime": "^1.4.4"
|
||||
},
|
||||
"cpu": [
|
||||
"wasm32"
|
||||
]
|
||||
}
|
@ -1,39 +0,0 @@
|
||||
{
|
||||
"name": "@img/sharp-win32-arm64",
|
||||
"version": "0.34.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Windows 64-bit ARM",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/win32-arm64"
|
||||
},
|
||||
"license": "Apache-2.0 AND LGPL-3.0-or-later",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"files": [
|
||||
"lib",
|
||||
"versions.json"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
"./sharp.node": "./lib/sharp-win32-arm64.node",
|
||||
"./package": "./package.json",
|
||||
"./versions": "./versions.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"cpu": [
|
||||
"arm64"
|
||||
]
|
||||
}
|
@ -1,39 +0,0 @@
|
||||
{
|
||||
"name": "@img/sharp-win32-ia32",
|
||||
"version": "0.34.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Windows x86 (32-bit)",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/win32-ia32"
|
||||
},
|
||||
"license": "Apache-2.0 AND LGPL-3.0-or-later",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"files": [
|
||||
"lib",
|
||||
"versions.json"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
"./sharp.node": "./lib/sharp-win32-ia32.node",
|
||||
"./package": "./package.json",
|
||||
"./versions": "./versions.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"cpu": [
|
||||
"ia32"
|
||||
]
|
||||
}
|
@ -1,39 +0,0 @@
|
||||
{
|
||||
"name": "@img/sharp-win32-x64",
|
||||
"version": "0.34.3-rc.0",
|
||||
"description": "Prebuilt sharp for use with Windows x64",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/win32-x64"
|
||||
},
|
||||
"license": "Apache-2.0 AND LGPL-3.0-or-later",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"files": [
|
||||
"lib",
|
||||
"versions.json"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
"./sharp.node": "./lib/sharp-win32-x64.node",
|
||||
"./package": "./package.json",
|
||||
"./versions": "./versions.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
]
|
||||
}
|
127
package.json
@ -1,9 +1,9 @@
|
||||
{
|
||||
"name": "sharp",
|
||||
"description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images",
|
||||
"version": "0.34.3-rc.0",
|
||||
"version": "0.32.0",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"homepage": "https://github.com/lovell/sharp",
|
||||
"contributors": [
|
||||
"Pierre Inglebert <pierre.inglebert@gmail.com>",
|
||||
"Jonathan Ong <jonathanrichardong@gmail.com>",
|
||||
@ -82,40 +82,36 @@
|
||||
"Joris Dugué <zaruike10@gmail.com>",
|
||||
"Chris Banks <christopher.bradley.banks@gmail.com>",
|
||||
"Ompal Singh <ompal.hitm09@gmail.com>",
|
||||
"Brodan <christopher.hranj@gmail.com>",
|
||||
"Brodan <christopher.hranj@gmail.com",
|
||||
"Ankur Parihar <ankur.github@gmail.com>",
|
||||
"Brahim Ait elhaj <brahima@gmail.com>",
|
||||
"Mart Jansink <m.jansink@gmail.com>",
|
||||
"Lachlan Newman <lachnewman007@gmail.com>",
|
||||
"Dennis Beatty <dennis@dcbeatty.com>",
|
||||
"Ingvar Stepanyan <me@rreverser.com>",
|
||||
"Don Denton <don@happycollision.com>"
|
||||
"Lachlan Newman <lachnewman007@gmail.com>"
|
||||
],
|
||||
"scripts": {
|
||||
"install": "node install/check.js",
|
||||
"clean": "rm -rf src/build/ .nyc_output/ coverage/ test/fixtures/output.*",
|
||||
"install": "(node install/libvips && node install/dll-copy && prebuild-install) || (node install/can-compile && node-gyp rebuild && node install/dll-copy)",
|
||||
"clean": "rm -rf node_modules/ build/ vendor/ .nyc_output/ coverage/ test/fixtures/output.*",
|
||||
"test": "npm run test-lint && npm run test-unit && npm run test-licensing && npm run test-types",
|
||||
"test-lint": "semistandard && cpplint",
|
||||
"test-unit": "nyc --reporter=lcov --reporter=text --check-coverage --branches=100 mocha",
|
||||
"test-licensing": "license-checker --production --summary --onlyAllow=\"Apache-2.0;BSD;ISC;LGPL-3.0-or-later;MIT\"",
|
||||
"test-licensing": "license-checker --production --summary --onlyAllow=\"Apache-2.0;BSD;ISC;MIT\"",
|
||||
"test-leak": "./test/leak/leak.sh",
|
||||
"test-types": "tsd",
|
||||
"package-from-local-build": "node npm/from-local-build.js",
|
||||
"docs-build": "node docs/build.mjs",
|
||||
"docs-serve": "cd docs && npm start",
|
||||
"docs-publish": "cd docs && npm run build && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp"
|
||||
"docs-build": "node docs/build && node docs/search-index/build",
|
||||
"docs-serve": "cd docs && npx serve",
|
||||
"docs-publish": "cd docs && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/index.d.ts",
|
||||
"files": [
|
||||
"install",
|
||||
"lib",
|
||||
"src/*.{cc,h,gyp}"
|
||||
"binding.gyp",
|
||||
"install/**",
|
||||
"lib/**",
|
||||
"src/**"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/lovell/sharp.git"
|
||||
"url": "git://github.com/lovell/sharp"
|
||||
},
|
||||
"keywords": [
|
||||
"jpeg",
|
||||
@ -137,66 +133,60 @@
|
||||
],
|
||||
"dependencies": {
|
||||
"color": "^4.2.3",
|
||||
"detect-libc": "^2.0.4",
|
||||
"semver": "^7.7.2"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-darwin-arm64": "0.34.3-rc.0",
|
||||
"@img/sharp-darwin-x64": "0.34.3-rc.0",
|
||||
"@img/sharp-libvips-darwin-arm64": "1.2.0",
|
||||
"@img/sharp-libvips-darwin-x64": "1.2.0",
|
||||
"@img/sharp-libvips-linux-arm": "1.2.0",
|
||||
"@img/sharp-libvips-linux-arm64": "1.2.0",
|
||||
"@img/sharp-libvips-linux-ppc64": "1.2.0",
|
||||
"@img/sharp-libvips-linux-s390x": "1.2.0",
|
||||
"@img/sharp-libvips-linux-x64": "1.2.0",
|
||||
"@img/sharp-libvips-linuxmusl-arm64": "1.2.0",
|
||||
"@img/sharp-libvips-linuxmusl-x64": "1.2.0",
|
||||
"@img/sharp-linux-arm": "0.34.3-rc.0",
|
||||
"@img/sharp-linux-arm64": "0.34.3-rc.0",
|
||||
"@img/sharp-linux-ppc64": "0.34.3-rc.0",
|
||||
"@img/sharp-linux-s390x": "0.34.3-rc.0",
|
||||
"@img/sharp-linux-x64": "0.34.3-rc.0",
|
||||
"@img/sharp-linuxmusl-arm64": "0.34.3-rc.0",
|
||||
"@img/sharp-linuxmusl-x64": "0.34.3-rc.0",
|
||||
"@img/sharp-wasm32": "0.34.3-rc.0",
|
||||
"@img/sharp-win32-arm64": "0.34.3-rc.0",
|
||||
"@img/sharp-win32-ia32": "0.34.3-rc.0",
|
||||
"@img/sharp-win32-x64": "0.34.3-rc.0"
|
||||
"detect-libc": "^2.0.1",
|
||||
"node-addon-api": "^6.0.0",
|
||||
"prebuild-install": "^7.1.1",
|
||||
"semver": "^7.3.8",
|
||||
"simple-get": "^4.0.1",
|
||||
"tar-fs": "^2.1.1",
|
||||
"tunnel-agent": "^0.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@emnapi/runtime": "^1.4.4",
|
||||
"@img/sharp-libvips-dev": "1.2.0",
|
||||
"@img/sharp-libvips-dev-wasm32": "1.2.0",
|
||||
"@img/sharp-libvips-win32-arm64": "1.2.0",
|
||||
"@img/sharp-libvips-win32-ia32": "1.2.0",
|
||||
"@img/sharp-libvips-win32-x64": "1.2.0",
|
||||
"@types/node": "*",
|
||||
"async": "^3.2.4",
|
||||
"cc": "^3.0.1",
|
||||
"emnapi": "^1.4.4",
|
||||
"exif-reader": "^2.0.2",
|
||||
"exif-reader": "^1.2.0",
|
||||
"extract-zip": "^2.0.1",
|
||||
"icc": "^3.0.0",
|
||||
"jsdoc-to-markdown": "^9.1.1",
|
||||
"icc": "^2.0.0",
|
||||
"jsdoc-to-markdown": "^8.0.0",
|
||||
"license-checker": "^25.0.1",
|
||||
"mocha": "^11.7.1",
|
||||
"node-addon-api": "^8.4.0",
|
||||
"node-gyp": "^11.2.0",
|
||||
"nyc": "^17.1.0",
|
||||
"semistandard": "^17.0.0",
|
||||
"tar-fs": "^3.1.0",
|
||||
"tsd": "^0.32.0"
|
||||
"mocha": "^10.2.0",
|
||||
"mock-fs": "^5.2.0",
|
||||
"nyc": "^15.1.0",
|
||||
"prebuild": "^11.0.4",
|
||||
"semistandard": "^16.0.1",
|
||||
"tsd": "^0.28.0"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"config": {
|
||||
"libvips": ">=8.17.1"
|
||||
"libvips": "8.14.2",
|
||||
"integrity": {
|
||||
"darwin-arm64v8": "sha512-eUuxg6H0tXgX4z2lsaGtZ4cbPAm7yoFgkvPDd4csxoiVt+QUB25pEJwiXw7oB53VlBFIp3O8lbydSFS5zH8MQQ==",
|
||||
"darwin-x64": "sha512-cMT4v76IgzSR0VoXqLk/yftRyzMEZ+SBVMLzXCgqP/lmnYisrpmHHNqrWnoZbUUBXbPXLn6KMultYOJHe/c9ZQ==",
|
||||
"linux-arm64v8": "sha512-OcDJ/ly80pxwaKnw0W91sSvZczPtWsjmzrY/+6NMiQZT84LkmeaRuwErbHhorKDxnl7iZuNn9Uj5V25Xmj+LDQ==",
|
||||
"linux-armv6": "sha512-hk2ohSOYTJEtVQxEQFyQ+tuayKpYqx6NiXa7AE+8MF+yscxt+g+mLJ7TjDqtmb4ttFGH4IVfsEfU2YXIqWqkpg==",
|
||||
"linux-armv7": "sha512-/5Ci2Cd+yLZmTaEt9lVJ89elxX3RMJpps0ESjj43X40yrwka51QfXeg1QV38uNzZpCDIZkrbXZK0lyKldjpLuA==",
|
||||
"linux-x64": "sha512-wjCKmWfBb0uz1UB7rPDLvO0s+VWuoAY/Vv/YGCRFEQUkdSLQUgHExrOMMbOM3FleuYfQqznDYCXXphkl7X44+w==",
|
||||
"linuxmusl-arm64v8": "sha512-QtD2n90yi+rLE65C0gksFUU5uMUFPICI/pS3A0bgthpIcoCejAOYs3ZjVWpZbHQuV/lWahIUYO78MB9CzY860A==",
|
||||
"linuxmusl-x64": "sha512-TokQ/ETCJAsPYuxIMOPYDp25rlcwtpmIMtRUR9PB75TmZEJe7abRfCEInIPYeD8F/HxxnJSLiEdlbn1z1Jfzng==",
|
||||
"win32-arm64v8": "sha512-IIuj4EAgLqEVAoOuYH79C61a7TcJXlU/RBwk+5JsGWc2mr4J/Ar5J01e6XBvU4Lu3eqcU+3GPaACZEa1511buA==",
|
||||
"win32-ia32": "sha512-CsZi7lrReX3B6tmYgOGJ0IiAfcN5APDC6l+3gdosxfTfwpLLO+jXaSmyNwIGeMqrdgckG/gwwc+IrUZmkmjJ/A==",
|
||||
"win32-x64": "sha512-J7znmNKUK4ZKo6SnSnEtzT1xRAwvkGXxIx9/QihAadu1TFdS06yNhcENmwC4973+KZBlAdVpWbZ8sLrEoWkdCA=="
|
||||
},
|
||||
"runtime": "napi",
|
||||
"target": 7
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.15.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"binary": {
|
||||
"napi_versions": [
|
||||
7
|
||||
]
|
||||
},
|
||||
"semistandard": {
|
||||
"env": [
|
||||
"mocha"
|
||||
@ -208,11 +198,6 @@
|
||||
"build/include"
|
||||
]
|
||||
},
|
||||
"nyc": {
|
||||
"include": [
|
||||
"lib"
|
||||
]
|
||||
},
|
||||
"tsd": {
|
||||
"directory": "test/types/"
|
||||
}
|
||||
|
299
src/binding.gyp
@ -1,299 +0,0 @@
|
||||
# Copyright 2013 Lovell Fuller and others.
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
{
|
||||
'variables': {
|
||||
'vips_version': '<!(node -p "require(\'../lib/libvips\').minimumLibvipsVersion")',
|
||||
'platform_and_arch': '<!(node -p "require(\'../lib/libvips\').buildPlatformArch()")',
|
||||
'sharp_libvips_version': '<!(node -p "require(\'../package.json\').optionalDependencies[\'@img/sharp-libvips-<(platform_and_arch)\']")',
|
||||
'sharp_libvips_yarn_locator': '<!(node -p "require(\'../lib/libvips\').yarnLocator()")',
|
||||
'sharp_libvips_include_dir': '<!(node -p "require(\'../lib/libvips\').buildSharpLibvipsIncludeDir()")',
|
||||
'sharp_libvips_cplusplus_dir': '<!(node -p "require(\'../lib/libvips\').buildSharpLibvipsCPlusPlusDir()")',
|
||||
'sharp_libvips_lib_dir': '<!(node -p "require(\'../lib/libvips\').buildSharpLibvipsLibDir()")'
|
||||
},
|
||||
'targets': [{
|
||||
'target_name': 'libvips-cpp-<(vips_version)',
|
||||
'conditions': [
|
||||
['OS == "win"', {
|
||||
# Build libvips C++ binding for Windows due to MSVC std library ABI changes
|
||||
'type': 'shared_library',
|
||||
'defines': [
|
||||
'_VIPS_PUBLIC=__declspec(dllexport)',
|
||||
'_ALLOW_KEYWORD_MACROS',
|
||||
'G_DISABLE_ASSERT',
|
||||
'G_DISABLE_CAST_CHECKS',
|
||||
'G_DISABLE_CHECKS'
|
||||
],
|
||||
'sources': [
|
||||
'<(sharp_libvips_cplusplus_dir)/VConnection.cpp',
|
||||
'<(sharp_libvips_cplusplus_dir)/VError.cpp',
|
||||
'<(sharp_libvips_cplusplus_dir)/VImage.cpp',
|
||||
'<(sharp_libvips_cplusplus_dir)/VInterpolate.cpp',
|
||||
'<(sharp_libvips_cplusplus_dir)/VRegion.cpp'
|
||||
],
|
||||
'include_dirs': [
|
||||
'<(sharp_libvips_include_dir)',
|
||||
'<(sharp_libvips_include_dir)/glib-2.0',
|
||||
'<(sharp_libvips_lib_dir)/glib-2.0/include'
|
||||
],
|
||||
'link_settings': {
|
||||
'library_dirs': [
|
||||
'<(sharp_libvips_lib_dir)'
|
||||
],
|
||||
'libraries': [
|
||||
'libvips.lib'
|
||||
],
|
||||
},
|
||||
'configurations': {
|
||||
'Release': {
|
||||
'msvs_settings': {
|
||||
'VCCLCompilerTool': {
|
||||
"AdditionalOptions": [
|
||||
"/std:c++17"
|
||||
],
|
||||
'ExceptionHandling': 1,
|
||||
'Optimization': 1,
|
||||
'WholeProgramOptimization': 'true'
|
||||
},
|
||||
'VCLibrarianTool': {
|
||||
'AdditionalOptions': [
|
||||
'/LTCG:INCREMENTAL'
|
||||
]
|
||||
},
|
||||
'VCLinkerTool': {
|
||||
'ImageHasSafeExceptionHandlers': 'false',
|
||||
'OptimizeReferences': 2,
|
||||
'EnableCOMDATFolding': 2,
|
||||
'LinkIncremental': 1,
|
||||
'AdditionalOptions': [
|
||||
'/LTCG:INCREMENTAL'
|
||||
]
|
||||
}
|
||||
},
|
||||
'msvs_disabled_warnings': [
|
||||
4275
|
||||
]
|
||||
}
|
||||
}
|
||||
}, {
|
||||
# Ignore this target for non-Windows
|
||||
'type': 'none'
|
||||
}]
|
||||
]
|
||||
}, {
|
||||
'target_name': 'sharp-<(platform_and_arch)',
|
||||
'defines': [
|
||||
'G_DISABLE_ASSERT',
|
||||
'G_DISABLE_CAST_CHECKS',
|
||||
'G_DISABLE_CHECKS',
|
||||
'NAPI_VERSION=9',
|
||||
'NODE_ADDON_API_DISABLE_DEPRECATED',
|
||||
'NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS'
|
||||
],
|
||||
'dependencies': [
|
||||
'<!(node -p "require(\'node-addon-api\').gyp")',
|
||||
'libvips-cpp-<(vips_version)'
|
||||
],
|
||||
'variables': {
|
||||
'conditions': [
|
||||
['OS != "win"', {
|
||||
'pkg_config_path': '<!(node -p "require(\'../lib/libvips\').pkgConfigPath()")',
|
||||
'use_global_libvips': '<!(node -p "Boolean(require(\'../lib/libvips\').useGlobalLibvips()).toString()")'
|
||||
}, {
|
||||
'pkg_config_path': '',
|
||||
'use_global_libvips': ''
|
||||
}]
|
||||
]
|
||||
},
|
||||
'sources': [
|
||||
'common.cc',
|
||||
'metadata.cc',
|
||||
'stats.cc',
|
||||
'operations.cc',
|
||||
'pipeline.cc',
|
||||
'utilities.cc',
|
||||
'sharp.cc'
|
||||
],
|
||||
'include_dirs': [
|
||||
'<!(node -p "require(\'node-addon-api\').include_dir")',
|
||||
],
|
||||
'conditions': [
|
||||
['use_global_libvips == "true"', {
|
||||
# Use pkg-config for include and lib
|
||||
'include_dirs': ['<!@(PKG_CONFIG_PATH="<(pkg_config_path)" pkg-config --cflags-only-I vips-cpp vips glib-2.0 | sed s\/-I//g)'],
|
||||
'libraries': ['<!@(PKG_CONFIG_PATH="<(pkg_config_path)" pkg-config --libs vips-cpp)'],
|
||||
'defines': [
|
||||
'SHARP_USE_GLOBAL_LIBVIPS'
|
||||
],
|
||||
'conditions': [
|
||||
['OS == "linux"', {
|
||||
'defines': [
|
||||
# Inspect libvips-cpp.so to determine which C++11 ABI version was used and set _GLIBCXX_USE_CXX11_ABI accordingly. This is quite horrible.
|
||||
'_GLIBCXX_USE_CXX11_ABI=<!(if readelf -Ws "$(PKG_CONFIG_PATH="<(pkg_config_path)" pkg-config --variable libdir vips-cpp)/libvips-cpp.so" | c++filt | grep -qF __cxx11;then echo "1";else echo "0";fi)'
|
||||
]
|
||||
}]
|
||||
]
|
||||
}, {
|
||||
# Use pre-built libvips stored locally within node_modules
|
||||
'include_dirs': [
|
||||
'<(sharp_libvips_include_dir)',
|
||||
'<(sharp_libvips_include_dir)/glib-2.0',
|
||||
'<(sharp_libvips_lib_dir)/glib-2.0/include'
|
||||
],
|
||||
'library_dirs': [
|
||||
'<(sharp_libvips_lib_dir)'
|
||||
],
|
||||
'conditions': [
|
||||
['OS == "win"', {
|
||||
'defines': [
|
||||
'_ALLOW_KEYWORD_MACROS',
|
||||
'_FILE_OFFSET_BITS=64'
|
||||
],
|
||||
'link_settings': {
|
||||
'libraries': [
|
||||
'libvips.lib'
|
||||
]
|
||||
}
|
||||
}],
|
||||
['OS == "mac"', {
|
||||
'link_settings': {
|
||||
'libraries': [
|
||||
'libvips-cpp.<(vips_version).dylib'
|
||||
]
|
||||
},
|
||||
'xcode_settings': {
|
||||
'OTHER_LDFLAGS': [
|
||||
'-Wl,-s',
|
||||
'-Wl,-dead_strip',
|
||||
# Ensure runtime linking is relative to sharp.node
|
||||
'-Wl,-rpath,\'@loader_path/../../sharp-libvips-<(platform_and_arch)/lib\'',
|
||||
'-Wl,-rpath,\'@loader_path/../../../sharp-libvips-<(platform_and_arch)/<(sharp_libvips_version)/lib\'',
|
||||
'-Wl,-rpath,\'@loader_path/../../node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\'',
|
||||
'-Wl,-rpath,\'@loader_path/../../../node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\'',
|
||||
'-Wl,-rpath,\'@loader_path/../../../../../@img-sharp-libvips-<(platform_and_arch)-npm-<(sharp_libvips_version)-<(sharp_libvips_yarn_locator)/node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\''
|
||||
]
|
||||
}
|
||||
}],
|
||||
['OS == "linux"', {
|
||||
'defines': [
|
||||
'_GLIBCXX_USE_CXX11_ABI=1'
|
||||
],
|
||||
'cflags_cc': [
|
||||
'<!(node -p "require(\'detect-libc\').isNonGlibcLinuxSync() ? \'\' : \'-flto=auto\'")'
|
||||
],
|
||||
'link_settings': {
|
||||
'libraries': [
|
||||
'-l:libvips-cpp.so.<(vips_version)'
|
||||
],
|
||||
'ldflags': [
|
||||
'-lstdc++fs',
|
||||
'-Wl,-s',
|
||||
'-Wl,--disable-new-dtags',
|
||||
'-Wl,-z,nodelete',
|
||||
'-Wl,-Bsymbolic-functions',
|
||||
'-Wl,-rpath=\'$$ORIGIN/../../sharp-libvips-<(platform_and_arch)/lib\'',
|
||||
'-Wl,-rpath=\'$$ORIGIN/../../../sharp-libvips-<(platform_and_arch)/<(sharp_libvips_version)/lib\'',
|
||||
'-Wl,-rpath=\'$$ORIGIN/../../node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\'',
|
||||
'-Wl,-rpath=\'$$ORIGIN/../../../node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\'',
|
||||
'-Wl,-rpath,\'$$ORIGIN/../../../../../@img-sharp-libvips-<(platform_and_arch)-npm-<(sharp_libvips_version)-<(sharp_libvips_yarn_locator)/node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\''
|
||||
]
|
||||
}
|
||||
}],
|
||||
['OS == "emscripten"', {
|
||||
'product_extension': 'node.js',
|
||||
'link_settings': {
|
||||
'ldflags': [
|
||||
'-fexceptions',
|
||||
'--pre-js=<!(node -p "require.resolve(\'./emscripten/pre.js\')")',
|
||||
'-Oz',
|
||||
'-sALLOW_MEMORY_GROWTH',
|
||||
'-sENVIRONMENT=node',
|
||||
'-sEXPORTED_FUNCTIONS=["emnapiInit", "_vips_shutdown", "_uv_library_shutdown"]',
|
||||
'-sNODERAWFS',
|
||||
'-sTEXTDECODER=0',
|
||||
'-sWASM_ASYNC_COMPILATION=0',
|
||||
'-sWASM_BIGINT'
|
||||
],
|
||||
'libraries': [
|
||||
'<!@(PKG_CONFIG_PATH="<!(node -p "require(\'@img/sharp-libvips-dev-wasm32/lib\')")/pkgconfig" pkg-config --static --libs vips-cpp)'
|
||||
],
|
||||
}
|
||||
}]
|
||||
]
|
||||
}]
|
||||
],
|
||||
'cflags_cc': [
|
||||
'-std=c++17',
|
||||
'-fexceptions',
|
||||
'-Wall',
|
||||
'-Os'
|
||||
],
|
||||
'xcode_settings': {
|
||||
'CLANG_CXX_LANGUAGE_STANDARD': 'c++17',
|
||||
'MACOSX_DEPLOYMENT_TARGET': '10.15',
|
||||
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
|
||||
'GCC_ENABLE_CPP_RTTI': 'YES',
|
||||
'OTHER_CPLUSPLUSFLAGS': [
|
||||
'-fexceptions',
|
||||
'-Wall',
|
||||
'-Oz'
|
||||
]
|
||||
},
|
||||
'configurations': {
|
||||
'Release': {
|
||||
'conditions': [
|
||||
['target_arch == "arm"', {
|
||||
'cflags_cc': [
|
||||
'-Wno-psabi'
|
||||
]
|
||||
}],
|
||||
['OS == "win"', {
|
||||
'msvs_settings': {
|
||||
'VCCLCompilerTool': {
|
||||
"AdditionalOptions": [
|
||||
"/std:c++17"
|
||||
],
|
||||
'ExceptionHandling': 1,
|
||||
'Optimization': 1,
|
||||
'WholeProgramOptimization': 'true'
|
||||
},
|
||||
'VCLibrarianTool': {
|
||||
'AdditionalOptions': [
|
||||
'/LTCG:INCREMENTAL'
|
||||
]
|
||||
},
|
||||
'VCLinkerTool': {
|
||||
'ImageHasSafeExceptionHandlers': 'false',
|
||||
'OptimizeReferences': 2,
|
||||
'EnableCOMDATFolding': 2,
|
||||
'LinkIncremental': 1,
|
||||
'AdditionalOptions': [
|
||||
'/LTCG:INCREMENTAL'
|
||||
]
|
||||
}
|
||||
},
|
||||
'msvs_disabled_warnings': [
|
||||
4275
|
||||
]
|
||||
}]
|
||||
]
|
||||
}
|
||||
},
|
||||
}, {
|
||||
'target_name': 'copy-dll',
|
||||
'type': 'none',
|
||||
'dependencies': [
|
||||
'sharp-<(platform_and_arch)'
|
||||
],
|
||||
'conditions': [
|
||||
['OS == "win"', {
|
||||
'copies': [{
|
||||
'destination': 'build/Release',
|
||||
'files': [
|
||||
'<(sharp_libvips_lib_dir)/libvips-42.dll'
|
||||
]
|
||||
}]
|
||||
}]
|
||||
]
|
||||
}]
|
||||
}
|
297
src/common.cc
@ -65,6 +65,16 @@ namespace sharp {
|
||||
}
|
||||
return vector;
|
||||
}
|
||||
Napi::Buffer<char> NewOrCopyBuffer(Napi::Env env, char* data, size_t len) {
|
||||
try {
|
||||
return Napi::Buffer<char>::New(env, data, len, FreeCallback);
|
||||
} catch (Napi::Error const &err) {
|
||||
static_cast<void>(err);
|
||||
}
|
||||
Napi::Buffer<char> buf = Napi::Buffer<char>::Copy(env, data, len);
|
||||
FreeCallback(nullptr, data);
|
||||
return buf;
|
||||
}
|
||||
|
||||
// Create an InputDescriptor instance from a Napi::Object describing an input image
|
||||
InputDescriptor* CreateInputDescriptor(Napi::Object input) {
|
||||
@ -75,7 +85,7 @@ namespace sharp {
|
||||
Napi::Buffer<char> buffer = input.Get("buffer").As<Napi::Buffer<char>>();
|
||||
descriptor->bufferLength = buffer.Length();
|
||||
descriptor->buffer = buffer.Data();
|
||||
descriptor->isBuffer = true;
|
||||
descriptor->isBuffer = TRUE;
|
||||
}
|
||||
descriptor->failOn = AttrAsEnum<VipsFailOn>(input, "failOn", VIPS_TYPE_FAIL_ON);
|
||||
// Density for vector-based input
|
||||
@ -93,7 +103,6 @@ namespace sharp {
|
||||
descriptor->rawWidth = AttrAsUint32(input, "rawWidth");
|
||||
descriptor->rawHeight = AttrAsUint32(input, "rawHeight");
|
||||
descriptor->rawPremultiplied = AttrAsBool(input, "rawPremultiplied");
|
||||
descriptor->rawPageHeight = AttrAsUint32(input, "rawPageHeight");
|
||||
}
|
||||
// Multi-page input (GIF, TIFF, PDF)
|
||||
if (HasAttr(input, "pages")) {
|
||||
@ -102,35 +111,19 @@ namespace sharp {
|
||||
if (HasAttr(input, "page")) {
|
||||
descriptor->page = AttrAsUint32(input, "page");
|
||||
}
|
||||
// SVG
|
||||
if (HasAttr(input, "svgStylesheet")) {
|
||||
descriptor->svgStylesheet = AttrAsStr(input, "svgStylesheet");
|
||||
}
|
||||
if (HasAttr(input, "svgHighBitdepth")) {
|
||||
descriptor->svgHighBitdepth = AttrAsBool(input, "svgHighBitdepth");
|
||||
}
|
||||
// Multi-level input (OpenSlide)
|
||||
if (HasAttr(input, "openSlideLevel")) {
|
||||
descriptor->openSlideLevel = AttrAsUint32(input, "openSlideLevel");
|
||||
if (HasAttr(input, "level")) {
|
||||
descriptor->level = AttrAsUint32(input, "level");
|
||||
}
|
||||
// subIFD (OME-TIFF)
|
||||
if (HasAttr(input, "subifd")) {
|
||||
descriptor->tiffSubifd = AttrAsInt32(input, "tiffSubifd");
|
||||
}
|
||||
// // PDF background color
|
||||
if (HasAttr(input, "pdfBackground")) {
|
||||
descriptor->pdfBackground = AttrAsVectorOfDouble(input, "pdfBackground");
|
||||
}
|
||||
// Use JPEG 2000 oneshot mode?
|
||||
if (HasAttr(input, "jp2Oneshot")) {
|
||||
descriptor->jp2Oneshot = AttrAsBool(input, "jp2Oneshot");
|
||||
descriptor->subifd = AttrAsInt32(input, "subifd");
|
||||
}
|
||||
// Create new image
|
||||
if (HasAttr(input, "createChannels")) {
|
||||
descriptor->createChannels = AttrAsUint32(input, "createChannels");
|
||||
descriptor->createWidth = AttrAsUint32(input, "createWidth");
|
||||
descriptor->createHeight = AttrAsUint32(input, "createHeight");
|
||||
descriptor->createPageHeight = AttrAsUint32(input, "createPageHeight");
|
||||
if (HasAttr(input, "createNoiseType")) {
|
||||
descriptor->createNoiseType = AttrAsStr(input, "createNoiseType");
|
||||
descriptor->createNoiseMean = AttrAsDouble(input, "createNoiseMean");
|
||||
@ -173,42 +166,20 @@ namespace sharp {
|
||||
descriptor->textWrap = AttrAsEnum<VipsTextWrap>(input, "textWrap", VIPS_TYPE_TEXT_WRAP);
|
||||
}
|
||||
}
|
||||
// Join images together
|
||||
if (HasAttr(input, "joinAnimated")) {
|
||||
descriptor->joinAnimated = AttrAsBool(input, "joinAnimated");
|
||||
}
|
||||
if (HasAttr(input, "joinAcross")) {
|
||||
descriptor->joinAcross = AttrAsUint32(input, "joinAcross");
|
||||
}
|
||||
if (HasAttr(input, "joinShim")) {
|
||||
descriptor->joinShim = AttrAsUint32(input, "joinShim");
|
||||
}
|
||||
if (HasAttr(input, "joinBackground")) {
|
||||
descriptor->joinBackground = AttrAsVectorOfDouble(input, "joinBackground");
|
||||
}
|
||||
if (HasAttr(input, "joinHalign")) {
|
||||
descriptor->joinHalign = AttrAsEnum<VipsAlign>(input, "joinHalign", VIPS_TYPE_ALIGN);
|
||||
}
|
||||
if (HasAttr(input, "joinValign")) {
|
||||
descriptor->joinValign = AttrAsEnum<VipsAlign>(input, "joinValign", VIPS_TYPE_ALIGN);
|
||||
}
|
||||
// Limit input images to a given number of pixels, where pixels = width * height
|
||||
descriptor->limitInputPixels = static_cast<uint64_t>(AttrAsInt64(input, "limitInputPixels"));
|
||||
if (HasAttr(input, "access")) {
|
||||
descriptor->access = AttrAsBool(input, "sequentialRead") ? VIPS_ACCESS_SEQUENTIAL : VIPS_ACCESS_RANDOM;
|
||||
}
|
||||
// Allow switch from random to sequential access
|
||||
descriptor->access = AttrAsBool(input, "sequentialRead") ? VIPS_ACCESS_SEQUENTIAL : VIPS_ACCESS_RANDOM;
|
||||
// Remove safety features and allow unlimited input
|
||||
descriptor->unlimited = AttrAsBool(input, "unlimited");
|
||||
// Use the EXIF orientation to auto orient the image
|
||||
descriptor->autoOrient = AttrAsBool(input, "autoOrient");
|
||||
return descriptor;
|
||||
}
|
||||
|
||||
// How many tasks are in the queue?
|
||||
std::atomic<int> counterQueue{0};
|
||||
volatile int counterQueue = 0;
|
||||
|
||||
// How many tasks are being processed?
|
||||
std::atomic<int> counterProcess{0};
|
||||
volatile int counterProcess = 0;
|
||||
|
||||
// Filename extension checkers
|
||||
static bool EndsWith(std::string const &str, std::string const &end) {
|
||||
@ -283,8 +254,6 @@ namespace sharp {
|
||||
case ImageType::FITS: id = "fits"; break;
|
||||
case ImageType::EXR: id = "exr"; break;
|
||||
case ImageType::JXL: id = "jxl"; break;
|
||||
case ImageType::RAD: id = "rad"; break;
|
||||
case ImageType::DCRAW: id = "dcraw"; break;
|
||||
case ImageType::VIPS: id = "vips"; break;
|
||||
case ImageType::RAW: id = "raw"; break;
|
||||
case ImageType::UNKNOWN: id = "unknown"; break;
|
||||
@ -331,10 +300,6 @@ namespace sharp {
|
||||
{ "VipsForeignLoadOpenexr", ImageType::EXR },
|
||||
{ "VipsForeignLoadJxlFile", ImageType::JXL },
|
||||
{ "VipsForeignLoadJxlBuffer", ImageType::JXL },
|
||||
{ "VipsForeignLoadRadFile", ImageType::RAD },
|
||||
{ "VipsForeignLoadRadBuffer", ImageType::RAD },
|
||||
{ "VipsForeignLoadDcRawFile", ImageType::DCRAW },
|
||||
{ "VipsForeignLoadDcRawBuffer", ImageType::DCRAW },
|
||||
{ "VipsForeignLoadVips", ImageType::VIPS },
|
||||
{ "VipsForeignLoadVipsFile", ImageType::VIPS },
|
||||
{ "VipsForeignLoadRaw", ImageType::RAW }
|
||||
@ -399,48 +364,6 @@ namespace sharp {
|
||||
imageType == ImageType::HEIF;
|
||||
}
|
||||
|
||||
/*
|
||||
Format-specific options builder
|
||||
*/
|
||||
vips::VOption* GetOptionsForImageType(ImageType imageType, InputDescriptor *descriptor) {
|
||||
vips::VOption *option = VImage::option()
|
||||
->set("access", descriptor->access)
|
||||
->set("fail_on", descriptor->failOn);
|
||||
if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {
|
||||
option->set("unlimited", true);
|
||||
}
|
||||
if (ImageTypeSupportsPage(imageType)) {
|
||||
option->set("n", descriptor->pages);
|
||||
option->set("page", descriptor->page);
|
||||
}
|
||||
switch (imageType) {
|
||||
case ImageType::SVG:
|
||||
option->set("dpi", descriptor->density)
|
||||
->set("stylesheet", descriptor->svgStylesheet.data())
|
||||
->set("high_bitdepth", descriptor->svgHighBitdepth);
|
||||
break;
|
||||
case ImageType::TIFF:
|
||||
option->set("tiffSubifd", descriptor->tiffSubifd);
|
||||
break;
|
||||
case ImageType::PDF:
|
||||
option->set("dpi", descriptor->density)
|
||||
->set("background", descriptor->pdfBackground);
|
||||
break;
|
||||
case ImageType::OPENSLIDE:
|
||||
option->set("openSlideLevel", descriptor->openSlideLevel);
|
||||
break;
|
||||
case ImageType::JP2:
|
||||
option->set("oneshot", descriptor->jp2Oneshot);
|
||||
break;
|
||||
case ImageType::MAGICK:
|
||||
option->set("density", std::to_string(descriptor->density).data());
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return option;
|
||||
}
|
||||
|
||||
/*
|
||||
Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data)
|
||||
*/
|
||||
@ -450,17 +373,12 @@ namespace sharp {
|
||||
if (descriptor->isBuffer) {
|
||||
if (descriptor->rawChannels > 0) {
|
||||
// Raw, uncompressed pixel data
|
||||
bool const is8bit = vips_band_format_is8bit(descriptor->rawDepth);
|
||||
image = VImage::new_from_memory(descriptor->buffer, descriptor->bufferLength,
|
||||
descriptor->rawWidth, descriptor->rawHeight, descriptor->rawChannels, descriptor->rawDepth);
|
||||
if (descriptor->rawChannels < 3) {
|
||||
image.get_image()->Type = is8bit ? VIPS_INTERPRETATION_B_W : VIPS_INTERPRETATION_GREY16;
|
||||
image.get_image()->Type = VIPS_INTERPRETATION_B_W;
|
||||
} else {
|
||||
image.get_image()->Type = is8bit ? VIPS_INTERPRETATION_sRGB : VIPS_INTERPRETATION_RGB16;
|
||||
}
|
||||
if (descriptor->rawPageHeight > 0) {
|
||||
image.set(VIPS_META_PAGE_HEIGHT, descriptor->rawPageHeight);
|
||||
image.set(VIPS_META_N_PAGES, static_cast<int>(descriptor->rawHeight / descriptor->rawPageHeight));
|
||||
image.get_image()->Type = VIPS_INTERPRETATION_sRGB;
|
||||
}
|
||||
if (descriptor->rawPremultiplied) {
|
||||
image = image.unpremultiply();
|
||||
@ -471,7 +389,28 @@ namespace sharp {
|
||||
imageType = DetermineImageType(descriptor->buffer, descriptor->bufferLength);
|
||||
if (imageType != ImageType::UNKNOWN) {
|
||||
try {
|
||||
vips::VOption *option = GetOptionsForImageType(imageType, descriptor);
|
||||
vips::VOption *option = VImage::option()
|
||||
->set("access", descriptor->access)
|
||||
->set("fail_on", descriptor->failOn);
|
||||
if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {
|
||||
option->set("unlimited", TRUE);
|
||||
}
|
||||
if (imageType == ImageType::SVG || imageType == ImageType::PDF) {
|
||||
option->set("dpi", descriptor->density);
|
||||
}
|
||||
if (imageType == ImageType::MAGICK) {
|
||||
option->set("density", std::to_string(descriptor->density).data());
|
||||
}
|
||||
if (ImageTypeSupportsPage(imageType)) {
|
||||
option->set("n", descriptor->pages);
|
||||
option->set("page", descriptor->page);
|
||||
}
|
||||
if (imageType == ImageType::OPENSLIDE) {
|
||||
option->set("level", descriptor->level);
|
||||
}
|
||||
if (imageType == ImageType::TIFF) {
|
||||
option->set("subifd", descriptor->subifd);
|
||||
}
|
||||
image = VImage::new_from_buffer(descriptor->buffer, descriptor->bufferLength, nullptr, option);
|
||||
if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) {
|
||||
image = SetDensity(image, descriptor->density);
|
||||
@ -511,10 +450,6 @@ namespace sharp {
|
||||
channels < 3 ? VIPS_INTERPRETATION_B_W : VIPS_INTERPRETATION_sRGB))
|
||||
.new_from_image(background);
|
||||
}
|
||||
if (descriptor->createPageHeight > 0) {
|
||||
image.set(VIPS_META_PAGE_HEIGHT, descriptor->createPageHeight);
|
||||
image.set(VIPS_META_N_PAGES, static_cast<int>(descriptor->createHeight / descriptor->createPageHeight));
|
||||
}
|
||||
image = image.cast(VIPS_FORMAT_UCHAR);
|
||||
imageType = ImageType::RAW;
|
||||
} else if (descriptor->textValue.length() > 0) {
|
||||
@ -558,7 +493,28 @@ namespace sharp {
|
||||
}
|
||||
if (imageType != ImageType::UNKNOWN) {
|
||||
try {
|
||||
vips::VOption *option = GetOptionsForImageType(imageType, descriptor);
|
||||
vips::VOption *option = VImage::option()
|
||||
->set("access", descriptor->access)
|
||||
->set("fail_on", descriptor->failOn);
|
||||
if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {
|
||||
option->set("unlimited", TRUE);
|
||||
}
|
||||
if (imageType == ImageType::SVG || imageType == ImageType::PDF) {
|
||||
option->set("dpi", descriptor->density);
|
||||
}
|
||||
if (imageType == ImageType::MAGICK) {
|
||||
option->set("density", std::to_string(descriptor->density).data());
|
||||
}
|
||||
if (ImageTypeSupportsPage(imageType)) {
|
||||
option->set("n", descriptor->pages);
|
||||
option->set("page", descriptor->page);
|
||||
}
|
||||
if (imageType == ImageType::OPENSLIDE) {
|
||||
option->set("level", descriptor->level);
|
||||
}
|
||||
if (imageType == ImageType::TIFF) {
|
||||
option->set("subifd", descriptor->subifd);
|
||||
}
|
||||
image = VImage::new_from_file(descriptor->file.data(), option);
|
||||
if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) {
|
||||
image = SetDensity(image, descriptor->density);
|
||||
@ -584,54 +540,15 @@ namespace sharp {
|
||||
Does this image have an embedded profile?
|
||||
*/
|
||||
bool HasProfile(VImage image) {
|
||||
return image.get_typeof(VIPS_META_ICC_NAME) == VIPS_TYPE_BLOB;
|
||||
return (image.get_typeof(VIPS_META_ICC_NAME) != 0) ? TRUE : FALSE;
|
||||
}
|
||||
|
||||
/*
|
||||
Get copy of embedded profile.
|
||||
Does this image have an alpha channel?
|
||||
Uses colour space interpretation with number of channels to guess this.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
bool HasAlpha(VImage image) {
|
||||
return image.has_alpha();
|
||||
}
|
||||
|
||||
/*
|
||||
@ -669,21 +586,22 @@ namespace sharp {
|
||||
*/
|
||||
VImage SetAnimationProperties(VImage image, int nPages, int pageHeight, std::vector<int> delay, int loop) {
|
||||
bool hasDelay = !delay.empty();
|
||||
|
||||
// Avoid a copy if none of the animation properties are needed.
|
||||
if (nPages == 1 && !hasDelay && loop == -1) return image;
|
||||
|
||||
if (delay.size() == 1) {
|
||||
// We have just one delay, repeat that value for all frames.
|
||||
delay.insert(delay.end(), nPages - 1, delay[0]);
|
||||
}
|
||||
|
||||
// Attaching metadata, need to copy the image.
|
||||
VImage copy = image.copy();
|
||||
|
||||
// Only set page-height if we have more than one page, or this could
|
||||
// accidentally turn into an animated image later.
|
||||
if (nPages > 1) copy.set(VIPS_META_PAGE_HEIGHT, pageHeight);
|
||||
if (hasDelay) {
|
||||
if (delay.size() == 1) {
|
||||
// We have just one delay, repeat that value for all frames.
|
||||
delay.insert(delay.end(), nPages - 1, delay[0]);
|
||||
}
|
||||
copy.set("delay", delay);
|
||||
}
|
||||
if (nPages == 1 && !hasDelay && loop == -1) {
|
||||
loop = 1;
|
||||
}
|
||||
if (hasDelay) copy.set("delay", delay);
|
||||
if (loop != -1) copy.set("loop", loop);
|
||||
|
||||
return copy;
|
||||
@ -761,10 +679,6 @@ namespace sharp {
|
||||
if (image.width() > 65535 || height > 65535) {
|
||||
throw vips::VError("Processed image is too large for the GIF format");
|
||||
}
|
||||
} else if (imageType == ImageType::HEIF) {
|
||||
if (image.width() > 16384 || height > 16384) {
|
||||
throw vips::VError("Processed image is too large for the HEIF format");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -812,7 +726,7 @@ namespace sharp {
|
||||
int *timeout = VIPS_NEW(im, int);
|
||||
*timeout = seconds;
|
||||
g_signal_connect(im, "eval", G_CALLBACK(VipsProgressCallBack), timeout);
|
||||
vips_image_set_progress(im, true);
|
||||
vips_image_set_progress(im, TRUE);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -822,7 +736,7 @@ namespace sharp {
|
||||
*/
|
||||
void VipsProgressCallBack(VipsImage *im, VipsProgress *progress, int *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);
|
||||
*timeout = 0;
|
||||
}
|
||||
@ -969,6 +883,14 @@ namespace sharp {
|
||||
return interpretation == VIPS_INTERPRETATION_RGB16 || interpretation == VIPS_INTERPRETATION_GREY16;
|
||||
}
|
||||
|
||||
/*
|
||||
Return the image alpha maximum. Useful for combining alpha bands. scRGB
|
||||
images are 0 - 1 for image data, but the alpha is 0 - 255.
|
||||
*/
|
||||
double MaximumImageAlpha(VipsInterpretation const interpretation) {
|
||||
return Is16Bit(interpretation) ? 65535.0 : 255.0;
|
||||
}
|
||||
|
||||
/*
|
||||
Convert RGBA value to another colourspace
|
||||
*/
|
||||
@ -1011,25 +933,25 @@ namespace sharp {
|
||||
0.0722 * colour[2])
|
||||
};
|
||||
}
|
||||
// Add alpha channel(s) to alphaColour colour
|
||||
if (colour[3] < 255.0 || image.has_alpha()) {
|
||||
int extraBands = image.bands() > 4 ? image.bands() - 3 : 1;
|
||||
alphaColour.insert(alphaColour.end(), extraBands, colour[3] * multiplier);
|
||||
// Add alpha channel to alphaColour colour
|
||||
if (colour[3] < 255.0 || HasAlpha(image)) {
|
||||
alphaColour.push_back(colour[3] * multiplier);
|
||||
}
|
||||
// Ensure alphaColour colour uses correct colourspace
|
||||
alphaColour = sharp::GetRgbaAsColourspace(alphaColour, image.interpretation(), premultiply);
|
||||
// Add non-transparent alpha channel, if required
|
||||
if (colour[3] < 255.0 && !image.has_alpha()) {
|
||||
image = image.bandjoin_const({ 255 * multiplier });
|
||||
if (colour[3] < 255.0 && !HasAlpha(image)) {
|
||||
image = image.bandjoin(
|
||||
VImage::new_matrix(image.width(), image.height()).new_from_image(255 * multiplier).cast(image.format()));
|
||||
}
|
||||
return std::make_tuple(image, alphaColour);
|
||||
}
|
||||
|
||||
/*
|
||||
Removes alpha channels, if any.
|
||||
Removes alpha channel, if any.
|
||||
*/
|
||||
VImage RemoveAlpha(VImage image) {
|
||||
while (image.bands() > 1 && image.has_alpha()) {
|
||||
if (HasAlpha(image)) {
|
||||
image = image.extract_band(0, VImage::option()->set("n", image.bands() - 1));
|
||||
}
|
||||
return image;
|
||||
@ -1039,14 +961,21 @@ namespace sharp {
|
||||
Ensures alpha channel, if missing.
|
||||
*/
|
||||
VImage EnsureAlpha(VImage image, double const value) {
|
||||
if (!image.has_alpha()) {
|
||||
image = image.bandjoin_const({ value * vips_interpretation_max_alpha(image.interpretation()) });
|
||||
if (!HasAlpha(image)) {
|
||||
std::vector<double> alpha;
|
||||
alpha.push_back(value * sharp::MaximumImageAlpha(image.interpretation()));
|
||||
image = image.bandjoin_const(alpha);
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
std::pair<double, double> ResolveShrink(int width, int height, int targetWidth, int targetHeight,
|
||||
Canvas canvas, bool withoutEnlargement, bool withoutReduction) {
|
||||
Canvas canvas, bool swap, bool withoutEnlargement, bool withoutReduction) {
|
||||
if (swap && canvas != Canvas::IGNORE_ASPECT) {
|
||||
// Swap input width and height when requested.
|
||||
std::swap(width, height);
|
||||
}
|
||||
|
||||
double hshrink = 1.0;
|
||||
double vshrink = 1.0;
|
||||
|
||||
@ -1112,14 +1041,4 @@ namespace sharp {
|
||||
return std::make_pair(hshrink, vshrink);
|
||||
}
|
||||
|
||||
/*
|
||||
Ensure decoding remains sequential.
|
||||
*/
|
||||
VImage StaySequential(VImage image, bool condition) {
|
||||
if (vips_image_is_sequential(image.get_image()) && condition) {
|
||||
image = image.copy_memory().copy();
|
||||
image.remove(VIPS_META_SEQUENTIAL);
|
||||
}
|
||||
return image;
|
||||
}
|
||||
} // namespace sharp
|
||||
|
115
src/common.h
@ -7,7 +7,6 @@
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <vector>
|
||||
#include <atomic>
|
||||
|
||||
#include <napi.h>
|
||||
#include <vips/vips8>
|
||||
@ -15,14 +14,18 @@
|
||||
// Verify platform and compiler compatibility
|
||||
|
||||
#if (VIPS_MAJOR_VERSION < 8) || \
|
||||
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION < 17) || \
|
||||
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION == 17 && VIPS_MICRO_VERSION < 1)
|
||||
#error "libvips version 8.17.1+ is required - please see https://sharp.pixelplumbing.com/install"
|
||||
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION < 14) || \
|
||||
(VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION == 14 && VIPS_MICRO_VERSION < 2)
|
||||
#error "libvips version 8.14.2+ is required - please see https://sharp.pixelplumbing.com/install"
|
||||
#endif
|
||||
|
||||
#if defined(__has_include)
|
||||
#if !__has_include(<filesystem>)
|
||||
#error "C++17 compiler required - please see https://sharp.pixelplumbing.com/install"
|
||||
#if ((!defined(__clang__)) && defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 6)))
|
||||
#error "GCC version 4.6+ is required for C++11 features - please see https://sharp.pixelplumbing.com/install"
|
||||
#endif
|
||||
|
||||
#if (defined(__clang__) && defined(__has_feature))
|
||||
#if (!__has_feature(cxx_range_for))
|
||||
#error "clang version 3.0+ is required for C++11 features - please see https://sharp.pixelplumbing.com/install"
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@ -33,7 +36,6 @@ namespace sharp {
|
||||
struct InputDescriptor { // NOLINT(runtime/indentation_namespace)
|
||||
std::string name;
|
||||
std::string file;
|
||||
bool autoOrient;
|
||||
char *buffer;
|
||||
VipsFailOn failOn;
|
||||
uint64_t limitInputPixels;
|
||||
@ -48,13 +50,13 @@ namespace sharp {
|
||||
int rawWidth;
|
||||
int rawHeight;
|
||||
bool rawPremultiplied;
|
||||
int rawPageHeight;
|
||||
int pages;
|
||||
int page;
|
||||
int level;
|
||||
int subifd;
|
||||
int createChannels;
|
||||
int createWidth;
|
||||
int createHeight;
|
||||
int createPageHeight;
|
||||
std::vector<double> createBackground;
|
||||
std::string createNoiseType;
|
||||
double createNoiseMean;
|
||||
@ -71,65 +73,41 @@ namespace sharp {
|
||||
int textSpacing;
|
||||
VipsTextWrap textWrap;
|
||||
int textAutofitDpi;
|
||||
bool joinAnimated;
|
||||
int joinAcross;
|
||||
int joinShim;
|
||||
std::vector<double> joinBackground;
|
||||
VipsAlign joinHalign;
|
||||
VipsAlign joinValign;
|
||||
std::string svgStylesheet;
|
||||
bool svgHighBitdepth;
|
||||
int tiffSubifd;
|
||||
int openSlideLevel;
|
||||
std::vector<double> pdfBackground;
|
||||
bool jp2Oneshot;
|
||||
|
||||
InputDescriptor():
|
||||
autoOrient(false),
|
||||
buffer(nullptr),
|
||||
failOn(VIPS_FAIL_ON_WARNING),
|
||||
limitInputPixels(0x3FFF * 0x3FFF),
|
||||
unlimited(false),
|
||||
access(VIPS_ACCESS_SEQUENTIAL),
|
||||
unlimited(FALSE),
|
||||
access(VIPS_ACCESS_RANDOM),
|
||||
bufferLength(0),
|
||||
isBuffer(false),
|
||||
isBuffer(FALSE),
|
||||
density(72.0),
|
||||
ignoreIcc(false),
|
||||
ignoreIcc(FALSE),
|
||||
rawDepth(VIPS_FORMAT_UCHAR),
|
||||
rawChannels(0),
|
||||
rawWidth(0),
|
||||
rawHeight(0),
|
||||
rawPremultiplied(false),
|
||||
rawPageHeight(0),
|
||||
pages(1),
|
||||
page(0),
|
||||
level(0),
|
||||
subifd(-1),
|
||||
createChannels(0),
|
||||
createWidth(0),
|
||||
createHeight(0),
|
||||
createPageHeight(0),
|
||||
createBackground{ 0.0, 0.0, 0.0, 255.0 },
|
||||
createNoiseMean(0.0),
|
||||
createNoiseSigma(0.0),
|
||||
textWidth(0),
|
||||
textHeight(0),
|
||||
textAlign(VIPS_ALIGN_LOW),
|
||||
textJustify(false),
|
||||
textJustify(FALSE),
|
||||
textDpi(72),
|
||||
textRgba(false),
|
||||
textRgba(FALSE),
|
||||
textSpacing(0),
|
||||
textWrap(VIPS_TEXT_WRAP_WORD),
|
||||
textAutofitDpi(0),
|
||||
joinAnimated(false),
|
||||
joinAcross(1),
|
||||
joinShim(0),
|
||||
joinBackground{ 0.0, 0.0, 0.0, 255.0 },
|
||||
joinHalign(VIPS_ALIGN_LOW),
|
||||
joinValign(VIPS_ALIGN_LOW),
|
||||
svgHighBitdepth(false),
|
||||
tiffSubifd(-1),
|
||||
openSlideLevel(0),
|
||||
pdfBackground{ 255.0, 255.0, 255.0, 255.0 },
|
||||
jp2Oneshot(false) {}
|
||||
textAutofitDpi(0) {}
|
||||
};
|
||||
|
||||
// Convenience methods to access the attributes of a Napi::Object
|
||||
@ -148,6 +126,7 @@ namespace sharp {
|
||||
return static_cast<T>(
|
||||
vips_enum_from_nick(nullptr, type, AttrAsStr(obj, attr).data()));
|
||||
}
|
||||
Napi::Buffer<char> NewOrCopyBuffer(Napi::Env env, char* data, size_t len);
|
||||
|
||||
// Create an InputDescriptor instance from a Napi::Object describing an input image
|
||||
InputDescriptor* CreateInputDescriptor(Napi::Object input);
|
||||
@ -168,8 +147,6 @@ namespace sharp {
|
||||
FITS,
|
||||
EXR,
|
||||
JXL,
|
||||
RAD,
|
||||
DCRAW,
|
||||
VIPS,
|
||||
RAW,
|
||||
UNKNOWN,
|
||||
@ -185,10 +162,10 @@ namespace sharp {
|
||||
};
|
||||
|
||||
// How many tasks are in the queue?
|
||||
extern std::atomic<int> counterQueue;
|
||||
extern volatile int counterQueue;
|
||||
|
||||
// How many tasks are being processed?
|
||||
extern std::atomic<int> counterProcess;
|
||||
extern volatile int counterProcess;
|
||||
|
||||
// Filename extension checkers
|
||||
bool IsJpeg(std::string const &str);
|
||||
@ -226,9 +203,14 @@ namespace sharp {
|
||||
ImageType DetermineImageType(char const *file);
|
||||
|
||||
/*
|
||||
Format-specific options builder
|
||||
Does this image type support multiple pages?
|
||||
*/
|
||||
vips::VOption* GetOptionsForImageType(ImageType imageType, InputDescriptor *descriptor);
|
||||
bool ImageTypeSupportsPage(ImageType imageType);
|
||||
|
||||
/*
|
||||
Does this image type support removal of safety limits?
|
||||
*/
|
||||
bool ImageTypeSupportsUnlimited(ImageType imageType);
|
||||
|
||||
/*
|
||||
Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data)
|
||||
@ -241,19 +223,10 @@ namespace sharp {
|
||||
bool HasProfile(VImage image);
|
||||
|
||||
/*
|
||||
Get copy of embedded profile.
|
||||
Does this image have an alpha channel?
|
||||
Uses colour space interpretation with number of channels to guess this.
|
||||
*/
|
||||
std::pair<char*, size_t> GetProfile(VImage image);
|
||||
|
||||
/*
|
||||
Set embedded profile.
|
||||
*/
|
||||
VImage SetProfile(VImage image, std::pair<char*, size_t> icc);
|
||||
|
||||
/*
|
||||
Remove all EXIF-related image fields.
|
||||
*/
|
||||
VImage RemoveExif(VImage image);
|
||||
bool HasAlpha(VImage image);
|
||||
|
||||
/*
|
||||
Get EXIF Orientation of image, if any.
|
||||
@ -362,6 +335,12 @@ namespace sharp {
|
||||
*/
|
||||
bool Is16Bit(VipsInterpretation const interpretation);
|
||||
|
||||
/*
|
||||
Return the image alpha maximum. Useful for combining alpha bands. scRGB
|
||||
images are 0 - 1 for image data, but the alpha is 0 - 255.
|
||||
*/
|
||||
double MaximumImageAlpha(VipsInterpretation const interpretation);
|
||||
|
||||
/*
|
||||
Convert RGBA value to another colourspace
|
||||
*/
|
||||
@ -374,7 +353,7 @@ namespace sharp {
|
||||
std::tuple<VImage, std::vector<double>> ApplyAlpha(VImage image, std::vector<double> colour, bool premultiply);
|
||||
|
||||
/*
|
||||
Removes alpha channels, if any.
|
||||
Removes alpha channel, if any.
|
||||
*/
|
||||
VImage RemoveAlpha(VImage image);
|
||||
|
||||
@ -384,15 +363,13 @@ namespace sharp {
|
||||
VImage EnsureAlpha(VImage image, double const value);
|
||||
|
||||
/*
|
||||
Calculate the horizontal and vertical shrink factors, taking the canvas mode into account.
|
||||
Calculate the shrink factor, taking into account auto-rotate, the canvas
|
||||
mode, and so on. The hshrink/vshrink are the amount to shrink the input
|
||||
image axes by in order for the output axes (ie. after rotation) to match
|
||||
the required thumbnail width/height and canvas mode.
|
||||
*/
|
||||
std::pair<double, double> ResolveShrink(int width, int height, int targetWidth, int targetHeight,
|
||||
Canvas canvas, bool withoutEnlargement, bool withoutReduction);
|
||||
|
||||
/*
|
||||
Ensure decoding remains sequential.
|
||||
*/
|
||||
VImage StaySequential(VImage image, bool condition = true);
|
||||
Canvas canvas, bool swap, bool withoutEnlargement, bool withoutReduction);
|
||||
|
||||
} // namespace sharp
|
||||
|
||||
|
@ -1,40 +0,0 @@
|
||||
# Copyright 2013 Lovell Fuller and others.
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
{
|
||||
'variables': {
|
||||
'OS': 'emscripten'
|
||||
},
|
||||
'target_defaults': {
|
||||
'default_configuration': 'Release',
|
||||
'type': 'executable',
|
||||
'cflags': [
|
||||
'-pthread'
|
||||
],
|
||||
'cflags_cc': [
|
||||
'-pthread'
|
||||
],
|
||||
'ldflags': [
|
||||
'--js-library=<!(node -p "require(\'emnapi\').js_library")',
|
||||
'-sAUTO_JS_LIBRARIES=0',
|
||||
'-sAUTO_NATIVE_LIBRARIES=0',
|
||||
'-sDEFAULT_TO_CXX=0',
|
||||
'-sNODEJS_CATCH_EXIT=0',
|
||||
'-sNODEJS_CATCH_REJECTION=0'
|
||||
],
|
||||
'defines': [
|
||||
'__STDC_FORMAT_MACROS',
|
||||
'BUILDING_NODE_EXTENSION',
|
||||
'EMNAPI_WORKER_POOL_SIZE=1'
|
||||
],
|
||||
'include_dirs': [
|
||||
'<!(node -p "require(\'emnapi\').include_dir")'
|
||||
],
|
||||
'sources': [
|
||||
'<!@(node -p "require(\'emnapi\').sources.map(x => JSON.stringify(path.relative(process.cwd(), x))).join(\' \')")'
|
||||
],
|
||||
'configurations': {
|
||||
'Release': {}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,19 +0,0 @@
|
||||
// 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();
|
||||
});
|
||||
};
|
151
src/libvips/cplusplus/VConnection.cpp
Normal file
@ -0,0 +1,151 @@
|
||||
/* Object part of the VSource and VTarget class
|
||||
*/
|
||||
|
||||
/*
|
||||
|
||||
Copyright (C) 1991-2001 The National Gallery
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
||||
02110-1301 USA
|
||||
|
||||
*/
|
||||
|
||||
/*
|
||||
|
||||
These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
|
||||
|
||||
*/
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif /*HAVE_CONFIG_H*/
|
||||
|
||||
#include <vips/vips8>
|
||||
|
||||
#include <vips/debug.h>
|
||||
|
||||
/*
|
||||
#define VIPS_DEBUG
|
||||
#define VIPS_DEBUG_VERBOSE
|
||||
*/
|
||||
|
||||
VIPS_NAMESPACE_START
|
||||
|
||||
VSource
|
||||
VSource::new_from_descriptor( int descriptor )
|
||||
{
|
||||
VipsSource *input;
|
||||
|
||||
if( !(input = vips_source_new_from_descriptor( descriptor )) )
|
||||
throw VError();
|
||||
|
||||
VSource out( input );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VSource
|
||||
VSource::new_from_file( const char *filename )
|
||||
{
|
||||
VipsSource *input;
|
||||
|
||||
if( !(input = vips_source_new_from_file( filename )) )
|
||||
throw VError();
|
||||
|
||||
VSource out( input );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VSource
|
||||
VSource::new_from_blob( VipsBlob *blob )
|
||||
{
|
||||
VipsSource *input;
|
||||
|
||||
if( !(input = vips_source_new_from_blob( blob )) )
|
||||
throw VError();
|
||||
|
||||
VSource out( input );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VSource
|
||||
VSource::new_from_memory( const void *data,
|
||||
size_t size )
|
||||
{
|
||||
VipsSource *input;
|
||||
|
||||
if( !(input = vips_source_new_from_memory( data, size )) )
|
||||
throw VError();
|
||||
|
||||
VSource out( input );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VSource
|
||||
VSource::new_from_options( const char *options )
|
||||
{
|
||||
VipsSource *input;
|
||||
|
||||
if( !(input = vips_source_new_from_options( options )) )
|
||||
throw VError();
|
||||
|
||||
VSource out( input );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VTarget
|
||||
VTarget::new_to_descriptor( int descriptor )
|
||||
{
|
||||
VipsTarget *output;
|
||||
|
||||
if( !(output = vips_target_new_to_descriptor( descriptor )) )
|
||||
throw VError();
|
||||
|
||||
VTarget out( output );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VTarget
|
||||
VTarget::new_to_file( const char *filename )
|
||||
{
|
||||
VipsTarget *output;
|
||||
|
||||
if( !(output = vips_target_new_to_file( filename )) )
|
||||
throw VError();
|
||||
|
||||
VTarget out( output );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VTarget
|
||||
VTarget::new_to_memory()
|
||||
{
|
||||
VipsTarget *output;
|
||||
|
||||
if( !(output = vips_target_new_to_memory()) )
|
||||
throw VError();
|
||||
|
||||
VTarget out( output );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VIPS_NAMESPACE_END
|
49
src/libvips/cplusplus/VError.cpp
Normal file
@ -0,0 +1,49 @@
|
||||
// Code for error type
|
||||
|
||||
/*
|
||||
|
||||
Copyright (C) 1991-2001 The National Gallery
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
||||
02110-1301 USA
|
||||
|
||||
*/
|
||||
|
||||
/*
|
||||
|
||||
These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
|
||||
|
||||
*/
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif /*HAVE_CONFIG_H*/
|
||||
|
||||
#include <vips/vips8>
|
||||
|
||||
VIPS_NAMESPACE_START
|
||||
|
||||
std::ostream &operator<<( std::ostream &file, const VError &err )
|
||||
{
|
||||
err.ostream_print( file );
|
||||
return( file );
|
||||
}
|
||||
|
||||
void VError::ostream_print( std::ostream &file ) const
|
||||
{
|
||||
file << _what;
|
||||
}
|
||||
|
||||
VIPS_NAMESPACE_END
|
1548
src/libvips/cplusplus/VImage.cpp
Normal file
62
src/libvips/cplusplus/VInterpolate.cpp
Normal file
@ -0,0 +1,62 @@
|
||||
/* Object part of VInterpolate class
|
||||
*/
|
||||
|
||||
/*
|
||||
|
||||
Copyright (C) 1991-2001 The National Gallery
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
||||
02110-1301 USA
|
||||
|
||||
*/
|
||||
|
||||
/*
|
||||
|
||||
These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
|
||||
|
||||
*/
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif /*HAVE_CONFIG_H*/
|
||||
|
||||
#include <vips/vips8>
|
||||
|
||||
#include <vips/debug.h>
|
||||
|
||||
/*
|
||||
#define VIPS_DEBUG
|
||||
#define VIPS_DEBUG_VERBOSE
|
||||
*/
|
||||
|
||||
VIPS_NAMESPACE_START
|
||||
|
||||
VInterpolate
|
||||
VInterpolate::new_from_name( const char *name, VOption *options )
|
||||
{
|
||||
VipsInterpolate *interp;
|
||||
|
||||
if( !(interp = vips_interpolate_new( name )) ) {
|
||||
delete options;
|
||||
throw VError();
|
||||
}
|
||||
delete options;
|
||||
|
||||
VInterpolate out( interp );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VIPS_NAMESPACE_END
|
27
src/libvips/cplusplus/VRegion.cpp
Normal file
@ -0,0 +1,27 @@
|
||||
// Object part of VRegion class
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif /*HAVE_CONFIG_H*/
|
||||
|
||||
#include <vips/vips8>
|
||||
|
||||
#include <vips/debug.h>
|
||||
|
||||
VIPS_NAMESPACE_START
|
||||
|
||||
VRegion
|
||||
VRegion::new_from_image( VImage image )
|
||||
{
|
||||
VipsRegion *region;
|
||||
|
||||
if( !(region = vips_region_new( image.get_image() )) ) {
|
||||
throw VError();
|
||||
}
|
||||
|
||||
VRegion out( region );
|
||||
|
||||
return( out );
|
||||
}
|
||||
|
||||
VIPS_NAMESPACE_END
|