Compare commits

...

14 Commits

Author SHA1 Message Date
Lovell Fuller
8f690236ed Release v0.20.0 2018-03-04 21:54:28 +00:00
Lovell Fuller
430a4297aa Add support for prebuilt sharp binaries on common platforms 2018-03-04 14:33:44 +00:00
Oskar Thornblad
69e3ab02c4 Mention EXIF orientation in metadata's jsdocs (#1142) 2018-03-04 14:19:53 +00:00
Lovell Fuller
b87a20b881 Release v0.19.1 2018-02-24 10:02:12 +00:00
Lovell Fuller
0e6f2d16ab Bump dependencies 2018-02-23 19:27:34 +00:00
Lovell Fuller
498b061819 Upgrade nan dependency, enables async hooks 2018-02-23 19:18:31 +00:00
Lovell Fuller
5ab6f599fb Prevent crop when at or below target dimensions #1134 2018-02-23 10:31:11 +00:00
Lovell Fuller
8b80626035 Changelog, credit and doc refresh for #1121 2018-02-18 19:14:37 +00:00
Andrea Bianco
f86ae79fdb Expose angle option in tile feature (#1121) 2018-02-18 20:00:08 +01:00
Lovell Fuller
1a4e68096f Changelog and credit for #1024, bump dependencies 2018-02-04 13:30:47 +00:00
Marcel
d599d1f29e Expose linear transform feature of libvips (#1024) 2018-02-04 10:36:04 +00:00
Lovell Fuller
73edfb3d2c Update list of files that npm can ignore 2018-01-13 10:28:31 +00:00
Lovell Fuller
ebae68d579 Doc refresh for #1077 2018-01-13 10:27:43 +00:00
Tony Mobily
573836e2b8 Add mention of max() to preserve ratio in withoutEnlargement (#1077) 2018-01-13 09:59:59 +00:00
44 changed files with 1108 additions and 502 deletions

1
.gitignore vendored
View File

@@ -12,3 +12,4 @@ vendor
.gitattributes .gitattributes
.DS_Store .DS_Store
.nyc_output .nyc_output
package-lock.json

View File

@@ -2,13 +2,13 @@ build
node_modules node_modules
coverage coverage
.editorconfig .editorconfig
.gitattributes
.gitignore .gitignore
test test
.travis.yml .travis.yml
appveyor.yml appveyor.yml
circle.yml
mkdocs.yml mkdocs.yml
vendor vendor
packaging .prebuildrc
preinstall.sh
.nyc_output .nyc_output
CONTRIBUTING.md

4
.prebuildrc Normal file
View File

@@ -0,0 +1,4 @@
{
"include-regex": "(sharp\\.node|libvips-cpp\\.dll)",
"strip": true
}

View File

@@ -41,8 +41,9 @@ Any change that modifies the existing public API should be added to the relevant
| Release | WIP branch | | Release | WIP branch |
| ------: | :--------- | | ------: | :--------- |
| v0.19.0 | suit | | v0.20.0 | prebuild |
| v0.20.0 | teeth | | v0.21.0 | teeth |
| v0.22.0 | uptake |
Please squash your changes into a single commit using a command like `git rebase -i upstream/<wip-branch>`. Please squash your changes into a single commit using a command like `git rebase -i upstream/<wip-branch>`.

View File

@@ -4,6 +4,10 @@
npm install sharp npm install sharp
``` ```
```sh
yarn add sharp
```
The typical use case for this high speed Node.js module The typical use case for this high speed Node.js module
is to convert large images in common formats to is to convert large images in common formats to
smaller, web-friendly JPEG, PNG and WebP images of varying dimensions. smaller, web-friendly JPEG, PNG and WebP images of varying dimensions.
@@ -17,8 +21,9 @@ Lanczos resampling ensures quality is not sacrificed for speed.
As well as image resizing, operations such as As well as image resizing, operations such as
rotation, extraction, compositing and gamma correction are available. rotation, extraction, compositing and gamma correction are available.
OS X, Windows (x64), Linux (x64, ARM) systems do not require Most modern 64-bit OS X, Windows and Linux (glibc) systems running
the installation of any external runtime dependencies. Node versions 4, 6, 8 and 9
do not require any additional install or runtime dependencies.
## Examples ## Examples

View File

@@ -5,9 +5,6 @@
['OS == "win"', { ['OS == "win"', {
# Build libvips C++ binding for Windows due to MSVC std library ABI changes # Build libvips C++ binding for Windows due to MSVC std library ABI changes
'type': 'shared_library', 'type': 'shared_library',
'variables': {
'download_vips': '<!(node -e "require(\'./binding\').download_vips()")'
},
'defines': [ 'defines': [
'VIPS_CPLUSPLUS_EXPORTS', 'VIPS_CPLUSPLUS_EXPORTS',
'_ALLOW_KEYWORD_MACROS' '_ALLOW_KEYWORD_MACROS'
@@ -49,37 +46,15 @@
'dependencies': [ 'dependencies': [
'libvips-cpp' 'libvips-cpp'
], ],
# Nested variables "pattern" borrowed from http://src.chromium.org/viewvc/chrome/trunk/src/build/common.gypi
'variables': { 'variables': {
'variables': {
'variables': {
'conditions': [
['OS != "win"', {
# Build the PKG_CONFIG_PATH environment variable with all possible combinations
'pkg_config_path': '<!(which brew >/dev/null 2>&1 && eval $(brew --env) && echo $PKG_CONFIG_LIBDIR || true):$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig:/usr/lib/pkgconfig'
}, {
'pkg_config_path': ''
}]
],
},
'conditions': [
['OS != "win"', {
# Which version, if any, of libvips is available globally via pkg-config?
'global_vips_version': '<!(PKG_CONFIG_PATH="<(pkg_config_path)" pkg-config --modversion vips-cpp 2>/dev/null || true)'
}, {
'global_vips_version': ''
}]
],
'pkg_config_path%': '<(pkg_config_path)'
},
'pkg_config_path%': '<(pkg_config_path)',
'runtime_link%': 'shared', 'runtime_link%': 'shared',
'conditions': [ 'conditions': [
['OS != "win"', { ['OS != "win"', {
# Does the globally available version of libvips, if any, meet the minimum version requirement? 'pkg_config_path': '<!(node -e "console.log(require(\'./lib/libvips\').pkgConfigPath())")',
'use_global_vips': '<!(GLOBAL_VIPS_VERSION="<(global_vips_version)" node -e "require(\'./binding\').use_global_vips()")' 'use_global_libvips': '<!(node -e "console.log(Boolean(require(\'./lib/libvips\').useGlobalLibvips()).toString())")'
}, { }, {
'use_global_vips': '' 'pkg_config_path': '',
'use_global_libvips': ''
}] }]
] ]
}, },
@@ -96,7 +71,7 @@
'<!(node -e "require(\'nan\')")' '<!(node -e "require(\'nan\')")'
], ],
'conditions': [ 'conditions': [
['use_global_vips == "true"', { ['use_global_libvips == "true"', {
# Use pkg-config for include and lib # 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)'], 'include_dirs': ['<!@(PKG_CONFIG_PATH="<(pkg_config_path)" pkg-config --cflags-only-I vips-cpp vips glib-2.0 | sed s\/-I//g)'],
'conditions': [ 'conditions': [
@@ -113,7 +88,7 @@
}] }]
] ]
}, { }, {
# Attempt to download pre-built libvips and install locally within node_modules # Use pre-built libvips stored locally within node_modules
'include_dirs': [ 'include_dirs': [
'vendor/include', 'vendor/include',
'vendor/include/glib-2.0', 'vendor/include/glib-2.0',
@@ -131,9 +106,6 @@
] ]
}], }],
['OS == "mac"', { ['OS == "mac"', {
'variables': {
'download_vips': '<!(node -e "require(\'./binding\').download_vips()")'
},
'libraries': [ 'libraries': [
'../vendor/lib/libvips-cpp.42.dylib', '../vendor/lib/libvips-cpp.42.dylib',
'../vendor/lib/libvips.42.dylib', '../vendor/lib/libvips.42.dylib',
@@ -144,9 +116,6 @@
] ]
}], }],
['OS == "linux"', { ['OS == "linux"', {
'variables': {
'download_vips': '<!(node -e "require(\'./binding\').download_vips()")'
},
'defines': [ 'defines': [
'_GLIBCXX_USE_CXX11_ABI=0' '_GLIBCXX_USE_CXX11_ABI=0'
], ],
@@ -219,65 +188,5 @@
] ]
} }
}, },
}, {
'target_name': 'win_copy_dlls',
'type': 'none',
'dependencies': [
'sharp'
],
'conditions': [
['OS == "win"', {
# Windows lacks support for rpath
'copies': [{
'destination': 'build/Release',
'files': [
'vendor/lib/libasprintf-0.dll',
'vendor/lib/libcairo-2.dll',
'vendor/lib/libcairo-gobject-2.dll',
'vendor/lib/libcairo-script-interpreter-2.dll',
'vendor/lib/libcharset-1.dll',
'vendor/lib/libcroco-0.6-3.dll',
'vendor/lib/libexif-12.dll',
'vendor/lib/libexpat-1.dll',
'vendor/lib/libffi-6.dll',
'vendor/lib/libfftw3-3.dll',
'vendor/lib/libfontconfig-1.dll',
'vendor/lib/libfreetype-6.dll',
'vendor/lib/libgcc_s_seh-1.dll',
'vendor/lib/libgdk_pixbuf-2.0-0.dll',
'vendor/lib/libgettextlib-0-19-8.dll',
'vendor/lib/libgettextpo-1.dll',
'vendor/lib/libgettextsrc-0-19-8.dll',
'vendor/lib/libgif-7.dll',
'vendor/lib/libgio-2.0-0.dll',
'vendor/lib/libglib-2.0-0.dll',
'vendor/lib/libgmodule-2.0-0.dll',
'vendor/lib/libgobject-2.0-0.dll',
'vendor/lib/libgsf-1-114.dll',
'vendor/lib/libgthread-2.0-0.dll',
'vendor/lib/libharfbuzz-0.dll',
'vendor/lib/libiconv-2.dll',
'vendor/lib/libintl-9.dll',
'vendor/lib/libjpeg-62.dll',
'vendor/lib/liblcms2-2.dll',
'vendor/lib/libpango-1.0-0.dll',
'vendor/lib/libpangocairo-1.0-0.dll',
'vendor/lib/libpangoft2-1.0-0.dll',
'vendor/lib/libpangowin32-1.0-0.dll',
'vendor/lib/libpixman-1-0.dll',
'vendor/lib/libpng16-16.dll',
'vendor/lib/libquadmath-0.dll',
'vendor/lib/librsvg-2-2.dll',
'vendor/lib/libssp-0.dll',
'vendor/lib/libstdc++-6.dll',
'vendor/lib/libtiff-5.dll',
'vendor/lib/libvips-42.dll',
'vendor/lib/libwebp-7.dll',
'vendor/lib/libxml2-2.dll',
'vendor/lib/zlib1.dll'
]
}]
}]
]
}] }]
} }

View File

@@ -1,108 +0,0 @@
'use strict';
const fs = require('fs');
const os = require('os');
const path = require('path');
const simpleGet = require('simple-get');
const semver = require('semver');
const tar = require('tar');
const detectLibc = require('detect-libc');
const agent = require('./lib/agent');
const platform = require('./lib/platform');
// Use NPM-provided environment variable where available, falling back to require-based method for Electron
const minimumLibvipsVersion = process.env.npm_package_config_libvips || require('./package.json').config.libvips;
const distBaseUrl = process.env.SHARP_DIST_BASE_URL || `https://github.com/lovell/sharp-libvips/releases/download/v${minimumLibvipsVersion}/`;
// -- Helpers
const unpack = function (tarPath, done) {
const vendorPath = path.join(__dirname, 'vendor');
fs.mkdirSync(vendorPath);
tar
.extract({
file: tarPath,
cwd: vendorPath,
strict: true
})
.then(done)
.catch(error);
};
const error = function (msg) {
if (msg instanceof Error) {
msg = msg.message;
}
process.stderr.write(`sharp: ${msg}\n`);
process.exit(1);
};
// -- Binary downloaders
module.exports.download_vips = function () {
// Check for existing vendored binaries and verify platform matches
const currentPlatformId = platform();
try {
const vendorPlatformId = require(path.join(__dirname, 'vendor', 'platform.json'));
if (currentPlatformId === vendorPlatformId) {
return;
} else {
error(`'${vendorPlatformId}' binaries cannot be used on the '${currentPlatformId}' platform. Please remove the 'node_modules/sharp/vendor' directory and run 'npm install'.`);
}
} catch (err) {}
// Ensure Intel 64-bit or ARM
const arch = process.env.npm_config_arch || process.arch;
if (arch === 'ia32') {
error(`Intel Architecture 32-bit systems require manual installation of libvips >= ${minimumLibvipsVersion} - please see http://sharp.pixelplumbing.com/page/install`);
}
// Ensure glibc Linux
if (detectLibc.isNonGlibcLinux) {
error(`Use with ${detectLibc.family} libc requires manual installation of libvips >= ${minimumLibvipsVersion} - please see http://sharp.pixelplumbing.com/page/install`);
}
// Ensure glibc >= 2.13
if (detectLibc.family === detectLibc.GLIBC && detectLibc.version && semver.lt(`${detectLibc.version}.0`, '2.13.0')) {
error(`Use with glibc version ${detectLibc.version} requires manual installation of libvips >= ${minimumLibvipsVersion} - please see http://sharp.pixelplumbing.com/page/install`);
}
// Arch/platform-specific .tar.gz
const tarFilename = ['libvips', minimumLibvipsVersion, currentPlatformId].join('-') + '.tar.gz';
// Download to per-process temporary file
const tarPathTemp = path.join(os.tmpdir(), `${process.pid}-${tarFilename}`);
const tmpFile = fs.createWriteStream(tarPathTemp).on('close', function () {
unpack(tarPathTemp, function () {
// Attempt to remove temporary file
try {
fs.unlinkSync(tarPathTemp);
} catch (err) {}
});
});
const url = distBaseUrl + tarFilename;
const simpleGetOpt = {
url: url,
agent: agent()
};
simpleGet(simpleGetOpt, function (err, response) {
if (err) {
error(`${url} download failed: ${err.message}`);
}
if (response.statusCode !== 200) {
error(`${url} download failed: status ${response.statusCode}`);
}
response.pipe(tmpFile);
});
};
module.exports.use_global_vips = function () {
const globalVipsVersion = process.env.GLOBAL_VIPS_VERSION;
if (globalVipsVersion) {
const useGlobalVips = semver.gte(
globalVipsVersion,
minimumLibvipsVersion
);
process.stdout.write(useGlobalVips ? 'true' : 'false');
} else {
process.stdout.write('false');
}
};

View File

@@ -2,9 +2,9 @@
### Table of Contents ### Table of Contents
- [extractChannel](#extractchannel) - [extractChannel][1]
- [joinChannel](#joinchannel) - [joinChannel][2]
- [bandbool](#bandbool) - [bandbool][3]
## extractChannel ## extractChannel
@@ -12,7 +12,7 @@ Extract a single channel from a multi-channel image.
**Parameters** **Parameters**
- `channel` **([Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) \| [String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String))** zero-indexed band number to extract, or `red`, `green` or `blue` as alternative to `0`, `1` or `2` respectively. - `channel` **([Number][4] \| [String][5])** zero-indexed band number to extract, or `red`, `green` or `blue` as alternative to `0`, `1` or `2` respectively.
**Examples** **Examples**
@@ -25,7 +25,7 @@ sharp(input)
}); });
``` ```
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid channel - Throws **[Error][6]** Invalid channel
Returns **Sharp** Returns **Sharp**
@@ -44,11 +44,11 @@ For raw pixel input, the `options` object should contain a `raw` attribute, whic
**Parameters** **Parameters**
- `images` **([Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)&lt;([String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Buffer](https://nodejs.org/api/buffer.html))> | [String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Buffer](https://nodejs.org/api/buffer.html))** one or more images (file paths, Buffers). - `images` **([Array][7]&lt;([String][5] \| [Buffer][8])> | [String][5] \| [Buffer][8])** one or more images (file paths, Buffers).
- `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** image options, see `sharp()` constructor. - `options` **[Object][9]** image options, see `sharp()` constructor.
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][6]** Invalid parameters
Returns **Sharp** Returns **Sharp**
@@ -58,7 +58,7 @@ Perform a bitwise boolean operation on all input image channels (bands) to produ
**Parameters** **Parameters**
- `boolOp` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. - `boolOp` **[String][5]** one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.
**Examples** **Examples**
@@ -72,6 +72,24 @@ sharp('3-channel-rgb-input.png')
}); });
``` ```
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][6]** Invalid parameters
Returns **Sharp** Returns **Sharp**
[1]: #extractchannel
[2]: #joinchannel
[3]: #bandbool
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
[8]: https://nodejs.org/api/buffer.html
[9]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object

View File

@@ -2,11 +2,11 @@
### Table of Contents ### Table of Contents
- [background](#background) - [background][1]
- [greyscale](#greyscale) - [greyscale][2]
- [grayscale](#grayscale) - [grayscale][3]
- [toColourspace](#tocolourspace) - [toColourspace][4]
- [toColorspace](#tocolorspace) - [toColorspace][5]
## background ## background
@@ -19,10 +19,10 @@ The alpha value is a float between `0` (transparent) and `1` (opaque).
**Parameters** **Parameters**
- `rgba` **([String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object))** parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. - `rgba` **([String][6] \| [Object][7])** parsed by the [color][8] module to extract values for red, green, blue and alpha.
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameter - Throws **[Error][9]** Invalid parameter
Returns **Sharp** Returns **Sharp**
@@ -37,7 +37,7 @@ An alpha channel may be present, and will be unchanged by the operation.
**Parameters** **Parameters**
- `greyscale` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** (optional, default `true`) - `greyscale` **[Boolean][10]** (optional, default `true`)
Returns **Sharp** Returns **Sharp**
@@ -47,7 +47,7 @@ Alternative spelling of `greyscale`.
**Parameters** **Parameters**
- `grayscale` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** (optional, default `true`) - `grayscale` **[Boolean][10]** (optional, default `true`)
Returns **Sharp** Returns **Sharp**
@@ -58,10 +58,10 @@ By default output image will be web-friendly sRGB, with additional channels inte
**Parameters** **Parameters**
- `colourspace` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?** output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/jcupitt/libvips/blob/master/libvips/iofuncs/enumtypes.c#L568) - `colourspace` **[String][6]?** output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...][11]
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][9]** Invalid parameters
Returns **Sharp** Returns **Sharp**
@@ -71,9 +71,31 @@ Alternative spelling of `toColourspace`.
**Parameters** **Parameters**
- `colorspace` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?** output colorspace. - `colorspace` **[String][6]?** output colorspace.
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][9]** Invalid parameters
Returns **Sharp** Returns **Sharp**
[1]: #background
[2]: #greyscale
[3]: #grayscale
[4]: #tocolourspace
[5]: #tocolorspace
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[8]: https://www.npmjs.org/package/color
[9]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
[10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[11]: https://github.com/jcupitt/libvips/blob/master/libvips/iofuncs/enumtypes.c#L568

View File

@@ -2,7 +2,7 @@
### Table of Contents ### Table of Contents
- [overlayWith](#overlaywith) - [overlayWith][1]
## overlayWith ## overlayWith
@@ -15,23 +15,23 @@ If the overlay image contains an alpha channel then composition with premultipli
**Parameters** **Parameters**
- `overlay` **([Buffer](https://nodejs.org/api/buffer.html) \| [String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String))** Buffer containing image data or String containing the path to an image file. - `overlay` **([Buffer][2] \| [String][3])** Buffer containing image data or String containing the path to an image file.
- `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** - `options` **[Object][4]?**
- `options.gravity` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** gravity at which to place the overlay. (optional, default `'centre'`) - `options.gravity` **[String][3]** gravity at which to place the overlay. (optional, default `'centre'`)
- `options.top` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** the pixel offset from the top edge. - `options.top` **[Number][5]?** the pixel offset from the top edge.
- `options.left` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** the pixel offset from the left edge. - `options.left` **[Number][5]?** the pixel offset from the left edge.
- `options.tile` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** set to true to repeat the overlay image across the entire image with the given `gravity`. (optional, default `false`) - `options.tile` **[Boolean][6]** set to true to repeat the overlay image across the entire image with the given `gravity`. (optional, default `false`)
- `options.cutout` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** set to true to apply only the alpha channel of the overlay image to the input image, giving the appearance of one image being cut out of another. (optional, default `false`) - `options.cutout` **[Boolean][6]** set to true to apply only the alpha channel of the overlay image to the input image, giving the appearance of one image being cut out of another. (optional, default `false`)
- `options.density` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** integral number representing the DPI for vector overlay image. (optional, default `72`) - `options.density` **[Number][5]** integral number representing the DPI for vector overlay image. (optional, default `72`)
- `options.raw` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** describes overlay when using raw pixel data. - `options.raw` **[Object][4]?** describes overlay when using raw pixel data.
- `options.raw.width` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** - `options.raw.width` **[Number][5]?**
- `options.raw.height` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** - `options.raw.height` **[Number][5]?**
- `options.raw.channels` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** - `options.raw.channels` **[Number][5]?**
- `options.create` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** describes a blank overlay to be created. - `options.create` **[Object][4]?** describes a blank overlay to be created.
- `options.create.width` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** - `options.create.width` **[Number][5]?**
- `options.create.height` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** - `options.create.height` **[Number][5]?**
- `options.create.channels` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** 3-4 - `options.create.channels` **[Number][5]?** 3-4
- `options.create.background` **([String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object))?** parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. - `options.create.background` **([String][3] \| [Object][4])?** parsed by the [color][7] module to extract values for red, green, blue and alpha.
**Examples** **Examples**
@@ -54,6 +54,22 @@ sharp('input.png')
}); });
``` ```
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][8]** Invalid parameters
Returns **Sharp** Returns **Sharp**
[1]: #overlaywith
[2]: https://nodejs.org/api/buffer.html
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[7]: https://www.npmjs.org/package/color
[8]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error

View File

@@ -2,33 +2,33 @@
### Table of Contents ### Table of Contents
- [Sharp](#sharp) - [Sharp][1]
- [format](#format) - [format][2]
- [versions](#versions) - [versions][3]
- [queue](#queue) - [queue][4]
## Sharp ## Sharp
**Parameters** **Parameters**
- `input` **([Buffer](https://nodejs.org/api/buffer.html) \| [String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String))?** if present, can be - `input` **([Buffer][5] \| [String][6])?** if present, can be
a Buffer containing JPEG, PNG, WebP, GIF, SVG, TIFF or raw pixel image data, or a Buffer containing JPEG, PNG, WebP, GIF, SVG, TIFF or raw pixel image data, or
a String containing the path to an JPEG, PNG, WebP, GIF, SVG or TIFF image file. a String containing the path to an JPEG, PNG, WebP, GIF, SVG or TIFF image file.
JPEG, PNG, WebP, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. JPEG, PNG, WebP, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present.
- `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** if present, is an Object with optional attributes. - `options` **[Object][7]?** if present, is an Object with optional attributes.
- `options.failOnError` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** by default apply a "best effort" - `options.failOnError` **[Boolean][8]** by default apply a "best effort"
to decode images, even if the data is corrupt or invalid. Set this flag to true to decode images, even if the data is corrupt or invalid. Set this flag to true
if you'd rather halt processing and raise an error when loading invalid images. (optional, default `false`) if you'd rather halt processing and raise an error when loading invalid images. (optional, default `false`)
- `options.density` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** integral number representing the DPI for vector images. (optional, default `72`) - `options.density` **[Number][9]** integral number representing the DPI for vector images. (optional, default `72`)
- `options.raw` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** describes raw pixel input image data. See `raw()` for pixel ordering. - `options.raw` **[Object][7]?** describes raw pixel input image data. See `raw()` for pixel ordering.
- `options.raw.width` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** - `options.raw.width` **[Number][9]?**
- `options.raw.height` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** - `options.raw.height` **[Number][9]?**
- `options.raw.channels` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** 1-4 - `options.raw.channels` **[Number][9]?** 1-4
- `options.create` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** describes a new image to be created. - `options.create` **[Object][7]?** describes a new image to be created.
- `options.create.width` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** - `options.create.width` **[Number][9]?**
- `options.create.height` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** - `options.create.height` **[Number][9]?**
- `options.create.channels` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** 3-4 - `options.create.channels` **[Number][9]?** 3-4
- `options.create.background` **([String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object))?** parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. - `options.create.background` **([String][6] \| [Object][7])?** parsed by the [color][10] module to extract values for red, green, blue and alpha.
**Examples** **Examples**
@@ -69,9 +69,9 @@ sharp({
.then( ... ); .then( ... );
``` ```
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][11]** Invalid parameters
Returns **[Sharp](#sharp)** Returns **[Sharp][12]**
### format ### format
@@ -83,7 +83,7 @@ An Object containing nested boolean values representing the available input and
console.log(sharp.format); console.log(sharp.format);
``` ```
Returns **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** Returns **[Object][7]**
### versions ### versions
@@ -109,3 +109,27 @@ sharp.queue.on('change', function(queueLength) {
console.log('Queue contains ' + queueLength + ' task(s)'); console.log('Queue contains ' + queueLength + ' task(s)');
}); });
``` ```
[1]: #sharp
[2]: #format
[3]: #versions
[4]: #queue
[5]: https://nodejs.org/api/buffer.html
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[8]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[9]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
[10]: https://www.npmjs.org/package/color
[11]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
[12]: #sharp

View File

@@ -2,11 +2,11 @@
### Table of Contents ### Table of Contents
- [clone](#clone) - [clone][1]
- [metadata](#metadata) - [metadata][2]
- [stats](#stats) - [stats][3]
- [limitInputPixels](#limitinputpixels) - [limitInputPixels][4]
- [sequentialRead](#sequentialread) - [sequentialRead][5]
## clone ## clone
@@ -33,23 +33,23 @@ Fast access to (uncached) image metadata without decoding any compressed image d
A Promises/A+ promise is returned when `callback` is not provided. A Promises/A+ promise is returned when `callback` is not provided.
- `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg` - `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg`
- `width`: Number of pixels wide - `width`: Number of pixels wide (EXIF orientation is not taken into consideration)
- `height`: Number of pixels high - `height`: Number of pixels high (EXIF orientation is not taken into consideration)
- `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/jcupitt/libvips/blob/master/libvips/iofuncs/enumtypes.c#L636) - `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...][6]
- `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK - `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK
- `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...](https://github.com/jcupitt/libvips/blob/master/libvips/iofuncs/enumtypes.c#L672) - `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...][7]
- `density`: Number of pixels per inch (DPI), if present - `density`: Number of pixels per inch (DPI), if present
- `hasProfile`: Boolean indicating the presence of an embedded ICC profile - `hasProfile`: Boolean indicating the presence of an embedded ICC profile
- `hasAlpha`: Boolean indicating the presence of an alpha transparency channel - `hasAlpha`: Boolean indicating the presence of an alpha transparency channel
- `orientation`: Number value of the EXIF Orientation header, if present - `orientation`: Number value of the EXIF Orientation header, if present
- `exif`: Buffer containing raw EXIF data, if present - `exif`: Buffer containing raw EXIF data, if present
- `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present - `icc`: Buffer containing raw [ICC][8] profile data, if present
- `iptc`: Buffer containing raw IPTC data, if present - `iptc`: Buffer containing raw IPTC data, if present
- `xmp`: Buffer containing raw XMP data, if present - `xmp`: Buffer containing raw XMP data, if present
**Parameters** **Parameters**
- `callback` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)?** called with the arguments `(err, metadata)` - `callback` **[Function][9]?** called with the arguments `(err, metadata)`
**Examples** **Examples**
@@ -68,7 +68,7 @@ image
}); });
``` ```
Returns **([Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)> | Sharp)** Returns **([Promise][10]&lt;[Object][11]> | Sharp)**
## stats ## stats
@@ -90,7 +90,7 @@ A Promise is returned when `callback` is not provided.
**Parameters** **Parameters**
- `callback` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)?** called with the arguments `(err, stats)` - `callback` **[Function][9]?** called with the arguments `(err, stats)`
**Examples** **Examples**
@@ -103,7 +103,7 @@ image
}); });
``` ```
Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)>** Returns **[Promise][10]&lt;[Object][11]>**
## limitInputPixels ## limitInputPixels
@@ -113,10 +113,10 @@ The default limit is 268402689 (0x3FFF _ 0x3FFF) pixels.
**Parameters** **Parameters**
- `limit` **([Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) \| [Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean))** an integral Number of pixels, zero or false to remove limit, true to use default limit. - `limit` **([Number][12] \| [Boolean][13])** an integral Number of pixels, zero or false to remove limit, true to use default limit.
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid limit - Throws **[Error][14]** Invalid limit
Returns **Sharp** Returns **Sharp**
@@ -129,6 +129,34 @@ The default behaviour _before_ function call is `false`, meaning the libvips acc
**Parameters** **Parameters**
- `sequentialRead` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** (optional, default `true`) - `sequentialRead` **[Boolean][13]** (optional, default `true`)
Returns **Sharp** Returns **Sharp**
[1]: #clone
[2]: #metadata
[3]: #stats
[4]: #limitinputpixels
[5]: #sequentialread
[6]: https://github.com/jcupitt/libvips/blob/master/libvips/iofuncs/enumtypes.c#L636
[7]: https://github.com/jcupitt/libvips/blob/master/libvips/iofuncs/enumtypes.c#L672
[8]: https://www.npmjs.com/package/icc
[9]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function
[10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise
[11]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[12]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
[13]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[14]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error

View File

@@ -2,22 +2,23 @@
### Table of Contents ### Table of Contents
- [rotate](#rotate) - [rotate][1]
- [extract](#extract) - [extract][2]
- [flip](#flip) - [flip][3]
- [flop](#flop) - [flop][4]
- [sharpen](#sharpen) - [sharpen][5]
- [blur](#blur) - [blur][6]
- [extend](#extend) - [extend][7]
- [flatten](#flatten) - [flatten][8]
- [trim](#trim) - [trim][9]
- [gamma](#gamma) - [gamma][10]
- [negate](#negate) - [negate][11]
- [normalise](#normalise) - [normalise][12]
- [normalize](#normalize) - [normalize][13]
- [convolve](#convolve) - [convolve][14]
- [threshold](#threshold) - [threshold][15]
- [boolean](#boolean) - [boolean][16]
- [linear][17]
## rotate ## rotate
@@ -37,7 +38,7 @@ for example `rotate(x).extract(y)` will produce a different result to `extract(y
**Parameters** **Parameters**
- `angle` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** angle of rotation, must be a multiple of 90. (optional, default `auto`) - `angle` **[Number][18]** angle of rotation, must be a multiple of 90. (optional, default `auto`)
**Examples** **Examples**
@@ -53,7 +54,7 @@ const pipeline = sharp()
readableStream.pipe(pipeline); readableStream.pipe(pipeline);
``` ```
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][19]** Invalid parameters
Returns **Sharp** Returns **Sharp**
@@ -67,11 +68,11 @@ Extract a region of the image.
**Parameters** **Parameters**
- `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** - `options` **[Object][20]**
- `options.left` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** zero-indexed offset from left edge - `options.left` **[Number][18]** zero-indexed offset from left edge
- `options.top` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** zero-indexed offset from top edge - `options.top` **[Number][18]** zero-indexed offset from top edge
- `options.width` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** dimension of extracted image - `options.width` **[Number][18]** dimension of extracted image
- `options.height` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** dimension of extracted image - `options.height` **[Number][18]** dimension of extracted image
**Examples** **Examples**
@@ -93,7 +94,7 @@ sharp(input)
}); });
``` ```
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][19]** Invalid parameters
Returns **Sharp** Returns **Sharp**
@@ -104,7 +105,7 @@ The use of `flip` implies the removal of the EXIF `Orientation` tag, if any.
**Parameters** **Parameters**
- `flip` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** (optional, default `true`) - `flip` **[Boolean][21]** (optional, default `true`)
Returns **Sharp** Returns **Sharp**
@@ -115,7 +116,7 @@ The use of `flop` implies the removal of the EXIF `Orientation` tag, if any.
**Parameters** **Parameters**
- `flop` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** (optional, default `true`) - `flop` **[Boolean][21]** (optional, default `true`)
Returns **Sharp** Returns **Sharp**
@@ -128,12 +129,12 @@ Separate control over the level of sharpening in "flat" and "jagged" areas is av
**Parameters** **Parameters**
- `sigma` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. - `sigma` **[Number][18]?** the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
- `flat` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** the level of sharpening to apply to "flat" areas. (optional, default `1.0`) - `flat` **[Number][18]** the level of sharpening to apply to "flat" areas. (optional, default `1.0`)
- `jagged` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** the level of sharpening to apply to "jagged" areas. (optional, default `2.0`) - `jagged` **[Number][18]** the level of sharpening to apply to "jagged" areas. (optional, default `2.0`)
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][19]** Invalid parameters
Returns **Sharp** Returns **Sharp**
@@ -145,10 +146,10 @@ When a `sigma` is provided, performs a slower, more accurate Gaussian blur.
**Parameters** **Parameters**
- `sigma` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. - `sigma` **[Number][18]?** a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][19]** Invalid parameters
Returns **Sharp** Returns **Sharp**
@@ -159,11 +160,11 @@ This operation will always occur after resizing and extraction, if any.
**Parameters** **Parameters**
- `extend` **([Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) \| [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object))** single pixel count to add to all edges or an Object with per-edge counts - `extend` **([Number][18] \| [Object][20])** single pixel count to add to all edges or an Object with per-edge counts
- `extend.top` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** - `extend.top` **[Number][18]?**
- `extend.left` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** - `extend.left` **[Number][18]?**
- `extend.bottom` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** - `extend.bottom` **[Number][18]?**
- `extend.right` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** - `extend.right` **[Number][18]?**
**Examples** **Examples**
@@ -177,7 +178,7 @@ sharp(input)
... ...
``` ```
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][19]** Invalid parameters
Returns **Sharp** Returns **Sharp**
@@ -187,7 +188,7 @@ Merge alpha transparency channel, if any, with `background`.
**Parameters** **Parameters**
- `flatten` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** (optional, default `true`) - `flatten` **[Boolean][21]** (optional, default `true`)
Returns **Sharp** Returns **Sharp**
@@ -197,10 +198,10 @@ Trim "boring" pixels from all edges that contain values within a percentage simi
**Parameters** **Parameters**
- `tolerance` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** value between 1 and 99 representing the percentage similarity. (optional, default `10`) - `tolerance` **[Number][18]** value between 1 and 99 representing the percentage similarity. (optional, default `10`)
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][19]** Invalid parameters
Returns **Sharp** Returns **Sharp**
@@ -214,10 +215,10 @@ when applying a gamma correction.
**Parameters** **Parameters**
- `gamma` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** value between 1.0 and 3.0. (optional, default `2.2`) - `gamma` **[Number][18]** value between 1.0 and 3.0. (optional, default `2.2`)
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][19]** Invalid parameters
Returns **Sharp** Returns **Sharp**
@@ -227,7 +228,7 @@ Produce the "negative" of the image.
**Parameters** **Parameters**
- `negate` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** (optional, default `true`) - `negate` **[Boolean][21]** (optional, default `true`)
Returns **Sharp** Returns **Sharp**
@@ -237,7 +238,7 @@ Enhance output image contrast by stretching its luminance to cover the full dyna
**Parameters** **Parameters**
- `normalise` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** (optional, default `true`) - `normalise` **[Boolean][21]** (optional, default `true`)
Returns **Sharp** Returns **Sharp**
@@ -247,7 +248,7 @@ Alternative spelling of normalise.
**Parameters** **Parameters**
- `normalize` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** (optional, default `true`) - `normalize` **[Boolean][21]** (optional, default `true`)
Returns **Sharp** Returns **Sharp**
@@ -257,12 +258,12 @@ Convolve the image with the specified kernel.
**Parameters** **Parameters**
- `kernel` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** - `kernel` **[Object][20]**
- `kernel.width` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** width of the kernel in pixels. - `kernel.width` **[Number][18]** width of the kernel in pixels.
- `kernel.height` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** width of the kernel in pixels. - `kernel.height` **[Number][18]** width of the kernel in pixels.
- `kernel.kernel` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)&lt;[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)>** Array of length `width*height` containing the kernel values. - `kernel.kernel` **[Array][22]&lt;[Number][18]>** Array of length `width*height` containing the kernel values.
- `kernel.scale` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** the scale of the kernel in pixels. (optional, default `sum`) - `kernel.scale` **[Number][18]** the scale of the kernel in pixels. (optional, default `sum`)
- `kernel.offset` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** the offset of the kernel in pixels. (optional, default `0`) - `kernel.offset` **[Number][18]** the offset of the kernel in pixels. (optional, default `0`)
**Examples** **Examples**
@@ -280,7 +281,7 @@ sharp(input)
}); });
``` ```
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][19]** Invalid parameters
Returns **Sharp** Returns **Sharp**
@@ -290,13 +291,13 @@ Any pixel value greather than or equal to the threshold value will be set to 255
**Parameters** **Parameters**
- `threshold` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** a value in the range 0-255 representing the level at which the threshold will be applied. (optional, default `128`) - `threshold` **[Number][18]** a value in the range 0-255 representing the level at which the threshold will be applied. (optional, default `128`)
- `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** - `options` **[Object][20]?**
- `options.greyscale` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** convert to single channel greyscale. (optional, default `true`) - `options.greyscale` **[Boolean][21]** convert to single channel greyscale. (optional, default `true`)
- `options.grayscale` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** alternative spelling for greyscale. (optional, default `true`) - `options.grayscale` **[Boolean][21]** alternative spelling for greyscale. (optional, default `true`)
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][19]** Invalid parameters
Returns **Sharp** Returns **Sharp**
@@ -309,15 +310,77 @@ the selected bitwise boolean `operation` between the corresponding pixels of the
**Parameters** **Parameters**
- `operand` **([Buffer](https://nodejs.org/api/buffer.html) \| [String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String))** Buffer containing image data or String containing the path to an image file. - `operand` **([Buffer][23] \| [String][24])** Buffer containing image data or String containing the path to an image file.
- `operator` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. - `operator` **[String][24]** one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.
- `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** - `options` **[Object][20]?**
- `options.raw` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** describes operand when using raw pixel data. - `options.raw` **[Object][20]?** describes operand when using raw pixel data.
- `options.raw.width` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** - `options.raw.width` **[Number][18]?**
- `options.raw.height` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** - `options.raw.height` **[Number][18]?**
- `options.raw.channels` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** - `options.raw.channels` **[Number][18]?**
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][19]** Invalid parameters
Returns **Sharp** Returns **Sharp**
## linear
Apply the linear formula a \* input + b to the image (levels adjustment)
**Parameters**
- `a` **[Number][18]** multiplier (optional, default `1.0`)
- `b` **[Number][18]** offset (optional, default `0.0`)
- Throws **[Error][19]** Invalid parameters
Returns **Sharp**
[1]: #rotate
[2]: #extract
[3]: #flip
[4]: #flop
[5]: #sharpen
[6]: #blur
[7]: #extend
[8]: #flatten
[9]: #trim
[10]: #gamma
[11]: #negate
[12]: #normalise
[13]: #normalize
[14]: #convolve
[15]: #threshold
[16]: #boolean
[17]: #linear
[18]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
[19]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
[20]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[21]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[22]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
[23]: https://nodejs.org/api/buffer.html
[24]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String

View File

@@ -2,16 +2,16 @@
### Table of Contents ### Table of Contents
- [toFile](#tofile) - [toFile][1]
- [toBuffer](#tobuffer) - [toBuffer][2]
- [withMetadata](#withmetadata) - [withMetadata][3]
- [jpeg](#jpeg) - [jpeg][4]
- [png](#png) - [png][5]
- [webp](#webp) - [webp][6]
- [tiff](#tiff) - [tiff][7]
- [raw](#raw) - [raw][8]
- [toFormat](#toformat) - [toFormat][9]
- [tile](#tile) - [tile][10]
## toFile ## toFile
@@ -25,16 +25,16 @@ A `Promise` is returned when `callback` is not provided.
**Parameters** **Parameters**
- `fileOut` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** the path to write the image data to. - `fileOut` **[String][11]** the path to write the image data to.
- `callback` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)?** called on completion with two arguments `(err, info)`. - `callback` **[Function][12]?** called on completion with two arguments `(err, info)`.
`info` contains the output image `format`, `size` (bytes), `width`, `height`, `info` contains the output image `format`, `size` (bytes), `width`, `height`,
`channels` and `premultiplied` (indicating if premultiplication was used). `channels` and `premultiplied` (indicating if premultiplication was used).
When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][13]** Invalid parameters
Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)>** when no callback is provided Returns **[Promise][14]&lt;[Object][15]>** when no callback is provided
## toBuffer ## toBuffer
@@ -54,11 +54,11 @@ A `Promise` is returned when `callback` is not provided.
**Parameters** **Parameters**
- `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** - `options` **[Object][15]?**
- `options.resolveWithObject` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)?** Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`. - `options.resolveWithObject` **[Boolean][16]?** Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`.
- `callback` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)?** - `callback` **[Function][12]?**
Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;[Buffer](https://nodejs.org/api/buffer.html)>** when no callback is provided Returns **[Promise][14]&lt;[Buffer][17]>** when no callback is provided
## withMetadata ## withMetadata
@@ -68,11 +68,11 @@ This will also convert to and add a web-friendly sRGB ICC profile.
**Parameters** **Parameters**
- `withMetadata` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** - `withMetadata` **[Object][15]?**
- `withMetadata.orientation` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** value between 1 and 8, used to update the EXIF `Orientation` tag. - `withMetadata.orientation` **[Number][18]?** value between 1 and 8, used to update the EXIF `Orientation` tag.
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][13]** Invalid parameters
Returns **Sharp** Returns **Sharp**
@@ -82,18 +82,18 @@ Use these JPEG options for output image.
**Parameters** **Parameters**
- `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** output options - `options` **[Object][15]?** output options
- `options.quality` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** quality, integer 1-100 (optional, default `80`) - `options.quality` **[Number][18]** quality, integer 1-100 (optional, default `80`)
- `options.progressive` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** use progressive (interlace) scan (optional, default `false`) - `options.progressive` **[Boolean][16]** use progressive (interlace) scan (optional, default `false`)
- `options.chromaSubsampling` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** set to '4:4:4' to prevent chroma subsampling when quality &lt;= 90 (optional, default `'4:2:0'`) - `options.chromaSubsampling` **[String][11]** set to '4:4:4' to prevent chroma subsampling when quality &lt;= 90 (optional, default `'4:2:0'`)
- `options.trellisQuantisation` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** apply trellis quantisation, requires mozjpeg (optional, default `false`) - `options.trellisQuantisation` **[Boolean][16]** apply trellis quantisation, requires mozjpeg (optional, default `false`)
- `options.overshootDeringing` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** apply overshoot deringing, requires mozjpeg (optional, default `false`) - `options.overshootDeringing` **[Boolean][16]** apply overshoot deringing, requires mozjpeg (optional, default `false`)
- `options.optimiseScans` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** optimise progressive scans, forces progressive, requires mozjpeg (optional, default `false`) - `options.optimiseScans` **[Boolean][16]** optimise progressive scans, forces progressive, requires mozjpeg (optional, default `false`)
- `options.optimizeScans` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** alternative spelling of optimiseScans (optional, default `false`) - `options.optimizeScans` **[Boolean][16]** alternative spelling of optimiseScans (optional, default `false`)
- `options.force` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** force JPEG output, otherwise attempt to use input format (optional, default `true`) - `options.force` **[Boolean][16]** force JPEG output, otherwise attempt to use input format (optional, default `true`)
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid options - Throws **[Error][13]** Invalid options
Returns **Sharp** Returns **Sharp**
@@ -103,14 +103,14 @@ Use these PNG options for output image.
**Parameters** **Parameters**
- `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** - `options` **[Object][15]?**
- `options.progressive` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** use progressive (interlace) scan (optional, default `false`) - `options.progressive` **[Boolean][16]** use progressive (interlace) scan (optional, default `false`)
- `options.compressionLevel` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** zlib compression level, 0-9 (optional, default `9`) - `options.compressionLevel` **[Number][18]** zlib compression level, 0-9 (optional, default `9`)
- `options.adaptiveFiltering` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** use adaptive row filtering (optional, default `false`) - `options.adaptiveFiltering` **[Boolean][16]** use adaptive row filtering (optional, default `false`)
- `options.force` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** force PNG output, otherwise attempt to use input format (optional, default `true`) - `options.force` **[Boolean][16]** force PNG output, otherwise attempt to use input format (optional, default `true`)
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid options - Throws **[Error][13]** Invalid options
Returns **Sharp** Returns **Sharp**
@@ -120,15 +120,15 @@ Use these WebP options for output image.
**Parameters** **Parameters**
- `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** output options - `options` **[Object][15]?** output options
- `options.quality` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** quality, integer 1-100 (optional, default `80`) - `options.quality` **[Number][18]** quality, integer 1-100 (optional, default `80`)
- `options.alphaQuality` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** quality of alpha layer, integer 0-100 (optional, default `100`) - `options.alphaQuality` **[Number][18]** quality of alpha layer, integer 0-100 (optional, default `100`)
- `options.lossless` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** use lossless compression mode (optional, default `false`) - `options.lossless` **[Boolean][16]** use lossless compression mode (optional, default `false`)
- `options.nearLossless` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** use near_lossless compression mode (optional, default `false`) - `options.nearLossless` **[Boolean][16]** use near_lossless compression mode (optional, default `false`)
- `options.force` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** force WebP output, otherwise attempt to use input format (optional, default `true`) - `options.force` **[Boolean][16]** force WebP output, otherwise attempt to use input format (optional, default `true`)
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid options - Throws **[Error][13]** Invalid options
Returns **Sharp** Returns **Sharp**
@@ -138,17 +138,17 @@ Use these TIFF options for output image.
**Parameters** **Parameters**
- `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** output options - `options` **[Object][15]?** output options
- `options.quality` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** quality, integer 1-100 (optional, default `80`) - `options.quality` **[Number][18]** quality, integer 1-100 (optional, default `80`)
- `options.force` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** force TIFF output, otherwise attempt to use input format (optional, default `true`) - `options.force` **[Boolean][16]** force TIFF output, otherwise attempt to use input format (optional, default `true`)
- `options.compression` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** compression options: lzw, deflate, jpeg (optional, default `'jpeg'`) - `options.compression` **[Boolean][16]** compression options: lzw, deflate, jpeg (optional, default `'jpeg'`)
- `options.predictor` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** compression predictor options: none, horizontal, float (optional, default `'horizontal'`) - `options.predictor` **[Boolean][16]** compression predictor options: none, horizontal, float (optional, default `'horizontal'`)
- `options.xres` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** horizontal resolution in pixels/mm (optional, default `1.0`) - `options.xres` **[Number][18]** horizontal resolution in pixels/mm (optional, default `1.0`)
- `options.yres` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** vertical resolution in pixels/mm (optional, default `1.0`) - `options.yres` **[Number][18]** vertical resolution in pixels/mm (optional, default `1.0`)
- `options.squash` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** squash 8-bit images down to 1 bit (optional, default `false`) - `options.squash` **[Boolean][16]** squash 8-bit images down to 1 bit (optional, default `false`)
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid options - Throws **[Error][13]** Invalid options
Returns **Sharp** Returns **Sharp**
@@ -164,11 +164,11 @@ Force output to a given format.
**Parameters** **Parameters**
- `format` **([String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object))** as a String or an Object with an 'id' attribute - `format` **([String][11] \| [Object][15])** as a String or an Object with an 'id' attribute
- `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** output options - `options` **[Object][15]** output options
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** unsupported format or options - Throws **[Error][13]** unsupported format or options
Returns **Sharp** Returns **Sharp**
@@ -180,11 +180,12 @@ Use a `.zip` or `.szi` file extension with `toFile` to write to a compressed arc
**Parameters** **Parameters**
- `tile` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** - `tile` **[Object][15]?**
- `tile.size` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** tile size in pixels, a value between 1 and 8192. (optional, default `256`) - `tile.size` **[Number][18]** tile size in pixels, a value between 1 and 8192. (optional, default `256`)
- `tile.overlap` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** tile overlap in pixels, a value between 0 and 8192. (optional, default `0`) - `tile.overlap` **[Number][18]** tile overlap in pixels, a value between 0 and 8192. (optional, default `0`)
- `tile.container` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** tile container, with value `fs` (filesystem) or `zip` (compressed file). (optional, default `'fs'`) - `tile.angle` **[Number][18]** tile angle of rotation, must be a multiple of 90. (optional, default `0`)
- `tile.layout` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** filesystem layout, possible values are `dz`, `zoomify` or `google`. (optional, default `'dz'`) - `tile.container` **[String][11]** tile container, with value `fs` (filesystem) or `zip` (compressed file). (optional, default `'fs'`)
- `tile.layout` **[String][11]** filesystem layout, possible values are `dz`, `zoomify` or `google`. (optional, default `'dz'`)
**Examples** **Examples**
@@ -200,6 +201,42 @@ sharp('input.tiff')
}); });
``` ```
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][13]** Invalid parameters
Returns **Sharp** Returns **Sharp**
[1]: #tofile
[2]: #tobuffer
[3]: #withmetadata
[4]: #jpeg
[5]: #png
[6]: #webp
[7]: #tiff
[8]: #raw
[9]: #toformat
[10]: #tile
[11]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[12]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function
[13]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
[14]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise
[15]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[16]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[17]: https://nodejs.org/api/buffer.html
[18]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number

View File

@@ -2,13 +2,13 @@
### Table of Contents ### Table of Contents
- [resize](#resize) - [resize][1]
- [crop](#crop) - [crop][2]
- [embed](#embed) - [embed][3]
- [max](#max) - [max][4]
- [min](#min) - [min][5]
- [ignoreAspectRatio](#ignoreaspectratio) - [ignoreAspectRatio][6]
- [withoutEnlargement](#withoutenlargement) - [withoutEnlargement][7]
## resize ## resize
@@ -17,18 +17,18 @@ By default, the resized image is centre cropped to the exact size specified.
Possible kernels are: Possible kernels are:
- `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). - `nearest`: Use [nearest neighbour interpolation][8].
- `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline). - `cubic`: Use a [Catmull-Rom spline][9].
- `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`. - `lanczos2`: Use a [Lanczos kernel][10] with `a=2`.
- `lanczos3`: Use a Lanczos kernel with `a=3` (the default). - `lanczos3`: Use a Lanczos kernel with `a=3` (the default).
**Parameters** **Parameters**
- `width` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height. - `width` **[Number][11]?** pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height.
- `height` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width. - `height` **[Number][11]?** pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width.
- `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** - `options` **[Object][12]?**
- `options.kernel` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** the kernel to use for image reduction. (optional, default `'lanczos3'`) - `options.kernel` **[String][13]** the kernel to use for image reduction. (optional, default `'lanczos3'`)
- `options.fastShrinkOnLoad` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern on some images. (optional, default `true`) - `options.fastShrinkOnLoad` **[Boolean][14]** take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern on some images. (optional, default `true`)
**Examples** **Examples**
@@ -47,7 +47,7 @@ sharp(inputBuffer)
}); });
``` ```
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][15]** Invalid parameters
Returns **Sharp** Returns **Sharp**
@@ -61,12 +61,12 @@ Possible attributes of the optional `sharp.gravity` are `north`, `northeast`, `e
The experimental strategy-based approach 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. then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.
- `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29). - `entropy`: focus on the region with the highest [Shannon entropy][16].
- `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones. - `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
**Parameters** **Parameters**
- `crop` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** A member of `sharp.gravity` to crop to an edge/corner or `sharp.strategy` to crop dynamically. (optional, default `'centre'`) - `crop` **[String][13]** A member of `sharp.gravity` to crop to an edge/corner or `sharp.strategy` to crop dynamically. (optional, default `'centre'`)
**Examples** **Examples**
@@ -82,7 +82,7 @@ const transformer = sharp()
readableStream.pipe(transformer).pipe(writableStream); readableStream.pipe(transformer).pipe(writableStream);
``` ```
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][15]** Invalid parameters
Returns **Sharp** Returns **Sharp**
@@ -96,7 +96,7 @@ contain an alpha channel, even when the input image does not.
**Parameters** **Parameters**
- `embed` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** A member of `sharp.gravity` to embed to an edge/corner. (optional, default `'centre'`) - `embed` **[String][13]** A member of `sharp.gravity` to embed to an edge/corner. (optional, default `'centre'`)
**Examples** **Examples**
@@ -115,7 +115,7 @@ sharp('input.gif')
}); });
``` ```
- Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Invalid parameters - Throws **[Error][15]** Invalid parameters
Returns **Sharp** Returns **Sharp**
@@ -163,11 +163,44 @@ Returns **Sharp**
Do not enlarge the output image if the input image width _or_ height are already less than the required dimensions. Do not enlarge the output image if the input image width _or_ height are already less than the required dimensions.
This is equivalent to GraphicsMagick's `>` geometry option: This is equivalent to GraphicsMagick's `>` geometry option:
"_change the dimensions of the image only if its width or height exceeds the geometry specification_". "_change the dimensions of the image only if its width or height exceeds the geometry specification_".
Use with `max()` to preserve the image's aspect ratio.
The default behaviour _before_ function call is `false`, meaning the image will be enlarged. The default behaviour _before_ function call is `false`, meaning the image will be enlarged.
**Parameters** **Parameters**
- `withoutEnlargement` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** (optional, default `true`) - `withoutEnlargement` **[Boolean][14]** (optional, default `true`)
Returns **Sharp** Returns **Sharp**
[1]: #resize
[2]: #crop
[3]: #embed
[4]: #max
[5]: #min
[6]: #ignoreaspectratio
[7]: #withoutenlargement
[8]: http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation
[9]: https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline
[10]: https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel
[11]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
[12]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[13]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[14]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[15]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error
[16]: https://en.wikipedia.org/wiki/Entropy_%28information_theory%29

View File

@@ -2,10 +2,10 @@
### Table of Contents ### Table of Contents
- [cache](#cache) - [cache][1]
- [concurrency](#concurrency) - [concurrency][2]
- [counters](#counters) - [counters][3]
- [simd](#simd) - [simd][4]
## cache ## cache
@@ -16,10 +16,10 @@ useful for determining how much working memory is required for a particular task
**Parameters** **Parameters**
- `options` **([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| [Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean))** Object with the following attributes, or Boolean where true uses default cache settings and false removes all caching (optional, default `true`) - `options` **([Object][5] \| [Boolean][6])** Object with the following attributes, or Boolean where true uses default cache settings and false removes all caching (optional, default `true`)
- `options.memory` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** is the maximum memory in MB to use for this cache (optional, default `50`) - `options.memory` **[Number][7]** is the maximum memory in MB to use for this cache (optional, default `50`)
- `options.files` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** is the maximum number of files to hold open (optional, default `20`) - `options.files` **[Number][7]** is the maximum number of files to hold open (optional, default `20`)
- `options.items` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** is the maximum number of operations to cache (optional, default `100`) - `options.items` **[Number][7]** is the maximum number of operations to cache (optional, default `100`)
**Examples** **Examples**
@@ -33,7 +33,7 @@ sharp.cache( { files: 0 } );
sharp.cache(false); sharp.cache(false);
``` ```
Returns **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** Returns **[Object][5]**
## concurrency ## concurrency
@@ -49,7 +49,7 @@ This method always returns the current concurrency.
**Parameters** **Parameters**
- `concurrency` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** - `concurrency` **[Number][7]?**
**Examples** **Examples**
@@ -59,7 +59,7 @@ sharp.concurrency(2); // 2
sharp.concurrency(0); // 4 sharp.concurrency(0); // 4
``` ```
Returns **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** concurrency Returns **[Number][7]** concurrency
## counters ## counters
@@ -74,7 +74,7 @@ Provides access to internal task counters.
const counters = sharp.counters(); // { queue: 2, process: 4 } const counters = sharp.counters(); // { queue: 2, process: 4 }
``` ```
Returns **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** Returns **[Object][5]**
## simd ## simd
@@ -89,7 +89,7 @@ Versions of liborc prior to 0.4.25 are known to segfault under heavy load.
**Parameters** **Parameters**
- `simd` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** (optional, default `false`) - `simd` **[Boolean][6]** (optional, default `false`)
**Examples** **Examples**
@@ -103,4 +103,18 @@ const simd = sharp.simd(true);
// attempts to enable the use of SIMD, returning true if available // attempts to enable the use of SIMD, returning true if available
``` ```
Returns **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Returns **[Boolean][6]**
[1]: #cache
[2]: #concurrency
[3]: #counters
[4]: #simd
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number

View File

@@ -1,9 +1,32 @@
# Changelog # Changelog
### v0.20 - "*prebuild*"
Requires libvips v8.6.1.
#### v0.20.0 - 5<sup>th</sup> March 2018
* Add support for prebuilt sharp binaries on common platforms.
[#186](https://github.com/lovell/sharp/issues/186)
### v0.19 - "*suit*" ### v0.19 - "*suit*"
Requires libvips v8.6.1. Requires libvips v8.6.1.
#### v0.19.1 - 24<sup>th</sup> February 2018
* Expose libvips' linear transform feature.
[#1024](https://github.com/lovell/sharp/pull/1024)
[@3epnm](https://github.com/3epnm)
* Expose angle option for tile-based output.
[#1121](https://github.com/lovell/sharp/pull/1121)
[@BiancoA](https://github.com/BiancoA)
* Prevent crop operation when image already at or below target dimensions.
[#1134](https://github.com/lovell/sharp/issues/1134)
[@pieh](https://github.com/pieh)
#### v0.19.0 - 11<sup>th</sup> January 2018 #### v0.19.0 - 11<sup>th</sup> January 2018
* Expose offset coordinates of strategy-based crop. * Expose offset coordinates of strategy-based crop.

View File

@@ -13,8 +13,9 @@ Lanczos resampling ensures quality is not sacrificed for speed.
As well as image resizing, operations such as As well as image resizing, operations such as
rotation, extraction, compositing and gamma correction are available. rotation, extraction, compositing and gamma correction are available.
OS X, Windows (x64), Linux (x64, ARM) systems do not require Most 64-bit OS X, Windows and Linux (glibc) systems running
the installation of any external runtime dependencies. Node versions 4, 6, 8 and 9
do not require any additional install or runtime dependencies.
[![Test Coverage](https://coveralls.io/repos/lovell/sharp/badge.png?branch=master)](https://coveralls.io/r/lovell/sharp?branch=master) [![Test Coverage](https://coveralls.io/repos/lovell/sharp/badge.png?branch=master)](https://coveralls.io/r/lovell/sharp?branch=master)
@@ -46,7 +47,7 @@ are held in memory and processed at a time,
taking full advantage of multiple CPU cores and L1/L2/L3 cache. taking full advantage of multiple CPU cores and L1/L2/L3 cache.
Everything remains non-blocking thanks to _libuv_, Everything remains non-blocking thanks to _libuv_,
no child processes are spawned and Promises/A+ are supported. no child processes are spawned and Promises/async/await are supported.
### Optimal ### Optimal
@@ -105,6 +106,9 @@ the help and code contributions of the following people:
* [Matthew McEachen](https://github.com/mceachen) * [Matthew McEachen](https://github.com/mceachen)
* [Jarda Kotěšovec](https://github.com/jardakotesovec) * [Jarda Kotěšovec](https://github.com/jardakotesovec)
* [Kenric D'Souza](https://github.com/AzureByte) * [Kenric D'Souza](https://github.com/AzureByte)
* [Oleh Aleinyk](https://github.com/oaleynik)
* [Marcel Bretschneider](https://github.com/3epnm)
* [Andrea Bianco](https://github.com/BiancoA)
Thank you! Thank you!

View File

@@ -8,12 +8,29 @@ npm install sharp
yarn add sharp yarn add sharp
``` ```
### Prerequisites ## Prerequisites
* Node v4.5.0+ * Node v4.5.0+
### Building from source
Pre-compiled binaries for sharp are provided for use with
Node versions 4, 6, 8 and 9 on
64-bit Windows, OS X and Linux platforms.
Sharp will be built from source at install time when:
* a globally-installed libvips is detected,
* pre-compiled binaries do not exist for the current platform and Node version, or
* when the `npm install --build-from-source` flag is used.
Building from source requires:
* C++11 compatible compiler such as gcc 4.8+, clang 3.0+ or MSVC 2013+ * C++11 compatible compiler such as gcc 4.8+, clang 3.0+ or MSVC 2013+
* [node-gyp](https://github.com/TooTallNate/node-gyp#installation) and its dependencies (includes Python) * [node-gyp](https://github.com/TooTallNate/node-gyp#installation) and its dependencies (includes Python)
## libvips
### Linux ### Linux
[![Ubuntu 16.04 Build Status](https://travis-ci.org/lovell/sharp.png?branch=master)](https://travis-ci.org/lovell/sharp) [![Ubuntu 16.04 Build Status](https://travis-ci.org/lovell/sharp.png?branch=master)](https://travis-ci.org/lovell/sharp)
@@ -23,14 +40,14 @@ This involves an automated HTTPS download of approximately 7MB.
Most recent Linux-based operating systems with glibc running on x64 and ARMv6+ CPUs should "just work", e.g.: Most recent Linux-based operating systems with glibc running on x64 and ARMv6+ CPUs should "just work", e.g.:
* Debian 7, 8 * Debian 7+
* Ubuntu 14.04, 16.04 * Ubuntu 14.04+
* Centos 7 * Centos 7+
* Fedora * Fedora
* openSUSE 13.2 * openSUSE 13.2+
* Archlinux * Archlinux
* Raspbian Jessie * Raspbian Jessie
* Amazon Linux 2017.03.1 * Amazon Linux
* Solus * Solus
To use a globally-installed version of libvips instead of the provided binaries, To use a globally-installed version of libvips instead of the provided binaries,
@@ -63,7 +80,7 @@ via `sharp.cache(false)` to avoid a stack overflow.
### Mac OS ### Mac OS
[![OS X 10.9.5 Build Status](https://travis-ci.org/lovell/sharp.png?branch=master)](https://travis-ci.org/lovell/sharp) [![OS X 10.12 Build Status](https://travis-ci.org/lovell/sharp.png?branch=master)](https://travis-ci.org/lovell/sharp)
libvips and its dependencies are fetched and stored within `node_modules/sharp/vendor` during `npm install`. libvips and its dependencies are fetched and stored within `node_modules/sharp/vendor` during `npm install`.
This involves an automated HTTPS download of approximately 7MB. This involves an automated HTTPS download of approximately 7MB.

34
install/dll-copy.js Normal file
View File

@@ -0,0 +1,34 @@
'use strict';
const fs = require('fs');
const path = require('path');
const copyFileSync = require('fs-copy-file-sync');
const npmLog = require('npmlog');
if (process.platform === 'win32') {
const buildDir = path.join(__dirname, '..', 'build');
const buildReleaseDir = path.join(buildDir, 'Release');
npmLog.info('sharp', `Creating ${buildReleaseDir}`);
try {
fs.mkdirSync(buildDir);
fs.mkdirSync(buildReleaseDir);
} catch (err) {}
const vendorLibDir = path.join(__dirname, '..', 'vendor', 'lib');
npmLog.info('sharp', `Copying DLLs from ${vendorLibDir} to ${buildReleaseDir}`);
try {
fs
.readdirSync(vendorLibDir)
.filter(function (filename) {
return /\.dll$/.test(filename);
})
.forEach(function (filename) {
copyFileSync(
path.join(vendorLibDir, filename),
path.join(buildReleaseDir, filename)
);
});
} catch (err) {
npmLog.error('sharp', err.message);
}
}

78
install/libvips.js Normal file
View File

@@ -0,0 +1,78 @@
'use strict';
const fs = require('fs');
const os = require('os');
const path = require('path');
const detectLibc = require('detect-libc');
const npmLog = require('npmlog');
const semver = require('semver');
const simpleGet = require('simple-get');
const tar = require('tar');
const agent = require('../lib/agent');
const libvips = require('../lib/libvips');
const platform = require('../lib/platform');
const minimumLibvipsVersion = libvips.minimumLibvipsVersion;
const distBaseUrl = process.env.SHARP_DIST_BASE_URL || `https://github.com/lovell/sharp-libvips/releases/download/v${minimumLibvipsVersion}/`;
try {
const globalLibvipsVersion = libvips.globalLibvipsVersion();
if (globalLibvipsVersion) {
npmLog.info('sharp', `Detected globally-installed libvips v${globalLibvipsVersion}`);
npmLog.info('sharp', 'Building from source via node-gyp');
process.exit(1);
} else if (libvips.hasVendoredLibvips()) {
npmLog.info('sharp', `Using existing vendored libvips v${minimumLibvipsVersion}`);
} else {
// Is this arch/platform supported?
const arch = process.env.npm_config_arch || process.arch;
if (arch === 'ia32') {
throw new Error(`Intel Architecture 32-bit systems require manual installation of libvips >= ${minimumLibvipsVersion}\n`);
}
if (detectLibc.isNonGlibcLinux) {
throw new Error(`Use with ${detectLibc.family} libc requires manual installation of libvips >= ${minimumLibvipsVersion}`);
}
if (detectLibc.family === detectLibc.GLIBC && detectLibc.version && semver.lt(`${detectLibc.version}.0`, '2.13.0')) {
throw new Error(`Use with glibc version ${detectLibc.version} requires manual installation of libvips >= ${minimumLibvipsVersion}`);
}
// Download to per-process temporary file
const tarFilename = ['libvips', minimumLibvipsVersion, platform()].join('-') + '.tar.gz';
const tarPathTemp = path.join(os.tmpdir(), `${process.pid}-${tarFilename}`);
const tmpFile = fs.createWriteStream(tarPathTemp);
const url = distBaseUrl + tarFilename;
npmLog.info('sharp', `Downloading ${url}`);
simpleGet({ url: url, agent: agent() }, function (err, response) {
if (err) {
throw err;
}
if (response.statusCode !== 200) {
throw new Error(`Status ${response.statusCode}`);
}
response.pipe(tmpFile);
});
tmpFile.on('close', function () {
const vendorPath = path.join(__dirname, '..', 'vendor');
fs.mkdirSync(vendorPath);
tar
.extract({
file: tarPathTemp,
cwd: vendorPath,
strict: true
})
.then(function () {
try {
fs.unlinkSync(tarPathTemp);
} catch (err) {}
})
.catch(function (err) {
throw err;
});
});
}
} catch (err) {
npmLog.error('sharp', err.message);
npmLog.error('sharp', 'Please see http://sharp.pixelplumbing.com/page/install');
process.exit(1);
}

View File

@@ -203,6 +203,8 @@ const Sharp = function (input, options) {
tiffYres: 1.0, tiffYres: 1.0,
tileSize: 256, tileSize: 256,
tileOverlap: 0, tileOverlap: 0,
linearA: 1,
linearB: 0,
// Function to notify of libvips warnings // Function to notify of libvips warnings
debuglog: debuglog, debuglog: debuglog,
// Function to notify of queue length changes // Function to notify of queue length changes

View File

@@ -171,8 +171,8 @@ function clone () {
* A Promises/A+ promise is returned when `callback` is not provided. * A Promises/A+ promise is returned when `callback` is not provided.
* *
* - `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg` * - `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg`
* - `width`: Number of pixels wide * - `width`: Number of pixels wide (EXIF orientation is not taken into consideration)
* - `height`: Number of pixels high * - `height`: Number of pixels high (EXIF orientation is not taken into consideration)
* - `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/jcupitt/libvips/blob/master/libvips/iofuncs/enumtypes.c#L636) * - `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/jcupitt/libvips/blob/master/libvips/iofuncs/enumtypes.c#L636)
* - `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK * - `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK
* - `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...](https://github.com/jcupitt/libvips/blob/master/libvips/iofuncs/enumtypes.c#L672) * - `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...](https://github.com/jcupitt/libvips/blob/master/libvips/iofuncs/enumtypes.c#L672)

59
lib/libvips.js Normal file
View File

@@ -0,0 +1,59 @@
'use strict';
const path = require('path');
const spawnSync = require('child_process').spawnSync;
const semver = require('semver');
const platform = require('./platform');
const minimumLibvipsVersion = process.env.npm_package_config_libvips || require('../package.json').config.libvips;
const spawnSyncOptions = {
encoding: 'utf8',
shell: true
};
const globalLibvipsVersion = function () {
if (process.platform !== 'win32') {
const globalLibvipsVersion = spawnSync(`PKG_CONFIG_PATH="${pkgConfigPath()}" pkg-config --modversion vips-cpp`, spawnSyncOptions).stdout || '';
return globalLibvipsVersion.trim();
} else {
return '';
}
};
const hasVendoredLibvips = function () {
const currentPlatformId = platform();
try {
const vendorPlatformId = require(path.join(__dirname, '..', 'vendor', 'platform.json'));
if (currentPlatformId === vendorPlatformId) {
return true;
} else {
throw new Error(`'${vendorPlatformId}' binaries cannot be used on the '${currentPlatformId}' platform. Please remove the 'node_modules/sharp/vendor' directory and run 'npm install'.`);
}
} catch (err) {}
return false;
};
const pkgConfigPath = function () {
if (process.platform !== 'win32') {
const brewPkgConfigPath = spawnSync('which brew >/dev/null 2>&1 && eval $(brew --env) && echo $PKG_CONFIG_LIBDIR', spawnSyncOptions).stdout || '';
return [brewPkgConfigPath.trim(), process.env.PKG_CONFIG_PATH, '/usr/local/lib/pkgconfig', '/usr/lib/pkgconfig']
.filter(function (p) { return !!p; })
.join(':');
} else {
return '';
}
};
const useGlobalLibvips = function () {
const globalVipsVersion = globalLibvipsVersion();
return !!globalVipsVersion && semver.gte(globalVipsVersion, minimumLibvipsVersion);
};
module.exports = {
minimumLibvipsVersion: minimumLibvipsVersion,
globalLibvipsVersion: globalLibvipsVersion,
hasVendoredLibvips: hasVendoredLibvips,
pkgConfigPath: pkgConfigPath,
useGlobalLibvips: useGlobalLibvips
};

View File

@@ -406,6 +406,33 @@ function boolean (operand, operator, options) {
return this; return this;
} }
/**
* Apply the linear formula a * input + b to the image (levels adjustment)
* @param {Number} [a=1.0] multiplier
* @param {Number} [b=0.0] offset
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
function linear (a, b) {
if (!is.defined(a)) {
this.options.linearA = 1.0;
} else if (is.number(a)) {
this.options.linearA = a;
} else {
throw new Error('Invalid linear transform multiplier ' + a);
}
if (!is.defined(b)) {
this.options.linearB = 0.0;
} else if (is.number(b)) {
this.options.linearB = b;
} else {
throw new Error('Invalid linear transform offset ' + b);
}
return this;
}
/** /**
* Decorate the Sharp prototype with operation-related functions. * Decorate the Sharp prototype with operation-related functions.
* @private * @private
@@ -427,7 +454,8 @@ module.exports = function (Sharp) {
normalize, normalize,
convolve, convolve,
threshold, threshold,
boolean boolean,
linear
].forEach(function (f) { ].forEach(function (f) {
Sharp.prototype[f.name] = f; Sharp.prototype[f.name] = f;
}); });

View File

@@ -319,6 +319,7 @@ function toFormat (format, options) {
* @param {Object} [tile] * @param {Object} [tile]
* @param {Number} [tile.size=256] tile size in pixels, a value between 1 and 8192. * @param {Number} [tile.size=256] tile size in pixels, a value between 1 and 8192.
* @param {Number} [tile.overlap=0] tile overlap in pixels, a value between 0 and 8192. * @param {Number} [tile.overlap=0] tile overlap in pixels, a value between 0 and 8192.
* @param {Number} [tile.angle=0] tile angle of rotation, must be a multiple of 90.
* @param {String} [tile.container='fs'] tile container, with value `fs` (filesystem) or `zip` (compressed file). * @param {String} [tile.container='fs'] tile container, with value `fs` (filesystem) or `zip` (compressed file).
* @param {String} [tile.layout='dz'] filesystem layout, possible values are `dz`, `zoomify` or `google`. * @param {String} [tile.layout='dz'] filesystem layout, possible values are `dz`, `zoomify` or `google`.
* @returns {Sharp} * @returns {Sharp}
@@ -361,6 +362,15 @@ function tile (tile) {
throw new Error('Invalid tile layout ' + tile.layout); throw new Error('Invalid tile layout ' + tile.layout);
} }
} }
// Angle of rotation,
if (is.defined(tile.angle)) {
if (is.integer(tile.angle) && !(tile.angle % 90)) {
this.options.tileAngle = tile.angle;
} else {
throw new Error('Unsupported angle: angle must be a positive/negative multiple of 90 ' + tile.angle);
}
}
} }
// Format // Format
if (is.inArray(this.options.formatOut, ['jpeg', 'png', 'webp'])) { if (is.inArray(this.options.formatOut, ['jpeg', 'png', 'webp'])) {
@@ -368,6 +378,7 @@ function tile (tile) {
} else if (this.options.formatOut !== 'input') { } else if (this.options.formatOut !== 'input') {
throw new Error('Invalid tile format ' + this.options.formatOut); throw new Error('Invalid tile format ' + this.options.formatOut);
} }
return this._updateFormatOut('dz'); return this._updateFormatOut('dz');
} }

View File

@@ -253,6 +253,7 @@ function ignoreAspectRatio () {
* Do not enlarge the output image if the input image width *or* height are already less than the required dimensions. * Do not enlarge the output image if the input image width *or* height are already less than the required dimensions.
* This is equivalent to GraphicsMagick's `>` geometry option: * This is equivalent to GraphicsMagick's `>` geometry option:
* "*change the dimensions of the image only if its width or height exceeds the geometry specification*". * "*change the dimensions of the image only if its width or height exceeds the geometry specification*".
* Use with `max()` to preserve the image's aspect ratio.
* *
* The default behaviour *before* function call is `false`, meaning the image will be enlarged. * The default behaviour *before* function call is `false`, meaning the image will be enlarged.
* *

View File

@@ -1,7 +1,7 @@
{ {
"name": "sharp", "name": "sharp",
"description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP and TIFF images", "description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP and TIFF images",
"version": "0.19.0", "version": "0.20.0",
"author": "Lovell Fuller <npm@lovell.info>", "author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://github.com/lovell/sharp", "homepage": "https://github.com/lovell/sharp",
"contributors": [ "contributors": [
@@ -39,14 +39,18 @@
"Guy Maliar <guy@tailorbrands.com>", "Guy Maliar <guy@tailorbrands.com>",
"Nicolas Coden <nicolas@ncoden.fr>", "Nicolas Coden <nicolas@ncoden.fr>",
"Matt Parrish <matt.r.parrish@gmail.com>", "Matt Parrish <matt.r.parrish@gmail.com>",
"Marcel Bretschneider <marcel.bretschneider@gmail.com>",
"Matthew McEachen <matthew+github@mceachen.org>", "Matthew McEachen <matthew+github@mceachen.org>",
"Jarda Kotěšovec <jarda.kotesovec@gmail.com>", "Jarda Kotěšovec <jarda.kotesovec@gmail.com>",
"Kenric D'Souza <kenric.dsouza@gmail.com>", "Kenric D'Souza <kenric.dsouza@gmail.com>",
"Oleh Aleinyk <oleg.aleynik@gmail.com>" "Oleh Aleinyk <oleg.aleynik@gmail.com>",
"Marcel Bretschneider <marcel.bretschneider@gmail.com>",
"Andrea Bianco <andrea.bianco@unibas.ch>"
], ],
"scripts": { "scripts": {
"install": "(node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)",
"clean": "rm -rf node_modules/ build/ vendor/ coverage/ test/fixtures/output.*", "clean": "rm -rf node_modules/ build/ vendor/ coverage/ test/fixtures/output.*",
"test": "semistandard && cc && nyc --reporter=lcov --branches=99 mocha --slow=5000 --timeout=60000 ./test/unit/*.js", "test": "semistandard && cc && nyc --reporter=lcov --branches=99 mocha --slow=5000 --timeout=60000 ./test/unit/*.js && prebuild-ci",
"coverage": "./test/coverage/report.sh", "coverage": "./test/coverage/report.sh",
"test-leak": "./test/leak/leak.sh", "test-leak": "./test/leak/leak.sh",
"docs": "for m in constructor input resize composite operation colour channel output utility; do documentation build --shallow --format=md lib/$m.js >docs/api-$m.md; done" "docs": "for m in constructor input resize composite operation colour channel output utility; do documentation build --shallow --format=md lib/$m.js >docs/api-$m.md; done"
@@ -73,24 +77,29 @@
"vips" "vips"
], ],
"dependencies": { "dependencies": {
"color": "^2.0.1", "color": "^3.0.0",
"detect-libc": "^1.0.3", "detect-libc": "^1.0.3",
"nan": "^2.8.0", "nan": "^2.9.2",
"semver": "^5.4.1", "fs-copy-file-sync": "^1.0.1",
"npmlog": "^4.1.2",
"prebuild-install": "^2.5.1",
"semver": "^5.5.0",
"simple-get": "^2.7.0", "simple-get": "^2.7.0",
"tar": "^4.2.0", "tar": "^4.4.0",
"tunnel-agent": "^0.6.0" "tunnel-agent": "^0.6.0"
}, },
"devDependencies": { "devDependencies": {
"async": "^2.6.0", "async": "^2.6.0",
"cc": "^1.0.1", "cc": "^1.0.1",
"documentation": "^5.3.5", "documentation": "^6.0.0",
"exif-reader": "^1.0.2", "exif-reader": "^1.0.2",
"icc": "^1.0.0", "icc": "^1.0.0",
"mocha": "^4.1.0", "mocha": "^5.0.1",
"nyc": "^11.4.1", "nyc": "^11.5.0",
"prebuild": "^7.4.0",
"prebuild-ci": "^2.2.3",
"rimraf": "^2.6.2", "rimraf": "^2.6.2",
"semistandard": "^12.0.0", "semistandard": "^12.0.1",
"unzip": "^0.1.11" "unzip": "^0.1.11"
}, },
"license": "Apache-2.0", "license": "Apache-2.0",

View File

@@ -27,7 +27,8 @@ class MetadataWorker : public Nan::AsyncWorker {
MetadataWorker( MetadataWorker(
Nan::Callback *callback, MetadataBaton *baton, Nan::Callback *debuglog, Nan::Callback *callback, MetadataBaton *baton, Nan::Callback *debuglog,
std::vector<v8::Local<v8::Object>> const buffersToPersist) : std::vector<v8::Local<v8::Object>> const buffersToPersist) :
Nan::AsyncWorker(callback), baton(baton), debuglog(debuglog), Nan::AsyncWorker(callback, "sharp:MetadataWorker"),
baton(baton), debuglog(debuglog),
buffersToPersist(buffersToPersist) { buffersToPersist(buffersToPersist) {
// Protect Buffer objects from GC, keyed on index // Protect Buffer objects from GC, keyed on index
std::accumulate(buffersToPersist.begin(), buffersToPersist.end(), 0, std::accumulate(buffersToPersist.begin(), buffersToPersist.end(), 0,
@@ -165,12 +166,12 @@ class MetadataWorker : public Nan::AsyncWorker {
std::string warning = sharp::VipsWarningPop(); std::string warning = sharp::VipsWarningPop();
while (!warning.empty()) { while (!warning.empty()) {
v8::Local<v8::Value> message[1] = { New(warning).ToLocalChecked() }; v8::Local<v8::Value> message[1] = { New(warning).ToLocalChecked() };
debuglog->Call(1, message); debuglog->Call(1, message, async_resource);
warning = sharp::VipsWarningPop(); warning = sharp::VipsWarningPop();
} }
// Return to JavaScript // Return to JavaScript
callback->Call(2, argv); callback->Call(2, argv, async_resource);
} }
private: private:

View File

@@ -341,4 +341,18 @@ namespace sharp {
return image.extract_area(left, top, width, height); return image.extract_area(left, top, width, height);
} }
/*
* Calculate (a * in + b)
*/
VImage Linear(VImage image, double const a, double const b) {
if (HasAlpha(image)) {
// Separate alpha channel
VImage imageWithoutAlpha = image.extract_band(0,
VImage::option()->set("n", image.bands() - 1));
VImage alpha = image[image.bands() - 1];
return imageWithoutAlpha.linear(a, b).bandjoin(alpha);
} else {
return image.linear(a, b);
}
}
} // namespace sharp } // namespace sharp

View File

@@ -92,6 +92,11 @@ namespace sharp {
*/ */
VImage Trim(VImage image, int const tolerance); VImage Trim(VImage image, int const tolerance);
/*
* Linear adjustment (a * in + b)
*/
VImage Linear(VImage image, double const a, double const b);
} // namespace sharp } // namespace sharp
#endif // SRC_OPERATIONS_H_ #endif // SRC_OPERATIONS_H_

View File

@@ -35,7 +35,8 @@ class PipelineWorker : public Nan::AsyncWorker {
PipelineWorker( PipelineWorker(
Nan::Callback *callback, PipelineBaton *baton, Nan::Callback *debuglog, Nan::Callback *queueListener, Nan::Callback *callback, PipelineBaton *baton, Nan::Callback *debuglog, Nan::Callback *queueListener,
std::vector<v8::Local<v8::Object>> const buffersToPersist) : std::vector<v8::Local<v8::Object>> const buffersToPersist) :
Nan::AsyncWorker(callback), baton(baton), debuglog(debuglog), queueListener(queueListener), Nan::AsyncWorker(callback, "sharp:PipelineWorker"),
baton(baton), debuglog(debuglog), queueListener(queueListener),
buffersToPersist(buffersToPersist) { buffersToPersist(buffersToPersist) {
// Protect Buffer objects from GC, keyed on index // Protect Buffer objects from GC, keyed on index
std::accumulate(buffersToPersist.begin(), buffersToPersist.end(), 0, std::accumulate(buffersToPersist.begin(), buffersToPersist.end(), 0,
@@ -465,7 +466,10 @@ class PipelineWorker : public Nan::AsyncWorker {
->set("extend", VIPS_EXTEND_BACKGROUND) ->set("extend", VIPS_EXTEND_BACKGROUND)
->set("background", background)); ->set("background", background));
} else if (baton->canvas != Canvas::IGNORE_ASPECT) { } else if (
baton->canvas != Canvas::IGNORE_ASPECT &&
(image.width() > baton->width || image.height() > baton->height)
) {
// Crop/max/min // Crop/max/min
if (baton->crop < 9) { if (baton->crop < 9) {
// Gravity-based crop // Gravity-based crop
@@ -644,6 +648,11 @@ class PipelineWorker : public Nan::AsyncWorker {
image = sharp::Gamma(image, baton->gamma); image = sharp::Gamma(image, baton->gamma);
} }
// Linear adjustment (a * in + b)
if (baton->linearA != 1.0 || baton->linearB != 0.0) {
image = sharp::Linear(image, baton->linearA, baton->linearB);
}
// Apply normalisation - stretch luminance to cover full dynamic range // Apply normalisation - stretch luminance to cover full dynamic range
if (baton->normalise) { if (baton->normalise) {
image = sharp::Normalise(image); image = sharp::Normalise(image);
@@ -912,7 +921,8 @@ class PipelineWorker : public Nan::AsyncWorker {
->set("overlap", baton->tileOverlap) ->set("overlap", baton->tileOverlap)
->set("container", baton->tileContainer) ->set("container", baton->tileContainer)
->set("layout", baton->tileLayout) ->set("layout", baton->tileLayout)
->set("suffix", const_cast<char*>(suffix.data()))); ->set("suffix", const_cast<char*>(suffix.data()))
->set("angle", CalculateAngleRotation(baton->tileAngle)));
baton->formatOut = "dz"; baton->formatOut = "dz";
} else if (baton->formatOut == "v" || (mightMatchInput && isV) || } else if (baton->formatOut == "v" || (mightMatchInput && isV) ||
(willMatchInput && inputImageType == ImageType::VIPS)) { (willMatchInput && inputImageType == ImageType::VIPS)) {
@@ -1005,18 +1015,18 @@ class PipelineWorker : public Nan::AsyncWorker {
std::string warning = sharp::VipsWarningPop(); std::string warning = sharp::VipsWarningPop();
while (!warning.empty()) { while (!warning.empty()) {
v8::Local<v8::Value> message[1] = { New(warning).ToLocalChecked() }; v8::Local<v8::Value> message[1] = { New(warning).ToLocalChecked() };
debuglog->Call(1, message); debuglog->Call(1, message, async_resource);
warning = sharp::VipsWarningPop(); warning = sharp::VipsWarningPop();
} }
// Decrement processing task counter // Decrement processing task counter
g_atomic_int_dec_and_test(&sharp::counterProcess); g_atomic_int_dec_and_test(&sharp::counterProcess);
v8::Local<v8::Value> queueLength[1] = { New<v8::Uint32>(sharp::counterQueue) }; v8::Local<v8::Value> queueLength[1] = { New<v8::Uint32>(sharp::counterQueue) };
queueListener->Call(1, queueLength); queueListener->Call(1, queueLength, async_resource);
delete queueListener; delete queueListener;
// Return to JavaScript // Return to JavaScript
callback->Call(3, argv); callback->Call(3, argv, async_resource);
} }
private: private:
@@ -1185,6 +1195,8 @@ NAN_METHOD(pipeline) {
baton->thresholdGrayscale = AttrTo<bool>(options, "thresholdGrayscale"); baton->thresholdGrayscale = AttrTo<bool>(options, "thresholdGrayscale");
baton->trimTolerance = AttrTo<int32_t>(options, "trimTolerance"); baton->trimTolerance = AttrTo<int32_t>(options, "trimTolerance");
baton->gamma = AttrTo<double>(options, "gamma"); baton->gamma = AttrTo<double>(options, "gamma");
baton->linearA = AttrTo<double>(options, "linearA");
baton->linearB = AttrTo<double>(options, "linearB");
baton->greyscale = AttrTo<bool>(options, "greyscale"); baton->greyscale = AttrTo<bool>(options, "greyscale");
baton->normalise = AttrTo<bool>(options, "normalise"); baton->normalise = AttrTo<bool>(options, "normalise");
baton->useExifOrientation = AttrTo<bool>(options, "useExifOrientation"); baton->useExifOrientation = AttrTo<bool>(options, "useExifOrientation");
@@ -1256,6 +1268,7 @@ NAN_METHOD(pipeline) {
baton->tileSize = AttrTo<uint32_t>(options, "tileSize"); baton->tileSize = AttrTo<uint32_t>(options, "tileSize");
baton->tileOverlap = AttrTo<uint32_t>(options, "tileOverlap"); baton->tileOverlap = AttrTo<uint32_t>(options, "tileOverlap");
std::string tileContainer = AttrAsStr(options, "tileContainer"); std::string tileContainer = AttrAsStr(options, "tileContainer");
baton->tileAngle = AttrTo<int32_t>(options, "tileAngle");
if (tileContainer == "zip") { if (tileContainer == "zip") {
baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP; baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP;
} else { } else {
@@ -1290,5 +1303,6 @@ NAN_METHOD(pipeline) {
// Increment queued task counter // Increment queued task counter
g_atomic_int_inc(&sharp::counterQueue); g_atomic_int_inc(&sharp::counterQueue);
v8::Local<v8::Value> queueLength[1] = { Nan::New<v8::Uint32>(sharp::counterQueue) }; v8::Local<v8::Value> queueLength[1] = { Nan::New<v8::Uint32>(sharp::counterQueue) };
queueListener->Call(1, queueLength); v8::Local<v8::Object> recv = Nan::New<v8::Object>();
Nan::Call(*queueListener, recv, 1, queueLength);
} }

View File

@@ -79,6 +79,8 @@ struct PipelineBaton {
int threshold; int threshold;
bool thresholdGrayscale; bool thresholdGrayscale;
int trimTolerance; int trimTolerance;
double linearA;
double linearB;
double gamma; double gamma;
bool greyscale; bool greyscale;
bool normalise; bool normalise;
@@ -130,6 +132,7 @@ struct PipelineBaton {
VipsForeignDzContainer tileContainer; VipsForeignDzContainer tileContainer;
VipsForeignDzLayout tileLayout; VipsForeignDzLayout tileLayout;
std::string tileFormat; std::string tileFormat;
int tileAngle;
PipelineBaton(): PipelineBaton():
input(nullptr), input(nullptr),
@@ -160,6 +163,8 @@ struct PipelineBaton {
threshold(0), threshold(0),
thresholdGrayscale(true), thresholdGrayscale(true),
trimTolerance(0), trimTolerance(0),
linearA(1.0),
linearB(0.0),
gamma(0.0), gamma(0.0),
greyscale(false), greyscale(false),
normalise(false), normalise(false),
@@ -202,7 +207,8 @@ struct PipelineBaton {
tileSize(256), tileSize(256),
tileOverlap(0), tileOverlap(0),
tileContainer(VIPS_FOREIGN_DZ_CONTAINER_FS), tileContainer(VIPS_FOREIGN_DZ_CONTAINER_FS),
tileLayout(VIPS_FOREIGN_DZ_LAYOUT_DZ) { tileLayout(VIPS_FOREIGN_DZ_LAYOUT_DZ),
tileAngle(0){
background[0] = 0.0; background[0] = 0.0;
background[1] = 0.0; background[1] = 0.0;
background[2] = 0.0; background[2] = 0.0;

View File

@@ -28,7 +28,8 @@ class StatsWorker : public Nan::AsyncWorker {
StatsWorker( StatsWorker(
Nan::Callback *callback, StatsBaton *baton, Nan::Callback *debuglog, Nan::Callback *callback, StatsBaton *baton, Nan::Callback *debuglog,
std::vector<v8::Local<v8::Object>> const buffersToPersist) : std::vector<v8::Local<v8::Object>> const buffersToPersist) :
Nan::AsyncWorker(callback), baton(baton), debuglog(debuglog), Nan::AsyncWorker(callback, "sharp:StatsWorker"),
baton(baton), debuglog(debuglog),
buffersToPersist(buffersToPersist) { buffersToPersist(buffersToPersist) {
// Protect Buffer objects from GC, keyed on index // Protect Buffer objects from GC, keyed on index
std::accumulate(buffersToPersist.begin(), buffersToPersist.end(), 0, std::accumulate(buffersToPersist.begin(), buffersToPersist.end(), 0,
@@ -145,12 +146,12 @@ class StatsWorker : public Nan::AsyncWorker {
std::string warning = sharp::VipsWarningPop(); std::string warning = sharp::VipsWarningPop();
while (!warning.empty()) { while (!warning.empty()) {
v8::Local<v8::Value> message[1] = { New(warning).ToLocalChecked() }; v8::Local<v8::Value> message[1] = { New(warning).ToLocalChecked() };
debuglog->Call(1, message); debuglog->Call(1, message, async_resource);
warning = sharp::VipsWarningPop(); warning = sharp::VipsWarningPop();
} }
// Return to JavaScript // Return to JavaScript
callback->Call(2, argv); callback->Call(2, argv, async_resource);
} }
private: private:

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 179 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

View File

@@ -159,6 +159,24 @@ describe('Crop', function () {
}); });
}); });
it('Skip crop when post-resize dimensions are at or below target dimensions', function () {
return sharp(fixtures.inputJpg)
.resize(1600, 1200)
.toBuffer()
.then(function (input) {
return sharp(input)
.resize(1110)
.crop(sharp.strategy.attention)
.toBuffer({ resolveWithObject: true })
.then(function (result) {
assert.strictEqual(1110, result.info.width);
assert.strictEqual(832, result.info.height);
assert.strictEqual(undefined, result.info.cropOffsetLeft);
assert.strictEqual(undefined, result.info.cropOffsetTop);
});
});
});
describe('Entropy-based strategy', function () { describe('Entropy-based strategy', function () {
it('JPEG', function (done) { it('JPEG', function (done) {
sharp(fixtures.inputJpg) sharp(fixtures.inputJpg)

62
test/unit/libvips.js Normal file
View File

@@ -0,0 +1,62 @@
'use strict';
const assert = require('assert');
const semver = require('semver');
const libvips = require('../../lib/libvips');
const originalPlatform = process.platform;
const setPlatform = function (platform) {
Object.defineProperty(process, 'platform', { value: platform });
};
const restorePlatform = function () {
setPlatform(originalPlatform);
};
describe('libvips binaries', function () {
describe('Windows platform', function () {
before(function () { setPlatform('win32'); });
after(restorePlatform);
it('pkgConfigPath returns empty string', function () {
assert.strictEqual('', libvips.pkgConfigPath());
});
it('globalLibvipsVersion returns empty string', function () {
assert.strictEqual('', libvips.globalLibvipsVersion());
});
it('globalLibvipsVersion is always false', function () {
assert.strictEqual(false, libvips.useGlobalLibvips());
});
});
describe('non-Windows platforms', function () {
before(function () { setPlatform('linux'); });
after(restorePlatform);
it('pkgConfigPath returns a string', function () {
const pkgConfigPath = libvips.pkgConfigPath();
assert.strictEqual('string', typeof pkgConfigPath);
});
it('globalLibvipsVersion returns a string', function () {
const globalLibvipsVersion = libvips.globalLibvipsVersion();
assert.strictEqual('string', typeof globalLibvipsVersion);
});
it('globalLibvipsVersion returns a boolean', function () {
const useGlobalLibvips = libvips.useGlobalLibvips();
assert.strictEqual('boolean', typeof useGlobalLibvips);
});
});
describe('platform agnostic', function () {
it('minimumLibvipsVersion returns a valid semver', function () {
const minimumLibvipsVersion = libvips.minimumLibvipsVersion;
assert.strictEqual('string', typeof minimumLibvipsVersion);
assert.notStrictEqual(null, semver.valid(minimumLibvipsVersion));
});
it('hasVendoredLibvips returns a boolean', function () {
const hasVendoredLibvips = libvips.hasVendoredLibvips();
assert.strictEqual('boolean', typeof hasVendoredLibvips);
});
});
});

79
test/unit/linear.js Normal file
View File

@@ -0,0 +1,79 @@
'use strict';
const sharp = require('../../');
const fixtures = require('../fixtures');
const assert = require('assert');
describe('Linear adjustment', function () {
const blackPoint = 70;
const whitePoint = 203;
const a = 255 / (whitePoint - blackPoint);
const b = -blackPoint * a;
it('applies linear levels adjustment w/o alpha ch', function (done) {
sharp(fixtures.inputJpgWithLowContrast)
.linear(a, b)
.toBuffer(function (err, data, info) {
if (err) throw err;
fixtures.assertSimilar(fixtures.expected('low-contrast-linear.jpg'), data, done);
});
});
it('applies slope level adjustment w/o alpha ch', function (done) {
sharp(fixtures.inputJpgWithLowContrast)
.linear(a)
.toBuffer(function (err, data, info) {
if (err) throw err;
fixtures.assertSimilar(fixtures.expected('low-contrast-slope.jpg'), data, done);
});
});
it('applies offset level adjustment w/o alpha ch', function (done) {
sharp(fixtures.inputJpgWithLowContrast)
.linear(null, b)
.toBuffer(function (err, data, info) {
if (err) throw err;
fixtures.assertSimilar(fixtures.expected('low-contrast-offset.jpg'), data, done);
});
});
it('applies linear levels adjustment w alpha ch', function (done) {
sharp(fixtures.inputPngOverlayLayer1)
.linear(a, b)
.toBuffer(function (err, data, info) {
if (err) throw err;
fixtures.assertSimilar(fixtures.expected('alpha-layer-1-fill-linear.png'), data, done);
});
});
it('applies slope level adjustment w alpha ch', function (done) {
sharp(fixtures.inputPngOverlayLayer1)
.linear(a)
.toBuffer(function (err, data, info) {
if (err) throw err;
fixtures.assertSimilar(fixtures.expected('alpha-layer-1-fill-slope.png'), data, done);
});
});
it('applies offset level adjustment w alpha ch', function (done) {
sharp(fixtures.inputPngOverlayLayer1)
.linear(null, b)
.toBuffer(function (err, data, info) {
if (err) throw err;
fixtures.assertSimilar(fixtures.expected('alpha-layer-1-fill-offset.png'), data, done);
});
});
it('Invalid linear arguments', function () {
assert.throws(function () {
sharp(fixtures.inputPngOverlayLayer1)
.linear('foo');
});
assert.throws(function () {
sharp(fixtures.inputPngOverlayLayer1)
.linear(undefined, { 'bar': 'baz' });
});
});
});

View File

@@ -146,13 +146,38 @@ describe('Tile', function () {
it('Prevent larger overlap than default size', function () { it('Prevent larger overlap than default size', function () {
assert.throws(function () { assert.throws(function () {
sharp().tile({overlap: 257}); sharp().tile({
overlap: 257
});
}); });
}); });
it('Prevent larger overlap than provided size', function () { it('Prevent larger overlap than provided size', function () {
assert.throws(function () { assert.throws(function () {
sharp().tile({size: 512, overlap: 513}); sharp().tile({
size: 512,
overlap: 513
});
});
});
it('Valid rotation angle values pass', function () {
[90, 270, -90].forEach(function (angle) {
assert.doesNotThrow(function () {
sharp().tile({
angle: angle
});
});
});
});
it('Invalid rotation angle values fail', function () {
['zoinks', 1.1, -1, 27].forEach(function (angle) {
assert.throws(function () {
sharp().tile({
angle: angle
});
});
}); });
}); });
@@ -192,6 +217,40 @@ describe('Tile', function () {
}); });
}); });
it('Deep Zoom layout with custom size+angle', function (done) {
const directory = fixtures.path('output.512_90.dzi_files');
rimraf(directory, function () {
sharp(fixtures.inputJpg)
.tile({
size: 512,
angle: 90
})
.toFile(fixtures.path('output.512_90.dzi'), function (err, info) {
if (err) throw err;
assert.strictEqual('dz', info.format);
assert.strictEqual(2725, info.width);
assert.strictEqual(2225, info.height);
assert.strictEqual(3, info.channels);
assert.strictEqual('undefined', typeof info.size);
assertDeepZoomTiles(directory, 512, 13, done);
// Verifies tiles in 10th level are rotated
let tile = path.join(directory, '10', '0_1.jpeg');
// verify that the width and height correspond to the rotated image
// expected are w=512 and h=170 for the 0_1.jpeg.
// if a 0 angle is supplied to the .tile function
// the expected values are w=170 and h=512 for the 1_0.jpeg
sharp(tile).metadata(function (err, metadata) {
if (err) {
throw err;
} else {
assert.strictEqual(true, metadata.width === 512);
assert.strictEqual(true, metadata.height === 170);
}
});
});
});
});
it('Zoomify layout', function (done) { it('Zoomify layout', function (done) {
const directory = fixtures.path('output.zoomify.dzi'); const directory = fixtures.path('output.zoomify.dzi');
rimraf(directory, function () { rimraf(directory, function () {
@@ -244,7 +303,9 @@ describe('Tile', function () {
const directory = fixtures.path('output.jpg.google.dzi'); const directory = fixtures.path('output.jpg.google.dzi');
rimraf(directory, function () { rimraf(directory, function () {
sharp(fixtures.inputJpg) sharp(fixtures.inputJpg)
.jpeg({ quality: 1 }) .jpeg({
quality: 1
})
.tile({ .tile({
layout: 'google' layout: 'google'
}) })
@@ -279,7 +340,9 @@ describe('Tile', function () {
const directory = fixtures.path('output.png.google.dzi'); const directory = fixtures.path('output.png.google.dzi');
rimraf(directory, function () { rimraf(directory, function () {
sharp(fixtures.inputJpg) sharp(fixtures.inputJpg)
.png({ compressionLevel: 1 }) .png({
compressionLevel: 1
})
.tile({ .tile({
layout: 'google' layout: 'google'
}) })
@@ -314,7 +377,9 @@ describe('Tile', function () {
const directory = fixtures.path('output.webp.google.dzi'); const directory = fixtures.path('output.webp.google.dzi');
rimraf(directory, function () { rimraf(directory, function () {
sharp(fixtures.inputJpg) sharp(fixtures.inputJpg)
.webp({ quality: 1 }) .webp({
quality: 1
})
.tile({ .tile({
layout: 'google' layout: 'google'
}) })
@@ -363,8 +428,12 @@ describe('Tile', function () {
assert.strictEqual(true, stat.isFile()); assert.strictEqual(true, stat.isFile());
assert.strictEqual(true, stat.size > 0); assert.strictEqual(true, stat.size > 0);
fs.createReadStream(container) fs.createReadStream(container)
.pipe(unzip.Extract({path: path.dirname(extractTo)})) .pipe(unzip.Extract({
.on('error', function (err) { throw err; }) path: path.dirname(extractTo)
}))
.on('error', function (err) {
throw err;
})
.on('close', function () { .on('close', function () {
assertDeepZoomTiles(directory, 256, 13, done); assertDeepZoomTiles(directory, 256, 13, done);
}); });
@@ -395,8 +464,12 @@ describe('Tile', function () {
assert.strictEqual(true, stat.isFile()); assert.strictEqual(true, stat.isFile());
assert.strictEqual(true, stat.size > 0); assert.strictEqual(true, stat.size > 0);
fs.createReadStream(container) fs.createReadStream(container)
.pipe(unzip.Extract({path: path.dirname(extractTo)})) .pipe(unzip.Extract({
.on('error', function (err) { throw err; }) path: path.dirname(extractTo)
}))
.on('error', function (err) {
throw err;
})
.on('close', function () { .on('close', function () {
assertDeepZoomTiles(directory, 256, 13, done); assertDeepZoomTiles(directory, 256, 13, done);
}); });