Comparing version 0.27.2 to 0.32.6
@@ -0,1 +1,4 @@ | ||
// Copyright 2013 Lovell Fuller and others. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
'use strict'; | ||
@@ -7,17 +10,16 @@ | ||
const libvips = require('../lib/libvips'); | ||
const npmLog = require('npmlog'); | ||
const platform = require('../lib/platform'); | ||
const minimumLibvipsVersion = libvips.minimumLibvipsVersion; | ||
const platform = process.env.npm_config_platform || process.platform; | ||
if (platform === 'win32') { | ||
const buildDir = path.join(__dirname, '..', 'build'); | ||
const buildReleaseDir = path.join(buildDir, 'Release'); | ||
npmLog.info('sharp', `Creating ${buildReleaseDir}`); | ||
const platformAndArch = platform(); | ||
if (platformAndArch.startsWith('win32')) { | ||
const buildReleaseDir = path.join(__dirname, '..', 'build', 'Release'); | ||
libvips.log(`Creating ${buildReleaseDir}`); | ||
try { | ||
libvips.mkdirSync(buildDir); | ||
libvips.mkdirSync(buildReleaseDir); | ||
} catch (err) {} | ||
const vendorLibDir = path.join(__dirname, '..', 'vendor', minimumLibvipsVersion, 'lib'); | ||
npmLog.info('sharp', `Copying DLLs from ${vendorLibDir} to ${buildReleaseDir}`); | ||
const vendorLibDir = path.join(__dirname, '..', 'vendor', minimumLibvipsVersion, platformAndArch, 'lib'); | ||
libvips.log(`Copying DLLs from ${vendorLibDir} to ${buildReleaseDir}`); | ||
try { | ||
@@ -36,4 +38,5 @@ fs | ||
} catch (err) { | ||
npmLog.error('sharp', err.message); | ||
libvips.log(err); | ||
process.exit(1); | ||
} | ||
} |
@@ -0,1 +1,4 @@ | ||
// Copyright 2013 Lovell Fuller and others. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
'use strict'; | ||
@@ -8,6 +11,8 @@ | ||
const zlib = require('zlib'); | ||
const { createHash } = require('crypto'); | ||
const detectLibc = require('detect-libc'); | ||
const npmLog = require('npmlog'); | ||
const semver = require('semver'); | ||
const semverCoerce = require('semver/functions/coerce'); | ||
const semverLessThan = require('semver/functions/lt'); | ||
const semverSatisfies = require('semver/functions/satisfies'); | ||
const simpleGet = require('simple-get'); | ||
@@ -22,34 +27,91 @@ const tarFs = require('tar-fs'); | ||
arm: '2.28', | ||
arm64: '2.29', | ||
arm64: '2.17', | ||
x64: '2.17' | ||
}; | ||
const hasSharpPrebuild = [ | ||
'darwin-x64', | ||
'darwin-arm64', | ||
'linux-arm64', | ||
'linux-x64', | ||
'linuxmusl-x64', | ||
'linuxmusl-arm64', | ||
'win32-ia32', | ||
'win32-x64' | ||
]; | ||
const { minimumLibvipsVersion, minimumLibvipsVersionLabelled } = libvips; | ||
const localLibvipsDir = process.env.npm_config_sharp_libvips_local_prebuilds || ''; | ||
const distHost = process.env.npm_config_sharp_libvips_binary_host || 'https://github.com/lovell/sharp-libvips/releases/download'; | ||
const distBaseUrl = process.env.npm_config_sharp_dist_base_url || process.env.SHARP_DIST_BASE_URL || `${distHost}/v${minimumLibvipsVersionLabelled}/`; | ||
const supportsBrotli = ('BrotliDecompress' in zlib); | ||
const installationForced = !!(process.env.npm_config_sharp_install_force || process.env.SHARP_INSTALL_FORCE); | ||
const fail = function (err) { | ||
npmLog.error('sharp', err.message); | ||
libvips.log(err); | ||
if (err.code === 'EACCES') { | ||
npmLog.info('sharp', 'Are you trying to install as a root or sudo user? Try again with the --unsafe-perm flag'); | ||
libvips.log('Are you trying to install as a root or sudo user?'); | ||
libvips.log('- For npm <= v6, try again with the "--unsafe-perm" flag'); | ||
libvips.log('- For npm >= v8, the user must own the directory "npm install" is run in'); | ||
} | ||
npmLog.info('sharp', 'Attempting to build from source via node-gyp but this may fail due to the above error'); | ||
npmLog.info('sharp', 'Please see https://sharp.pixelplumbing.com/install for required dependencies'); | ||
libvips.log('Please see https://sharp.pixelplumbing.com/install for required dependencies'); | ||
process.exit(1); | ||
}; | ||
const extractTarball = function (tarPath) { | ||
const vendorPath = path.join(__dirname, '..', 'vendor'); | ||
libvips.mkdirSync(vendorPath); | ||
const versionedVendorPath = path.join(vendorPath, minimumLibvipsVersion); | ||
const handleError = function (err) { | ||
if (installationForced) { | ||
libvips.log(`Installation warning: ${err.message}`); | ||
} else { | ||
throw err; | ||
} | ||
}; | ||
const verifyIntegrity = function (platformAndArch) { | ||
const expected = libvips.integrity(platformAndArch); | ||
if (installationForced || !expected) { | ||
libvips.log(`Integrity check skipped for ${platformAndArch}`); | ||
return new stream.PassThrough(); | ||
} | ||
const hash = createHash('sha512'); | ||
return new stream.Transform({ | ||
transform: function (chunk, _encoding, done) { | ||
hash.update(chunk); | ||
done(null, chunk); | ||
}, | ||
flush: function (done) { | ||
const digest = `sha512-${hash.digest('base64')}`; | ||
if (expected !== digest) { | ||
try { | ||
libvips.removeVendoredLibvips(); | ||
} catch (err) { | ||
libvips.log(err.message); | ||
} | ||
libvips.log(`Integrity expected: ${expected}`); | ||
libvips.log(`Integrity received: ${digest}`); | ||
done(new Error(`Integrity check failed for ${platformAndArch}`)); | ||
} else { | ||
libvips.log(`Integrity check passed for ${platformAndArch}`); | ||
done(); | ||
} | ||
} | ||
}); | ||
}; | ||
const extractTarball = function (tarPath, platformAndArch) { | ||
const versionedVendorPath = path.join(__dirname, '..', 'vendor', minimumLibvipsVersion, platformAndArch); | ||
libvips.mkdirSync(versionedVendorPath); | ||
const ignoreVendorInclude = hasSharpPrebuild.includes(platformAndArch) && !process.env.npm_config_build_from_source; | ||
const ignore = function (name) { | ||
return ignoreVendorInclude && name.includes('include/'); | ||
}; | ||
stream.pipeline( | ||
fs.createReadStream(tarPath), | ||
supportsBrotli ? new zlib.BrotliDecompress() : new zlib.Gunzip(), | ||
tarFs.extract(versionedVendorPath), | ||
verifyIntegrity(platformAndArch), | ||
new zlib.BrotliDecompress(), | ||
tarFs.extract(versionedVendorPath, { ignore }), | ||
function (err) { | ||
if (err) { | ||
if (/unexpected end of file/.test(err.message)) { | ||
npmLog.error('sharp', `Please delete ${tarPath} as it is not a valid tarball`); | ||
fail(new Error(`Please delete ${tarPath} as it is not a valid tarball`)); | ||
} | ||
@@ -67,7 +129,7 @@ fail(err); | ||
const globalLibvipsVersion = libvips.globalLibvipsVersion(); | ||
npmLog.info('sharp', `Detected globally-installed libvips v${globalLibvipsVersion}`); | ||
npmLog.info('sharp', 'Building from source via node-gyp'); | ||
libvips.log(`Detected globally-installed libvips v${globalLibvipsVersion}`); | ||
libvips.log('Building from source via node-gyp'); | ||
process.exit(1); | ||
} else if (libvips.hasVendoredLibvips()) { | ||
npmLog.info('sharp', `Using existing vendored libvips v${minimumLibvipsVersion}`); | ||
libvips.log(`Using existing vendored libvips v${minimumLibvipsVersion}`); | ||
} else { | ||
@@ -80,38 +142,41 @@ // Is this arch/platform supported? | ||
} | ||
if (platformAndArch === 'darwin-arm64') { | ||
throw new Error("Please run 'brew install vips' to install libvips on Apple M1 (ARM64) systems"); | ||
} | ||
if (platformAndArch === 'freebsd-x64' || platformAndArch === 'openbsd-x64' || platformAndArch === 'sunos-x64') { | ||
throw new Error(`BSD/SunOS systems require manual installation of libvips >= ${minimumLibvipsVersion}`); | ||
} | ||
if (detectLibc.family === detectLibc.GLIBC && detectLibc.version) { | ||
if (semver.lt(`${detectLibc.version}.0`, `${minimumGlibcVersionByArch[arch]}.0`)) { | ||
throw new Error(`Use with glibc ${detectLibc.version} requires manual installation of libvips >= ${minimumLibvipsVersion}`); | ||
// Linux libc version check | ||
const libcVersionRaw = detectLibc.versionSync(); | ||
if (libcVersionRaw) { | ||
const libcFamily = detectLibc.familySync(); | ||
const libcVersion = semverCoerce(libcVersionRaw).version; | ||
if (libcFamily === detectLibc.GLIBC && minimumGlibcVersionByArch[arch]) { | ||
if (semverLessThan(libcVersion, semverCoerce(minimumGlibcVersionByArch[arch]).version)) { | ||
handleError(new Error(`Use with glibc ${libcVersionRaw} requires manual installation of libvips >= ${minimumLibvipsVersion}`)); | ||
} | ||
} | ||
} | ||
if (detectLibc.family === detectLibc.MUSL && detectLibc.version) { | ||
if (!semver.satisfies(detectLibc.version, '>=1.1.24 <1.2.0')) { | ||
throw new Error(`Use with musl ${detectLibc.version} requires manual installation of libvips >= ${minimumLibvipsVersion}`); | ||
if (libcFamily === detectLibc.MUSL) { | ||
if (semverLessThan(libcVersion, '1.1.24')) { | ||
handleError(new Error(`Use with musl ${libcVersionRaw} requires manual installation of libvips >= ${minimumLibvipsVersion}`)); | ||
} | ||
} | ||
} | ||
// Node.js minimum version check | ||
const supportedNodeVersion = process.env.npm_package_engines_node || require('../package.json').engines.node; | ||
if (!semver.satisfies(process.versions.node, supportedNodeVersion)) { | ||
throw new Error(`Expected Node.js version ${supportedNodeVersion} but found ${process.versions.node}`); | ||
if (!semverSatisfies(process.versions.node, supportedNodeVersion)) { | ||
handleError(new Error(`Expected Node.js version ${supportedNodeVersion} but found ${process.versions.node}`)); | ||
} | ||
const extension = supportsBrotli ? 'br' : 'gz'; | ||
// Download to per-process temporary file | ||
const tarFilename = ['libvips', minimumLibvipsVersion, platformAndArch].join('-') + '.tar.' + extension; | ||
const tarFilename = ['libvips', minimumLibvipsVersionLabelled, platformAndArch].join('-') + '.tar.br'; | ||
const tarPathCache = path.join(libvips.cachePath(), tarFilename); | ||
if (fs.existsSync(tarPathCache)) { | ||
npmLog.info('sharp', `Using cached ${tarPathCache}`); | ||
extractTarball(tarPathCache); | ||
libvips.log(`Using cached ${tarPathCache}`); | ||
extractTarball(tarPathCache, platformAndArch); | ||
} else if (localLibvipsDir) { | ||
// If localLibvipsDir is given try to use binaries from local directory | ||
const tarPathLocal = path.join(path.resolve(localLibvipsDir), `v${minimumLibvipsVersionLabelled}`, tarFilename); | ||
libvips.log(`Using local libvips from ${tarPathLocal}`); | ||
extractTarball(tarPathLocal, platformAndArch); | ||
} else { | ||
const 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) { | ||
libvips.log(`Downloading ${url}`); | ||
simpleGet({ url: url, agent: agent(libvips.log) }, function (err, response) { | ||
if (err) { | ||
@@ -124,20 +189,35 @@ fail(err); | ||
} else { | ||
const tarPathTemp = path.join(os.tmpdir(), `${process.pid}-${tarFilename}`); | ||
const tmpFileStream = fs.createWriteStream(tarPathTemp); | ||
response | ||
.on('error', fail) | ||
.pipe(tmpFile); | ||
.on('error', function (err) { | ||
tmpFileStream.destroy(err); | ||
}) | ||
.on('close', function () { | ||
if (!response.complete) { | ||
tmpFileStream.destroy(new Error('Download incomplete (connection was terminated)')); | ||
} | ||
}) | ||
.pipe(tmpFileStream); | ||
tmpFileStream | ||
.on('error', function (err) { | ||
// Clean up temporary file | ||
try { | ||
fs.unlinkSync(tarPathTemp); | ||
} catch (e) {} | ||
fail(err); | ||
}) | ||
.on('close', function () { | ||
try { | ||
// Attempt to rename | ||
fs.renameSync(tarPathTemp, tarPathCache); | ||
} catch (err) { | ||
// Fall back to copy and unlink | ||
fs.copyFileSync(tarPathTemp, tarPathCache); | ||
fs.unlinkSync(tarPathTemp); | ||
} | ||
extractTarball(tarPathCache, platformAndArch); | ||
}); | ||
} | ||
}); | ||
tmpFile | ||
.on('error', fail) | ||
.on('close', function () { | ||
try { | ||
// Attempt to rename | ||
fs.renameSync(tarPathTemp, tarPathCache); | ||
} catch (err) { | ||
// Fall back to copy and unlink | ||
fs.copyFileSync(tarPathTemp, tarPathCache); | ||
fs.unlinkSync(tarPathTemp); | ||
} | ||
extractTarball(tarPathCache); | ||
}); | ||
} | ||
@@ -144,0 +224,0 @@ } |
@@ -0,1 +1,4 @@ | ||
// Copyright 2013 Lovell Fuller and others. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
'use strict'; | ||
@@ -21,3 +24,3 @@ | ||
module.exports = function () { | ||
module.exports = function (log) { | ||
try { | ||
@@ -29,4 +32,5 @@ const proxy = new url.URL(proxies.map(env).find(is.string)); | ||
const proxyAuth = proxy.username && proxy.password | ||
? `${proxy.username}:${proxy.password}` | ||
? `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}` | ||
: null; | ||
log(`Via proxy ${proxy.protocol}//${proxy.hostname}:${proxy.port} ${proxyAuth ? 'with' : 'no'} credentials`); | ||
return tunnel({ | ||
@@ -33,0 +37,0 @@ proxy: { |
@@ -0,1 +1,4 @@ | ||
// Copyright 2013 Lovell Fuller and others. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
'use strict'; | ||
@@ -18,2 +21,4 @@ | ||
* | ||
* See also {@link /api-operation#flatten|flatten}. | ||
* | ||
* @example | ||
@@ -34,3 +39,6 @@ * sharp('rgba.png') | ||
/** | ||
* Ensure alpha channel, if missing. The added alpha channel will be fully opaque. This is a no-op if the image already has an alpha channel. | ||
* Ensure the output image has an alpha transparency channel. | ||
* If missing, the added alpha channel will have the specified | ||
* transparency level, defaulting to fully-opaque (1). | ||
* This is a no-op if the image already has an alpha channel. | ||
* | ||
@@ -40,12 +48,27 @@ * @since 0.21.2 | ||
* @example | ||
* sharp('rgb.jpg') | ||
* // rgba.png will be a 4 channel image with a fully-opaque alpha channel | ||
* await sharp('rgb.jpg') | ||
* .ensureAlpha() | ||
* .toFile('rgba.png', function(err, info) { | ||
* // rgba.png is a 4 channel image with a fully opaque alpha channel | ||
* }); | ||
* .toFile('rgba.png') | ||
* | ||
* @example | ||
* // rgba is a 4 channel image with a fully-transparent alpha channel | ||
* const rgba = await sharp(rgb) | ||
* .ensureAlpha(0) | ||
* .toBuffer(); | ||
* | ||
* @param {number} [alpha=1] - alpha transparency level (0=fully-transparent, 1=fully-opaque) | ||
* @returns {Sharp} | ||
* @throws {Error} Invalid alpha transparency level | ||
*/ | ||
function ensureAlpha () { | ||
this.options.ensureAlpha = true; | ||
function ensureAlpha (alpha) { | ||
if (is.defined(alpha)) { | ||
if (is.number(alpha) && is.inRange(alpha, 0, 1)) { | ||
this.options.ensureAlpha = alpha; | ||
} else { | ||
throw is.invalidParameterError('alpha', 'number between 0 and 1', alpha); | ||
} | ||
} else { | ||
this.options.ensureAlpha = 1; | ||
} | ||
return this; | ||
@@ -58,10 +81,14 @@ } | ||
* @example | ||
* sharp(input) | ||
* // green.jpg is a greyscale image containing the green channel of the input | ||
* await sharp(input) | ||
* .extractChannel('green') | ||
* .toColourspace('b-w') | ||
* .toFile('green.jpg', function(err, info) { | ||
* // info.channels === 1 | ||
* // green.jpg is a greyscale image containing the green channel of the input | ||
* }); | ||
* .toFile('green.jpg'); | ||
* | ||
* @example | ||
* // red1 is the red value of the first pixel, red2 the second pixel etc. | ||
* const [red1, red2, ...] = await sharp(input) | ||
* .extractChannel(0) | ||
* .raw() | ||
* .toBuffer(); | ||
* | ||
* @param {number|string} channel - zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`. | ||
@@ -68,0 +95,0 @@ * @returns {Sharp} |
@@ -0,1 +1,4 @@ | ||
// Copyright 2013 Lovell Fuller and others. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
'use strict'; | ||
@@ -22,2 +25,7 @@ | ||
* | ||
* @example | ||
* const output = await sharp(input) | ||
* .tint({ r: 255, g: 240, b: 16 }) | ||
* .toBuffer(); | ||
* | ||
* @param {string|Object} rgb - parsed by the [color](https://www.npmjs.org/package/color) module to extract chroma values. | ||
@@ -41,2 +49,6 @@ * @returns {Sharp} | ||
* An alpha channel may be present, and will be unchanged by the operation. | ||
* | ||
* @example | ||
* const output = await sharp(input).greyscale().toBuffer(); | ||
* | ||
* @param {Boolean} [greyscale=true] | ||
@@ -60,2 +72,42 @@ * @returns {Sharp} | ||
/** | ||
* Set the pipeline colourspace. | ||
* | ||
* The input image will be converted to the provided colourspace at the start of the pipeline. | ||
* All operations will use this colourspace before converting to the output colourspace, | ||
* as defined by {@link #tocolourspace|toColourspace}. | ||
* | ||
* This feature is experimental and has not yet been fully-tested with all operations. | ||
* | ||
* @since 0.29.0 | ||
* | ||
* @example | ||
* // Run pipeline in 16 bits per channel RGB while converting final result to 8 bits per channel sRGB. | ||
* await sharp(input) | ||
* .pipelineColourspace('rgb16') | ||
* .toColourspace('srgb') | ||
* .toFile('16bpc-pipeline-to-8bpc-output.png') | ||
* | ||
* @param {string} [colourspace] - pipeline colourspace e.g. `rgb16`, `scrgb`, `lab`, `grey16` [...](https://github.com/libvips/libvips/blob/41cff4e9d0838498487a00623462204eb10ee5b8/libvips/iofuncs/enumtypes.c#L774) | ||
* @returns {Sharp} | ||
* @throws {Error} Invalid parameters | ||
*/ | ||
function pipelineColourspace (colourspace) { | ||
if (!is.string(colourspace)) { | ||
throw is.invalidParameterError('colourspace', 'string', colourspace); | ||
} | ||
this.options.colourspaceInput = colourspace; | ||
return this; | ||
} | ||
/** | ||
* Alternative spelling of `pipelineColourspace`. | ||
* @param {string} [colorspace] - pipeline colorspace. | ||
* @returns {Sharp} | ||
* @throws {Error} Invalid parameters | ||
*/ | ||
function pipelineColorspace (colorspace) { | ||
return this.pipelineColourspace(colorspace); | ||
} | ||
/** | ||
* Set the output colourspace. | ||
@@ -70,3 +122,3 @@ * By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. | ||
* | ||
* @param {string} [colourspace] - output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/libvips/libvips/blob/master/libvips/iofuncs/enumtypes.c#L568) | ||
* @param {string} [colourspace] - output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/libvips/libvips/blob/3c0bfdf74ce1dc37a6429bed47fa76f16e2cd70a/libvips/iofuncs/enumtypes.c#L777-L794) | ||
* @returns {Sharp} | ||
@@ -126,2 +178,4 @@ * @throws {Error} Invalid parameters | ||
grayscale, | ||
pipelineColourspace, | ||
pipelineColorspace, | ||
toColourspace, | ||
@@ -128,0 +182,0 @@ toColorspace, |
@@ -0,1 +1,4 @@ | ||
// Copyright 2013 Lovell Fuller and others. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
'use strict'; | ||
@@ -46,2 +49,5 @@ | ||
* | ||
* Any resize, rotate or extract operations in the same processing pipeline | ||
* will always be applied to the input image before composition. | ||
* | ||
* The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`, | ||
@@ -54,3 +60,3 @@ * `dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`, | ||
* More information about blend modes can be found at | ||
* https://libvips.github.io/libvips/API/current/libvips-conversion.html#VipsBlendMode | ||
* https://www.libvips.org/API/current/libvips-conversion.html#VipsBlendMode | ||
* and https://www.cairographics.org/operators/ | ||
@@ -61,2 +67,17 @@ * | ||
* @example | ||
* await sharp(background) | ||
* .composite([ | ||
* { input: layer1, gravity: 'northwest' }, | ||
* { input: layer2, gravity: 'southeast' }, | ||
* ]) | ||
* .toFile('combined.png'); | ||
* | ||
* @example | ||
* const output = await sharp('input.gif', { animated: true }) | ||
* .composite([ | ||
* { input: 'overlay.png', tile: true, blend: 'saturate' } | ||
* ]) | ||
* .toBuffer(); | ||
* | ||
* @example | ||
* sharp('input.png') | ||
@@ -84,2 +105,13 @@ * .rotate(180) | ||
* @param {String|Object} [images[].input.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. | ||
* @param {Object} [images[].input.text] - describes a new text image to be created. | ||
* @param {string} [images[].input.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`. | ||
* @param {string} [images[].input.text.font] - font name to render with. | ||
* @param {string} [images[].input.text.fontfile] - absolute filesystem path to a font file that can be used by `font`. | ||
* @param {number} [images[].input.text.width=0] - integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. | ||
* @param {number} [images[].input.text.height=0] - integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. | ||
* @param {string} [images[].input.text.align='left'] - text alignment (`'left'`, `'centre'`, `'center'`, `'right'`). | ||
* @param {boolean} [images[].input.text.justify=false] - set this to true to apply justification to the text. | ||
* @param {number} [images[].input.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified. | ||
* @param {boolean} [images[].input.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like `<span foreground="red">Red!</span>`. | ||
* @param {number} [images[].input.text.spacing=0] - text line height in points. Will use the font line height if none is specified. | ||
* @param {String} [images[].blend='over'] - how to blend this image with the image below. | ||
@@ -90,3 +122,3 @@ * @param {String} [images[].gravity='centre'] - gravity at which to place the overlay. | ||
* @param {Boolean} [images[].tile=false] - set to true to repeat the overlay image across the entire image with the given `gravity`. | ||
* @param {Boolean} [images[].premultiplied=false] - set to true to avoid premultipling the image below. Equivalent to the `--premultiplied` vips option. | ||
* @param {Boolean} [images[].premultiplied=false] - set to true to avoid premultiplying the image below. Equivalent to the `--premultiplied` vips option. | ||
* @param {Number} [images[].density=72] - number representing the DPI for vector overlay image. | ||
@@ -97,2 +129,5 @@ * @param {Object} [images[].raw] - describes overlay when using raw pixel data. | ||
* @param {Number} [images[].raw.channels] | ||
* @param {boolean} [images[].animated=false] - Set to `true` to read all frames/pages of an animated image. | ||
* @param {string} [images[].failOn='warning'] - @see {@link /api-constructor#parameters|constructor parameters} | ||
* @param {number|boolean} [images[].limitInputPixels=268402689] - @see {@link /api-constructor#parameters|constructor parameters} | ||
* @returns {Sharp} | ||
@@ -169,3 +204,2 @@ * @throws {Error} Invalid parameters | ||
} | ||
return composite; | ||
@@ -172,0 +206,0 @@ }); |
@@ -0,1 +1,4 @@ | ||
// Copyright 2013 Lovell Fuller and others. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
'use strict'; | ||
@@ -8,31 +11,4 @@ | ||
require('./libvips').hasVendoredLibvips(); | ||
require('./sharp'); | ||
/* istanbul ignore next */ | ||
try { | ||
require('../build/Release/sharp.node'); | ||
} catch (err) { | ||
// Bail early if bindings aren't available | ||
const help = ['', 'Something went wrong installing the "sharp" module', '', err.message, '']; | ||
if (/NODE_MODULE_VERSION/.test(err.message)) { | ||
help.push('- Ensure the version of Node.js used at install time matches that used at runtime'); | ||
} else if (/invalid ELF header/.test(err.message)) { | ||
help.push(`- Ensure "${process.platform}" is used at install time as well as runtime`); | ||
} else if (/dylib/.test(err.message) && /Incompatible library version/.test(err.message)) { | ||
help.push('- Run "brew update && brew upgrade vips"'); | ||
} else if (/Cannot find module/.test(err.message)) { | ||
help.push('- Run "npm rebuild --verbose sharp" and look for errors'); | ||
} else { | ||
help.push( | ||
'- Remove the "node_modules/sharp" directory then run', | ||
' "npm install --ignore-scripts=false --verbose" and look for errors' | ||
); | ||
} | ||
help.push( | ||
'- Consult the installation documentation at https://sharp.pixelplumbing.com/install', | ||
'- Search for this error at https://github.com/lovell/sharp/issues', '' | ||
); | ||
const error = help.join('\n'); | ||
throw new Error(error); | ||
} | ||
// Use NODE_DEBUG=sharp to enable libvips warnings | ||
@@ -44,3 +20,3 @@ const debuglog = util.debuglog('sharp'); | ||
* | ||
* JPEG, PNG, WebP, AVIF or TIFF format image data can be streamed out from this object. | ||
* JPEG, PNG, WebP, GIF, AVIF or TIFF format image data can be streamed out from this object. | ||
* When using Stream based output, derived attributes are available from the `info` event. | ||
@@ -78,3 +54,3 @@ * | ||
* @example | ||
* // Create a blank 300x200 PNG image of semi-transluent red pixels | ||
* // Create a blank 300x200 PNG image of semi-translucent red pixels | ||
* sharp({ | ||
@@ -125,19 +101,42 @@ * create: { | ||
* | ||
* @param {(Buffer|Uint8Array|Uint8ClampedArray|string)} [input] - if present, can be | ||
* a Buffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data, or | ||
* @example | ||
* // Generate an image from text | ||
* await sharp({ | ||
* text: { | ||
* text: 'Hello, world!', | ||
* width: 400, // max width | ||
* height: 300 // max height | ||
* } | ||
* }).toFile('text_bw.png'); | ||
* | ||
* @example | ||
* // Generate an rgba image from text using pango markup and font | ||
* await sharp({ | ||
* text: { | ||
* text: '<span foreground="red">Red!</span><span background="cyan">blue</span>', | ||
* font: 'sans', | ||
* rgba: true, | ||
* dpi: 300 | ||
* } | ||
* }).toFile('text_rgba.png'); | ||
* | ||
* @param {(Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string)} [input] - if present, can be | ||
* a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or | ||
* a TypedArray containing raw pixel image data, or | ||
* a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. | ||
* JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. | ||
* @param {Object} [options] - if present, is an Object with optional attributes. | ||
* @param {boolean} [options.failOnError=true] - by default halt processing and raise an error when loading invalid images. | ||
* Set this flag to `false` if you'd rather apply a "best effort" to decode images, even if the data is corrupt or invalid. | ||
* @param {string} [options.failOn='warning'] - when to abort processing of invalid pixel data, one of (in order of sensitivity): 'none' (least), 'truncated', 'error' or 'warning' (most), higher levels imply lower levels, invalid metadata will always abort. | ||
* @param {number|boolean} [options.limitInputPixels=268402689] - Do not process input images where the number of pixels | ||
* (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted. | ||
* An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). | ||
* @param {boolean} [options.sequentialRead=false] - Set this to `true` to use sequential rather than random access where possible. | ||
* This can reduce memory usage and might improve performance on some systems. | ||
* @param {boolean} [options.unlimited=false] - Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). | ||
* @param {boolean} [options.sequentialRead=true] - Set this to `false` to use random access rather than sequential read. Some operations will do this automatically. | ||
* @param {number} [options.density=72] - number representing the DPI for vector images in the range 1 to 100000. | ||
* @param {number} [options.pages=1] - number of pages to extract for multi-page input (GIF, WebP, AVIF, TIFF, PDF), use -1 for all pages. | ||
* @param {number} [options.page=0] - page number to start extracting from for multi-page input (GIF, WebP, AVIF, TIFF, PDF), zero based. | ||
* @param {number} [options.ignoreIcc=false] - should the embedded ICC profile, if any, be ignored. | ||
* @param {number} [options.pages=1] - Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages. | ||
* @param {number} [options.page=0] - Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based. | ||
* @param {number} [options.subifd=-1] - subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. | ||
* @param {number} [options.level=0] - level to extract from a multi-level input (OpenSlide), zero based. | ||
* @param {boolean} [options.animated=false] - Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). | ||
* @param {boolean} [options.animated=false] - Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`. | ||
* @param {Object} [options.raw] - describes raw pixel input image data. See `raw()` for pixel ordering. | ||
@@ -147,2 +146,4 @@ * @param {number} [options.raw.width] - integral number of pixels wide. | ||
* @param {number} [options.raw.channels] - integral number of channels, between 1 and 4. | ||
* @param {boolean} [options.raw.premultiplied] - specifies that the raw input has already been premultiplied, set to `true` | ||
* to avoid sharp premultiplying the image. (optional, default `false`) | ||
* @param {Object} [options.create] - describes a new image to be created. | ||
@@ -157,2 +158,14 @@ * @param {number} [options.create.width] - integral number of pixels wide. | ||
* @param {number} [options.create.noise.sigma] - standard deviation of pixels in generated noise. | ||
* @param {Object} [options.text] - describes a new text image to be created. | ||
* @param {string} [options.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`. | ||
* @param {string} [options.text.font] - font name to render with. | ||
* @param {string} [options.text.fontfile] - absolute filesystem path to a font file that can be used by `font`. | ||
* @param {number} [options.text.width=0] - Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. | ||
* @param {number} [options.text.height=0] - Maximum integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. | ||
* @param {string} [options.text.align='left'] - Alignment style for multi-line text (`'left'`, `'centre'`, `'center'`, `'right'`). | ||
* @param {boolean} [options.text.justify=false] - set this to true to apply justification to the text. | ||
* @param {number} [options.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified. | ||
* @param {boolean} [options.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground="red">Red!</span>`. | ||
* @param {number} [options.text.spacing=0] - text line height in points. Will use the font line height if none is specified. | ||
* @param {string} [options.text.wrap='word'] - word wrapping style when width is provided, one of: 'word', 'char', 'charWord' (prefer char, fallback to word) or 'none'. | ||
* @returns {Sharp} | ||
@@ -196,3 +209,5 @@ * @throws {Error} Invalid parameters | ||
extendBackground: [0, 0, 0, 255], | ||
extendWith: 'background', | ||
withoutEnlargement: false, | ||
withoutReduction: false, | ||
affineMatrix: [], | ||
@@ -212,10 +227,16 @@ affineBackground: [0, 0, 0, 255], | ||
flattenBackground: [0, 0, 0], | ||
unflatten: false, | ||
negate: false, | ||
negateAlpha: true, | ||
medianSize: 0, | ||
blurSigma: 0, | ||
sharpenSigma: 0, | ||
sharpenFlat: 1, | ||
sharpenJagged: 2, | ||
sharpenM1: 1, | ||
sharpenM2: 2, | ||
sharpenX1: 2, | ||
sharpenY2: 10, | ||
sharpenY3: 20, | ||
threshold: 0, | ||
thresholdGrayscale: true, | ||
trimBackground: [], | ||
trimThreshold: 0, | ||
@@ -226,5 +247,11 @@ gamma: 0, | ||
normalise: false, | ||
normaliseLower: 1, | ||
normaliseUpper: 99, | ||
claheWidth: 0, | ||
claheHeight: 0, | ||
claheMaxSlope: 3, | ||
brightness: 1, | ||
saturation: 1, | ||
hue: 0, | ||
lightness: 0, | ||
booleanBufferIn: null, | ||
@@ -235,4 +262,5 @@ booleanFileIn: '', | ||
removeAlpha: false, | ||
ensureAlpha: false, | ||
ensureAlpha: -1, | ||
colourspace: 'srgb', | ||
colourspaceInput: 'last', | ||
composite: [], | ||
@@ -245,3 +273,5 @@ // output | ||
withMetadataOrientation: -1, | ||
withMetadataDensity: 0, | ||
withMetadataIcc: '', | ||
withMetadataStrs: {}, | ||
resolveWithObject: false, | ||
@@ -258,8 +288,14 @@ // output format | ||
pngProgressive: false, | ||
pngCompressionLevel: 9, | ||
pngCompressionLevel: 6, | ||
pngAdaptiveFiltering: false, | ||
pngPalette: false, | ||
pngQuality: 100, | ||
pngColours: 256, | ||
pngEffort: 7, | ||
pngBitdepth: 8, | ||
pngDither: 1, | ||
jp2Quality: 80, | ||
jp2TileHeight: 512, | ||
jp2TileWidth: 512, | ||
jp2Lossless: false, | ||
jp2ChromaSubsampling: '4:4:4', | ||
webpQuality: 80, | ||
@@ -270,3 +306,13 @@ webpAlphaQuality: 100, | ||
webpSmartSubsample: false, | ||
webpReductionEffort: 4, | ||
webpPreset: 'default', | ||
webpEffort: 4, | ||
webpMinSize: false, | ||
webpMixed: false, | ||
gifBitdepth: 8, | ||
gifEffort: 7, | ||
gifDither: 1, | ||
gifInterFrameMaxError: 0, | ||
gifInterPaletteMaxError: 3, | ||
gifReuse: true, | ||
gifProgressive: false, | ||
tiffQuality: 80, | ||
@@ -282,7 +328,13 @@ tiffCompression: 'jpeg', | ||
tiffYres: 1.0, | ||
tiffResolutionUnit: 'inch', | ||
heifQuality: 50, | ||
heifLossless: false, | ||
heifCompression: 'av1', | ||
heifSpeed: 5, | ||
heifChromaSubsampling: '4:2:0', | ||
heifEffort: 4, | ||
heifChromaSubsampling: '4:4:4', | ||
jxlDistance: 1, | ||
jxlDecodingTier: 0, | ||
jxlEffort: 7, | ||
jxlLossless: false, | ||
rawDepth: 'uchar', | ||
tileSize: 256, | ||
@@ -298,4 +350,7 @@ tileOverlap: 0, | ||
tileCentre: false, | ||
linearA: 1, | ||
linearB: 0, | ||
tileId: 'https://example.com/iiif', | ||
tileBasename: '', | ||
timeoutSeconds: 0, | ||
linearA: [], | ||
linearB: [], | ||
// Function to notify of libvips warnings | ||
@@ -314,3 +369,4 @@ debuglog: warning => { | ||
}; | ||
util.inherits(Sharp, stream.Duplex); | ||
Object.setPrototypeOf(Sharp.prototype, stream.Duplex.prototype); | ||
Object.setPrototypeOf(Sharp, stream.Duplex); | ||
@@ -335,5 +391,3 @@ /** | ||
* const got = require("got"); | ||
* const sharpStream = sharp({ | ||
* failOnError: false | ||
* }); | ||
* const sharpStream = sharp({ failOn: 'none' }); | ||
* | ||
@@ -365,3 +419,3 @@ * const promises = []; | ||
* | ||
* // https://github.com/sindresorhus/got#gotstreamurl-options | ||
* // https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md | ||
* got.stream("https://www.example.com/some-file.jpg").pipe(sharpStream); | ||
@@ -368,0 +422,0 @@ * |
@@ -0,1 +1,4 @@ | ||
// Copyright 2013 Lovell Fuller and others. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
'use strict'; | ||
@@ -2,0 +5,0 @@ |
264
lib/input.js
@@ -0,1 +1,4 @@ | ||
// Copyright 2013 Lovell Fuller and others. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
'use strict'; | ||
@@ -5,5 +8,17 @@ | ||
const is = require('./is'); | ||
const sharp = require('../build/Release/sharp.node'); | ||
const sharp = require('./sharp'); | ||
/** | ||
* Justication alignment | ||
* @member | ||
* @private | ||
*/ | ||
const align = { | ||
left: 'low', | ||
center: 'centre', | ||
centre: 'centre', | ||
right: 'high' | ||
}; | ||
/** | ||
* Extract input options, if any, from an object. | ||
@@ -13,5 +28,5 @@ * @private | ||
function _inputOptionsFromObject (obj) { | ||
const { raw, density, limitInputPixels, sequentialRead, failOnError, animated, page, pages } = obj; | ||
return [raw, density, limitInputPixels, sequentialRead, failOnError, animated, page, pages].some(is.defined) | ||
? { raw, density, limitInputPixels, sequentialRead, failOnError, animated, page, pages } | ||
const { raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd } = obj; | ||
return [raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd].some(is.defined) | ||
? { raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd } | ||
: undefined; | ||
@@ -26,5 +41,7 @@ } | ||
const inputDescriptor = { | ||
failOnError: true, | ||
failOn: 'warning', | ||
limitInputPixels: Math.pow(0x3FFF, 2), | ||
sequentialRead: false | ||
ignoreIcc: false, | ||
unlimited: false, | ||
sequentialRead: true | ||
}; | ||
@@ -36,6 +53,16 @@ if (is.string(input)) { | ||
// Buffer | ||
if (input.length === 0) { | ||
throw Error('Input Buffer is empty'); | ||
} | ||
inputDescriptor.buffer = input; | ||
} else if (is.uint8Array(input)) { | ||
// Uint8Array or Uint8ClampedArray | ||
inputDescriptor.buffer = Buffer.from(input.buffer); | ||
} else if (is.arrayBuffer(input)) { | ||
if (input.byteLength === 0) { | ||
throw Error('Input bit Array is empty'); | ||
} | ||
inputDescriptor.buffer = Buffer.from(input, 0, input.byteLength); | ||
} else if (is.typedArray(input)) { | ||
if (input.length === 0) { | ||
throw Error('Input Bit Array is empty'); | ||
} | ||
inputDescriptor.buffer = Buffer.from(input.buffer, input.byteOffset, input.byteLength); | ||
} else if (is.plainObject(input) && !is.defined(inputOptions)) { | ||
@@ -57,6 +84,6 @@ // Plain Object descriptor, e.g. create | ||
if (is.object(inputOptions)) { | ||
// Fail on error | ||
// Deprecated: failOnError | ||
if (is.defined(inputOptions.failOnError)) { | ||
if (is.bool(inputOptions.failOnError)) { | ||
inputDescriptor.failOnError = inputOptions.failOnError; | ||
inputDescriptor.failOn = inputOptions.failOnError ? 'warning' : 'none'; | ||
} else { | ||
@@ -66,2 +93,10 @@ throw is.invalidParameterError('failOnError', 'boolean', inputOptions.failOnError); | ||
} | ||
// failOn | ||
if (is.defined(inputOptions.failOn)) { | ||
if (is.string(inputOptions.failOn) && is.inArray(inputOptions.failOn, ['none', 'truncated', 'error', 'warning'])) { | ||
inputDescriptor.failOn = inputOptions.failOn; | ||
} else { | ||
throw is.invalidParameterError('failOn', 'one of: none, truncated, error, warning', inputOptions.failOn); | ||
} | ||
} | ||
// Density | ||
@@ -75,2 +110,10 @@ if (is.defined(inputOptions.density)) { | ||
} | ||
// Ignore embeddded ICC profile | ||
if (is.defined(inputOptions.ignoreIcc)) { | ||
if (is.bool(inputOptions.ignoreIcc)) { | ||
inputDescriptor.ignoreIcc = inputOptions.ignoreIcc; | ||
} else { | ||
throw is.invalidParameterError('ignoreIcc', 'boolean', inputOptions.ignoreIcc); | ||
} | ||
} | ||
// limitInputPixels | ||
@@ -82,8 +125,16 @@ if (is.defined(inputOptions.limitInputPixels)) { | ||
: 0; | ||
} else if (is.integer(inputOptions.limitInputPixels) && inputOptions.limitInputPixels >= 0) { | ||
} else if (is.integer(inputOptions.limitInputPixels) && is.inRange(inputOptions.limitInputPixels, 0, Number.MAX_SAFE_INTEGER)) { | ||
inputDescriptor.limitInputPixels = inputOptions.limitInputPixels; | ||
} else { | ||
throw is.invalidParameterError('limitInputPixels', 'integer >= 0', inputOptions.limitInputPixels); | ||
throw is.invalidParameterError('limitInputPixels', 'positive integer', inputOptions.limitInputPixels); | ||
} | ||
} | ||
// unlimited | ||
if (is.defined(inputOptions.unlimited)) { | ||
if (is.bool(inputOptions.unlimited)) { | ||
inputDescriptor.unlimited = inputOptions.unlimited; | ||
} else { | ||
throw is.invalidParameterError('unlimited', 'boolean', inputOptions.unlimited); | ||
} | ||
} | ||
// sequentialRead | ||
@@ -108,2 +159,34 @@ if (is.defined(inputOptions.sequentialRead)) { | ||
inputDescriptor.rawChannels = inputOptions.raw.channels; | ||
inputDescriptor.rawPremultiplied = !!inputOptions.raw.premultiplied; | ||
switch (input.constructor) { | ||
case Uint8Array: | ||
case Uint8ClampedArray: | ||
inputDescriptor.rawDepth = 'uchar'; | ||
break; | ||
case Int8Array: | ||
inputDescriptor.rawDepth = 'char'; | ||
break; | ||
case Uint16Array: | ||
inputDescriptor.rawDepth = 'ushort'; | ||
break; | ||
case Int16Array: | ||
inputDescriptor.rawDepth = 'short'; | ||
break; | ||
case Uint32Array: | ||
inputDescriptor.rawDepth = 'uint'; | ||
break; | ||
case Int32Array: | ||
inputDescriptor.rawDepth = 'int'; | ||
break; | ||
case Float32Array: | ||
inputDescriptor.rawDepth = 'float'; | ||
break; | ||
case Float64Array: | ||
inputDescriptor.rawDepth = 'double'; | ||
break; | ||
default: | ||
inputDescriptor.rawDepth = 'uchar'; | ||
break; | ||
} | ||
} else { | ||
@@ -143,2 +226,10 @@ throw new Error('Expected width, height and channels for raw pixel input'); | ||
} | ||
// Sub Image File Directory (TIFF) | ||
if (is.defined(inputOptions.subifd)) { | ||
if (is.integer(inputOptions.subifd) && is.inRange(inputOptions.subifd, -1, 100000)) { | ||
inputDescriptor.subifd = inputOptions.subifd; | ||
} else { | ||
throw is.invalidParameterError('subifd', 'integer between -1 and 100000', inputOptions.subifd); | ||
} | ||
} | ||
// Create new image | ||
@@ -196,2 +287,84 @@ if (is.defined(inputOptions.create)) { | ||
} | ||
// Create a new image with text | ||
if (is.defined(inputOptions.text)) { | ||
if (is.object(inputOptions.text) && is.string(inputOptions.text.text)) { | ||
inputDescriptor.textValue = inputOptions.text.text; | ||
if (is.defined(inputOptions.text.height) && is.defined(inputOptions.text.dpi)) { | ||
throw new Error('Expected only one of dpi or height'); | ||
} | ||
if (is.defined(inputOptions.text.font)) { | ||
if (is.string(inputOptions.text.font)) { | ||
inputDescriptor.textFont = inputOptions.text.font; | ||
} else { | ||
throw is.invalidParameterError('text.font', 'string', inputOptions.text.font); | ||
} | ||
} | ||
if (is.defined(inputOptions.text.fontfile)) { | ||
if (is.string(inputOptions.text.fontfile)) { | ||
inputDescriptor.textFontfile = inputOptions.text.fontfile; | ||
} else { | ||
throw is.invalidParameterError('text.fontfile', 'string', inputOptions.text.fontfile); | ||
} | ||
} | ||
if (is.defined(inputOptions.text.width)) { | ||
if (is.number(inputOptions.text.width)) { | ||
inputDescriptor.textWidth = inputOptions.text.width; | ||
} else { | ||
throw is.invalidParameterError('text.textWidth', 'number', inputOptions.text.width); | ||
} | ||
} | ||
if (is.defined(inputOptions.text.height)) { | ||
if (is.number(inputOptions.text.height)) { | ||
inputDescriptor.textHeight = inputOptions.text.height; | ||
} else { | ||
throw is.invalidParameterError('text.height', 'number', inputOptions.text.height); | ||
} | ||
} | ||
if (is.defined(inputOptions.text.align)) { | ||
if (is.string(inputOptions.text.align) && is.string(this.constructor.align[inputOptions.text.align])) { | ||
inputDescriptor.textAlign = this.constructor.align[inputOptions.text.align]; | ||
} else { | ||
throw is.invalidParameterError('text.align', 'valid alignment', inputOptions.text.align); | ||
} | ||
} | ||
if (is.defined(inputOptions.text.justify)) { | ||
if (is.bool(inputOptions.text.justify)) { | ||
inputDescriptor.textJustify = inputOptions.text.justify; | ||
} else { | ||
throw is.invalidParameterError('text.justify', 'boolean', inputOptions.text.justify); | ||
} | ||
} | ||
if (is.defined(inputOptions.text.dpi)) { | ||
if (is.number(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 100000)) { | ||
inputDescriptor.textDpi = inputOptions.text.dpi; | ||
} else { | ||
throw is.invalidParameterError('text.dpi', 'number between 1 and 100000', inputOptions.text.dpi); | ||
} | ||
} | ||
if (is.defined(inputOptions.text.rgba)) { | ||
if (is.bool(inputOptions.text.rgba)) { | ||
inputDescriptor.textRgba = inputOptions.text.rgba; | ||
} else { | ||
throw is.invalidParameterError('text.rgba', 'bool', inputOptions.text.rgba); | ||
} | ||
} | ||
if (is.defined(inputOptions.text.spacing)) { | ||
if (is.number(inputOptions.text.spacing)) { | ||
inputDescriptor.textSpacing = inputOptions.text.spacing; | ||
} else { | ||
throw is.invalidParameterError('text.spacing', 'number', inputOptions.text.spacing); | ||
} | ||
} | ||
if (is.defined(inputOptions.text.wrap)) { | ||
if (is.string(inputOptions.text.wrap) && is.inArray(inputOptions.text.wrap, ['word', 'char', 'wordChar', 'none'])) { | ||
inputDescriptor.textWrap = inputOptions.text.wrap; | ||
} else { | ||
throw is.invalidParameterError('text.wrap', 'one of: word, char, wordChar, none', inputOptions.text.wrap); | ||
} | ||
} | ||
delete inputDescriptor.buffer; | ||
} else { | ||
throw new Error('Expected a valid string to create an image with text.'); | ||
} | ||
} | ||
} else if (is.defined(inputOptions)) { | ||
@@ -250,3 +423,11 @@ throw new Error('Invalid input options ' + inputOptions); | ||
/** | ||
* Fast access to (uncached) image metadata without decoding any compressed image data. | ||
* Fast access to (uncached) image metadata without decoding any compressed pixel data. | ||
* | ||
* This is read from the header of the input image. | ||
* It does not take into consideration any operations to be applied to the output image, | ||
* such as resize or rotate. | ||
* | ||
* Dimensions in the response will respect the `page` and `pages` properties of the | ||
* {@link /api-constructor#parameters|constructor parameters}. | ||
* | ||
* A `Promise` is returned when `callback` is not provided. | ||
@@ -256,7 +437,7 @@ * | ||
* - `size`: Total size of image in bytes, for Stream and Buffer input only | ||
* - `width`: Number of pixels wide (EXIF orientation is not taken into consideration) | ||
* - `height`: Number of pixels high (EXIF orientation is not taken into consideration) | ||
* - `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://libvips.github.io/libvips/API/current/VipsImage.html#VipsInterpretation) | ||
* - `width`: Number of pixels wide (EXIF orientation is not taken into consideration, see example below) | ||
* - `height`: Number of pixels high (EXIF orientation is not taken into consideration, see example below) | ||
* - `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://www.libvips.org/API/current/VipsImage.html#VipsInterpretation) | ||
* - `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK | ||
* - `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...](https://libvips.github.io/libvips/API/current/VipsImage.html#VipsBandFormat) | ||
* - `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...](https://www.libvips.org/API/current/VipsImage.html#VipsBandFormat) | ||
* - `density`: Number of pixels per inch (DPI), if present | ||
@@ -267,2 +448,3 @@ * - `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK | ||
* - `pageHeight`: Number of pixels high each page in a multi-page image will be. | ||
* - `paletteBitDepth`: Bit depth of palette-based image (GIF, PNG). | ||
* - `loop`: Number of times to loop an animated image, zero refers to a continuous loop. | ||
@@ -272,2 +454,6 @@ * - `delay`: Delay in ms between each page in an animated image, provided as an array of integers. | ||
* - `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide | ||
* - `subifds`: Number of Sub Image File Directories in an OME-TIFF image | ||
* - `background`: Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value | ||
* - `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC) | ||
* - `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present | ||
* - `hasProfile`: Boolean indicating the presence of an embedded ICC profile | ||
@@ -281,4 +467,8 @@ * - `hasAlpha`: Boolean indicating the presence of an alpha transparency channel | ||
* - `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present | ||
* - `formatMagick`: String containing format for images loaded via *magick | ||
* | ||
* @example | ||
* const metadata = await sharp(input).metadata(); | ||
* | ||
* @example | ||
* const image = sharp(inputJpg); | ||
@@ -297,2 +487,13 @@ * image | ||
* | ||
* @example | ||
* // Based on EXIF rotation metadata, get the right-side-up width and height: | ||
* | ||
* const size = getNormalSize(await sharp(input).metadata()); | ||
* | ||
* function getNormalSize({ width, height, orientation }) { | ||
* return (orientation || 0) >= 5 | ||
* ? { width: height, height: width } | ||
* : { width, height }; | ||
* } | ||
* | ||
* @param {Function} [callback] - called with the arguments `(err, metadata)` | ||
@@ -315,3 +516,3 @@ * @returns {Promise<Object>|Sharp} | ||
return new Promise((resolve, reject) => { | ||
this.on('finish', () => { | ||
const finished = () => { | ||
this._flattenBufferIn(); | ||
@@ -325,3 +526,8 @@ sharp.metadata(this.options, (err, metadata) => { | ||
}); | ||
}); | ||
}; | ||
if (this.writableFinished) { | ||
finished(); | ||
} else { | ||
this.once('finish', finished); | ||
} | ||
}); | ||
@@ -358,6 +564,9 @@ } else { | ||
* - `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque. | ||
* - `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any (experimental) | ||
* - `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any (experimental) | ||
* - `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram (experimental) | ||
* - `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any. | ||
* - `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any. | ||
* - `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram. | ||
* | ||
* **Note**: Statistics are derived from the original input image. Any operations performed on the image must first be | ||
* written to a buffer in order to run `stats` on the result (see third example). | ||
* | ||
* @example | ||
@@ -375,2 +584,9 @@ * const image = sharp(inputJpg); | ||
* | ||
* @example | ||
* const image = sharp(input); | ||
* // store intermediate result | ||
* const part = await image.extract(region).toBuffer(); | ||
* // create new instance to obtain statistics of extracted region | ||
* const stats = await sharp(part).stats(); | ||
* | ||
* @param {Function} [callback] - called with the arguments `(err, stats)` | ||
@@ -434,2 +650,4 @@ * @returns {Promise<Object>} | ||
}); | ||
// Class attributes | ||
Sharp.align = align; | ||
}; |
@@ -0,1 +1,4 @@ | ||
// Copyright 2013 Lovell Fuller and others. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
'use strict'; | ||
@@ -52,11 +55,33 @@ | ||
/** | ||
* Is this value a Uint8Array or Uint8ClampedArray object? | ||
* Is this value a typed array object?. E.g. Uint8Array or Uint8ClampedArray? | ||
* @private | ||
*/ | ||
const uint8Array = function (val) { | ||
// allow both since Uint8ClampedArray simply clamps the values between 0-255 | ||
return val instanceof Uint8Array || val instanceof Uint8ClampedArray; | ||
const typedArray = function (val) { | ||
if (defined(val)) { | ||
switch (val.constructor) { | ||
case Uint8Array: | ||
case Uint8ClampedArray: | ||
case Int8Array: | ||
case Uint16Array: | ||
case Int16Array: | ||
case Uint32Array: | ||
case Int32Array: | ||
case Float32Array: | ||
case Float64Array: | ||
return true; | ||
} | ||
} | ||
return false; | ||
}; | ||
/** | ||
* Is this value an ArrayBuffer object? | ||
* @private | ||
*/ | ||
const arrayBuffer = function (val) { | ||
return val instanceof ArrayBuffer; | ||
}; | ||
/** | ||
* Is this value a non-empty string? | ||
@@ -123,3 +148,4 @@ * @private | ||
buffer: buffer, | ||
uint8Array: uint8Array, | ||
typedArray: typedArray, | ||
arrayBuffer: arrayBuffer, | ||
string: string, | ||
@@ -126,0 +152,0 @@ number: number, |
@@ -0,1 +1,4 @@ | ||
// Copyright 2013 Lovell Fuller and others. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
'use strict'; | ||
@@ -7,9 +10,12 @@ | ||
const spawnSync = require('child_process').spawnSync; | ||
const semver = require('semver'); | ||
const semverCoerce = require('semver/functions/coerce'); | ||
const semverGreaterThanOrEqualTo = require('semver/functions/gte'); | ||
const platform = require('./platform'); | ||
const { config } = require('../package.json'); | ||
const env = process.env; | ||
const minimumLibvipsVersionLabelled = env.npm_package_config_libvips || /* istanbul ignore next */ | ||
require('../package.json').config.libvips; | ||
const minimumLibvipsVersion = semver.coerce(minimumLibvipsVersionLabelled).version; | ||
config.libvips; | ||
const minimumLibvipsVersion = semverCoerce(minimumLibvipsVersionLabelled).version; | ||
@@ -21,7 +27,9 @@ const spawnSyncOptions = { | ||
const vendorPath = path.join(__dirname, '..', 'vendor', minimumLibvipsVersion, platform()); | ||
const mkdirSync = function (dirPath) { | ||
try { | ||
fs.mkdirSync(dirPath); | ||
fs.mkdirSync(dirPath, { recursive: true }); | ||
} catch (err) { | ||
/* istanbul ignore if */ | ||
/* istanbul ignore next */ | ||
if (err.code !== 'EEXIST') { | ||
@@ -42,2 +50,14 @@ throw err; | ||
const integrity = function (platformAndArch) { | ||
return env[`npm_package_config_integrity_${platformAndArch.replace('-', '_')}`] || config.integrity[platformAndArch]; | ||
}; | ||
const log = function (item) { | ||
if (item instanceof Error) { | ||
console.error(`sharp: Installation error: ${item.message}`); | ||
} else { | ||
console.log(`sharp: ${item}`); | ||
} | ||
}; | ||
const isRosetta = function () { | ||
@@ -54,3 +74,9 @@ /* istanbul ignore next */ | ||
if (process.platform !== 'win32') { | ||
const globalLibvipsVersion = spawnSync(`PKG_CONFIG_PATH="${pkgConfigPath()}" pkg-config --modversion vips-cpp`, spawnSyncOptions).stdout; | ||
const globalLibvipsVersion = spawnSync('pkg-config --modversion vips-cpp', { | ||
...spawnSyncOptions, | ||
env: { | ||
...env, | ||
PKG_CONFIG_PATH: pkgConfigPath() | ||
} | ||
}).stdout; | ||
/* istanbul ignore next */ | ||
@@ -64,27 +90,25 @@ return (globalLibvipsVersion || '').trim(); | ||
const hasVendoredLibvips = function () { | ||
const currentPlatformId = platform(); | ||
const vendorPath = path.join(__dirname, '..', 'vendor', minimumLibvipsVersion); | ||
let vendorPlatformId; | ||
try { | ||
vendorPlatformId = require(path.join(vendorPath, 'platform.json')); | ||
} catch (err) {} | ||
/* istanbul ignore else */ | ||
if (vendorPlatformId) { | ||
/* istanbul ignore else */ | ||
if (currentPlatformId === vendorPlatformId) { | ||
return true; | ||
} else { | ||
throw new Error(`'${vendorPlatformId}' binaries cannot be used on the '${currentPlatformId}' platform. Please remove the 'node_modules/sharp' directory and run 'npm install' on the '${currentPlatformId}' platform.`); | ||
} | ||
} else { | ||
return false; | ||
} | ||
return fs.existsSync(vendorPath); | ||
}; | ||
/* istanbul ignore next */ | ||
const removeVendoredLibvips = function () { | ||
fs.rmSync(vendorPath, { recursive: true, maxRetries: 3, force: true }); | ||
}; | ||
/* istanbul ignore next */ | ||
const pkgConfigPath = function () { | ||
if (process.platform !== 'win32') { | ||
const brewPkgConfigPath = spawnSync('which brew >/dev/null 2>&1 && eval $(brew --env) && echo $PKG_CONFIG_LIBDIR', spawnSyncOptions).stdout || ''; | ||
return [brewPkgConfigPath.trim(), env.PKG_CONFIG_PATH, '/usr/local/lib/pkgconfig', '/usr/lib/pkgconfig'] | ||
.filter(function (p) { return !!p; }) | ||
.join(':'); | ||
const brewPkgConfigPath = spawnSync( | ||
'which brew >/dev/null 2>&1 && brew environment --plain | grep PKG_CONFIG_LIBDIR | cut -d" " -f2', | ||
spawnSyncOptions | ||
).stdout || ''; | ||
return [ | ||
brewPkgConfigPath.trim(), | ||
env.PKG_CONFIG_PATH, | ||
'/usr/local/lib/pkgconfig', | ||
'/usr/lib/pkgconfig', | ||
'/usr/local/libdata/pkgconfig', | ||
'/usr/libdata/pkgconfig' | ||
].filter(Boolean).join(':'); | ||
} else { | ||
@@ -101,2 +125,3 @@ return ''; | ||
if (isRosetta()) { | ||
log('Detected Rosetta, skipping search for globally-installed libvips'); | ||
return false; | ||
@@ -106,3 +131,3 @@ } | ||
return !!globalVipsVersion && /* istanbul ignore next */ | ||
semver.gte(globalVipsVersion, minimumLibvipsVersion); | ||
semverGreaterThanOrEqualTo(globalVipsVersion, minimumLibvipsVersion); | ||
}; | ||
@@ -114,4 +139,7 @@ | ||
cachePath, | ||
integrity, | ||
log, | ||
globalLibvipsVersion, | ||
hasVendoredLibvips, | ||
removeVendoredLibvips, | ||
pkgConfigPath, | ||
@@ -118,0 +146,0 @@ useGlobalLibvips, |
@@ -0,4 +1,6 @@ | ||
// Copyright 2013 Lovell Fuller and others. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
'use strict'; | ||
const { flatten: flattenArray } = require('array-flatten'); | ||
const color = require('color'); | ||
@@ -12,3 +14,3 @@ const is = require('./is'); | ||
* If an angle is provided, it is converted to a valid positive degree rotation. | ||
* For example, `-450` will produce a 270deg rotation. | ||
* For example, `-450` will produce a 270 degree rotation. | ||
* | ||
@@ -21,7 +23,10 @@ * When rotating by an angle other than a multiple of 90, | ||
* | ||
* The use of `rotate` implies the removal of the EXIF `Orientation` tag, if any. | ||
* The use of `rotate` without an angle will remove the EXIF `Orientation` tag, if any. | ||
* | ||
* Method order is important when both rotating and extracting regions, | ||
* for example `rotate(x).extract(y)` will produce a different result to `extract(y).rotate(x)`. | ||
* Only one rotation can occur per pipeline. | ||
* Previous calls to `rotate` in the same pipeline will be ignored. | ||
* | ||
* Method order is important when rotating, resizing and/or extracting regions, | ||
* for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`. | ||
* | ||
* @example | ||
@@ -38,2 +43,12 @@ * const pipeline = sharp() | ||
* | ||
* @example | ||
* const rotateThenResize = await sharp(input) | ||
* .rotate(90) | ||
* .resize({ width: 16, height: 8, fit: 'fill' }) | ||
* .toBuffer(); | ||
* const resizeThenRotate = await sharp(input) | ||
* .resize({ width: 16, height: 8, fit: 'fill' }) | ||
* .rotate(90) | ||
* .toBuffer(); | ||
* | ||
* @param {number} [angle=auto] angle of rotation. | ||
@@ -46,2 +61,5 @@ * @param {Object} [options] - if present, is an Object with optional attributes. | ||
function rotate (angle, options) { | ||
if (this.options.useExifOrientation || this.options.angle || this.options.rotationAngle) { | ||
this.options.debuglog('ignoring previous rotate options'); | ||
} | ||
if (!is.defined(angle)) { | ||
@@ -69,4 +87,10 @@ this.options.useExifOrientation = true; | ||
/** | ||
* Flip the image about the vertical Y axis. This always occurs after rotation, if any. | ||
* The use of `flip` implies the removal of the EXIF `Orientation` tag, if any. | ||
* Mirror the image vertically (up-down) about the x-axis. | ||
* This always occurs before rotation, if any. | ||
* | ||
* This operation does not work correctly with multi-page images. | ||
* | ||
* @example | ||
* const output = await sharp(input).flip().toBuffer(); | ||
* | ||
* @param {Boolean} [flip=true] | ||
@@ -81,4 +105,8 @@ * @returns {Sharp} | ||
/** | ||
* Flop the image about the horizontal X axis. This always occurs after rotation, if any. | ||
* The use of `flop` implies the removal of the EXIF `Orientation` tag, if any. | ||
* Mirror the image horizontally (left-right) about the y-axis. | ||
* This always occurs before rotation, if any. | ||
* | ||
* @example | ||
* const output = await sharp(input).flop().toBuffer(); | ||
* | ||
* @param {Boolean} [flop=true] | ||
@@ -97,3 +125,3 @@ * @returns {Sharp} | ||
* By default, new pixels are filled with a black background. You can provide a background color with the `background` option. | ||
* A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolator` Object e.g. `sharp.interpolator.nohalo`. | ||
* A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`. | ||
* | ||
@@ -115,3 +143,3 @@ * In the case of a 2x2 matrix, the transform is: | ||
* background: 'white', | ||
* interpolate: sharp.interpolators.nohalo | ||
* interpolator: sharp.interpolators.nohalo | ||
* }) | ||
@@ -138,3 +166,3 @@ * .toBuffer((err, outputBuffer, info) => { | ||
function affine (matrix, options) { | ||
const flatMatrix = flattenArray(matrix); | ||
const flatMatrix = [].concat(...matrix); | ||
if (flatMatrix.length === 4 && flatMatrix.every(is.number)) { | ||
@@ -194,26 +222,54 @@ this.options.affineMatrix = flatMatrix; | ||
* Sharpen the image. | ||
* | ||
* When used without parameters, performs a fast, mild sharpen of the output image. | ||
* | ||
* When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space. | ||
* Separate control over the level of sharpening in "flat" and "jagged" areas is available. | ||
* Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available. | ||
* | ||
* @param {number} [sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. | ||
* @param {number} [flat=1.0] - the level of sharpening to apply to "flat" areas. | ||
* @param {number} [jagged=2.0] - the level of sharpening to apply to "jagged" areas. | ||
* See {@link https://www.libvips.org/API/current/libvips-convolution.html#vips-sharpen|libvips sharpen} operation. | ||
* | ||
* @example | ||
* const data = await sharp(input).sharpen().toBuffer(); | ||
* | ||
* @example | ||
* const data = await sharp(input).sharpen({ sigma: 2 }).toBuffer(); | ||
* | ||
* @example | ||
* const data = await sharp(input) | ||
* .sharpen({ | ||
* sigma: 2, | ||
* m1: 0, | ||
* m2: 3, | ||
* x1: 3, | ||
* y2: 15, | ||
* y3: 15, | ||
* }) | ||
* .toBuffer(); | ||
* | ||
* @param {Object|number} [options] - if present, is an Object with attributes | ||
* @param {number} [options.sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`, between 0.000001 and 10 | ||
* @param {number} [options.m1=1.0] - the level of sharpening to apply to "flat" areas, between 0 and 1000000 | ||
* @param {number} [options.m2=2.0] - the level of sharpening to apply to "jagged" areas, between 0 and 1000000 | ||
* @param {number} [options.x1=2.0] - threshold between "flat" and "jagged", between 0 and 1000000 | ||
* @param {number} [options.y2=10.0] - maximum amount of brightening, between 0 and 1000000 | ||
* @param {number} [options.y3=20.0] - maximum amount of darkening, between 0 and 1000000 | ||
* @param {number} [flat] - (deprecated) see `options.m1`. | ||
* @param {number} [jagged] - (deprecated) see `options.m2`. | ||
* @returns {Sharp} | ||
* @throws {Error} Invalid parameters | ||
*/ | ||
function sharpen (sigma, flat, jagged) { | ||
if (!is.defined(sigma)) { | ||
function sharpen (options, flat, jagged) { | ||
if (!is.defined(options)) { | ||
// No arguments: default to mild sharpen | ||
this.options.sharpenSigma = -1; | ||
} else if (is.bool(sigma)) { | ||
// Boolean argument: apply mild sharpen? | ||
this.options.sharpenSigma = sigma ? -1 : 0; | ||
} else if (is.number(sigma) && is.inRange(sigma, 0.01, 10000)) { | ||
// Numeric argument: specific sigma | ||
this.options.sharpenSigma = sigma; | ||
// Control over flat areas | ||
} else if (is.bool(options)) { | ||
// Deprecated boolean argument: apply mild sharpen? | ||
this.options.sharpenSigma = options ? -1 : 0; | ||
} else if (is.number(options) && is.inRange(options, 0.01, 10000)) { | ||
// Deprecated numeric argument: specific sigma | ||
this.options.sharpenSigma = options; | ||
// Deprecated control over flat areas | ||
if (is.defined(flat)) { | ||
if (is.number(flat) && is.inRange(flat, 0, 10000)) { | ||
this.options.sharpenFlat = flat; | ||
this.options.sharpenM1 = flat; | ||
} else { | ||
@@ -223,6 +279,6 @@ throw is.invalidParameterError('flat', 'number between 0 and 10000', flat); | ||
} | ||
// Control over jagged areas | ||
// Deprecated control over jagged areas | ||
if (is.defined(jagged)) { | ||
if (is.number(jagged) && is.inRange(jagged, 0, 10000)) { | ||
this.options.sharpenJagged = jagged; | ||
this.options.sharpenM2 = jagged; | ||
} else { | ||
@@ -232,4 +288,45 @@ throw is.invalidParameterError('jagged', 'number between 0 and 10000', jagged); | ||
} | ||
} else if (is.plainObject(options)) { | ||
if (is.number(options.sigma) && is.inRange(options.sigma, 0.000001, 10)) { | ||
this.options.sharpenSigma = options.sigma; | ||
} else { | ||
throw is.invalidParameterError('options.sigma', 'number between 0.000001 and 10', options.sigma); | ||
} | ||
if (is.defined(options.m1)) { | ||
if (is.number(options.m1) && is.inRange(options.m1, 0, 1000000)) { | ||
this.options.sharpenM1 = options.m1; | ||
} else { | ||
throw is.invalidParameterError('options.m1', 'number between 0 and 1000000', options.m1); | ||
} | ||
} | ||
if (is.defined(options.m2)) { | ||
if (is.number(options.m2) && is.inRange(options.m2, 0, 1000000)) { | ||
this.options.sharpenM2 = options.m2; | ||
} else { | ||
throw is.invalidParameterError('options.m2', 'number between 0 and 1000000', options.m2); | ||
} | ||
} | ||
if (is.defined(options.x1)) { | ||
if (is.number(options.x1) && is.inRange(options.x1, 0, 1000000)) { | ||
this.options.sharpenX1 = options.x1; | ||
} else { | ||
throw is.invalidParameterError('options.x1', 'number between 0 and 1000000', options.x1); | ||
} | ||
} | ||
if (is.defined(options.y2)) { | ||
if (is.number(options.y2) && is.inRange(options.y2, 0, 1000000)) { | ||
this.options.sharpenY2 = options.y2; | ||
} else { | ||
throw is.invalidParameterError('options.y2', 'number between 0 and 1000000', options.y2); | ||
} | ||
} | ||
if (is.defined(options.y3)) { | ||
if (is.number(options.y3) && is.inRange(options.y3, 0, 1000000)) { | ||
this.options.sharpenY3 = options.y3; | ||
} else { | ||
throw is.invalidParameterError('options.y3', 'number between 0 and 1000000', options.y3); | ||
} | ||
} | ||
} else { | ||
throw is.invalidParameterError('sigma', 'number between 0.01 and 10000', sigma); | ||
throw is.invalidParameterError('sigma', 'number between 0.01 and 10000', options); | ||
} | ||
@@ -242,2 +339,9 @@ return this; | ||
* When used without parameters the default window is 3x3. | ||
* | ||
* @example | ||
* const output = await sharp(input).median().toBuffer(); | ||
* | ||
* @example | ||
* const output = await sharp(input).median(5).toBuffer(); | ||
* | ||
* @param {number} [size=3] square mask size: size x size | ||
@@ -262,4 +366,17 @@ * @returns {Sharp} | ||
* Blur the image. | ||
* When used without parameters, performs a fast, mild blur of the output image. | ||
* | ||
* When used without parameters, performs a fast 3x3 box blur (equivalent to a box linear filter). | ||
* | ||
* When a `sigma` is provided, performs a slower, more accurate Gaussian blur. | ||
* | ||
* @example | ||
* const boxBlurred = await sharp(input) | ||
* .blur() | ||
* .toBuffer(); | ||
* | ||
* @example | ||
* const gaussianBlurred = await sharp(input) | ||
* .blur(5) | ||
* .toBuffer(); | ||
* | ||
* @param {number} [sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. | ||
@@ -286,3 +403,11 @@ * @returns {Sharp} | ||
/** | ||
* Merge alpha transparency channel, if any, with a background. | ||
* Merge alpha transparency channel, if any, with a background, then remove the alpha channel. | ||
* | ||
* See also {@link /api-channel#removealpha|removeAlpha}. | ||
* | ||
* @example | ||
* await sharp(rgbaInput) | ||
* .flatten({ background: '#F0A703' }) | ||
* .toBuffer(); | ||
* | ||
* @param {Object} [options] | ||
@@ -301,2 +426,28 @@ * @param {string|Object} [options.background={r: 0, g: 0, b: 0}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black. | ||
/** | ||
* Ensure the image has an alpha channel | ||
* with all white pixel values made fully transparent. | ||
* | ||
* Existing alpha channel values for non-white pixels remain unchanged. | ||
* | ||
* This feature is experimental and the API may change. | ||
* | ||
* @since 0.32.1 | ||
* | ||
* @example | ||
* await sharp(rgbInput) | ||
* .unflatten() | ||
* .toBuffer(); | ||
* | ||
* @example | ||
* await sharp(rgbInput) | ||
* .threshold(128, { grayscale: false }) // converter bright pixels to white | ||
* .unflatten() | ||
* .toBuffer(); | ||
*/ | ||
function unflatten () { | ||
this.options.unflatten = true; | ||
return this; | ||
} | ||
/** | ||
* Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of `1/gamma` | ||
@@ -337,7 +488,26 @@ * then increasing the encoding (brighten) post-resize at a factor of `gamma`. | ||
* Produce the "negative" of the image. | ||
* @param {Boolean} [negate=true] | ||
* | ||
* @example | ||
* const output = await sharp(input) | ||
* .negate() | ||
* .toBuffer(); | ||
* | ||
* @example | ||
* const output = await sharp(input) | ||
* .negate({ alpha: false }) | ||
* .toBuffer(); | ||
* | ||
* @param {Object} [options] | ||
* @param {Boolean} [options.alpha=true] Whether or not to negate any alpha channel | ||
* @returns {Sharp} | ||
*/ | ||
function negate (negate) { | ||
this.options.negate = is.bool(negate) ? negate : true; | ||
function negate (options) { | ||
this.options.negate = is.bool(options) ? options : true; | ||
if (is.plainObject(options) && 'alpha' in options) { | ||
if (!is.bool(options.alpha)) { | ||
throw is.invalidParameterError('alpha', 'should be boolean value', options.alpha); | ||
} else { | ||
this.options.negateAlpha = options.alpha; | ||
} | ||
} | ||
return this; | ||
@@ -347,8 +517,46 @@ } | ||
/** | ||
* Enhance output image contrast by stretching its luminance to cover the full dynamic range. | ||
* @param {Boolean} [normalise=true] | ||
* Enhance output image contrast by stretching its luminance to cover a full dynamic range. | ||
* | ||
* Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes. | ||
* | ||
* Luminance values below the `lower` percentile will be underexposed by clipping to zero. | ||
* Luminance values above the `upper` percentile will be overexposed by clipping to the max pixel value. | ||
* | ||
* @example | ||
* const output = await sharp(input) | ||
* .normalise() | ||
* .toBuffer(); | ||
* | ||
* @example | ||
* const output = await sharp(input) | ||
* .normalise({ lower: 0, upper: 100 }) | ||
* .toBuffer(); | ||
* | ||
* @param {Object} [options] | ||
* @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed. | ||
* @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed. | ||
* @returns {Sharp} | ||
*/ | ||
function normalise (normalise) { | ||
this.options.normalise = is.bool(normalise) ? normalise : true; | ||
function normalise (options) { | ||
if (is.plainObject(options)) { | ||
if (is.defined(options.lower)) { | ||
if (is.number(options.lower) && is.inRange(options.lower, 0, 99)) { | ||
this.options.normaliseLower = options.lower; | ||
} else { | ||
throw is.invalidParameterError('lower', 'number between 0 and 99', options.lower); | ||
} | ||
} | ||
if (is.defined(options.upper)) { | ||
if (is.number(options.upper) && is.inRange(options.upper, 1, 100)) { | ||
this.options.normaliseUpper = options.upper; | ||
} else { | ||
throw is.invalidParameterError('upper', 'number between 1 and 100', options.upper); | ||
} | ||
} | ||
} | ||
if (this.options.normaliseLower >= this.options.normaliseUpper) { | ||
throw is.invalidParameterError('range', 'lower to be less than upper', | ||
`${this.options.normaliseLower} >= ${this.options.normaliseUpper}`); | ||
} | ||
this.options.normalise = true; | ||
return this; | ||
@@ -359,10 +567,66 @@ } | ||
* Alternative spelling of normalise. | ||
* @param {Boolean} [normalize=true] | ||
* | ||
* @example | ||
* const output = await sharp(input) | ||
* .normalize() | ||
* .toBuffer(); | ||
* | ||
* @param {Object} [options] | ||
* @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed. | ||
* @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed. | ||
* @returns {Sharp} | ||
*/ | ||
function normalize (normalize) { | ||
return this.normalise(normalize); | ||
function normalize (options) { | ||
return this.normalise(options); | ||
} | ||
/** | ||
* Perform contrast limiting adaptive histogram equalization | ||
* {@link https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE|CLAHE}. | ||
* | ||
* This will, in general, enhance the clarity of the image by bringing out darker details. | ||
* | ||
* @since 0.28.3 | ||
* | ||
* @example | ||
* const output = await sharp(input) | ||
* .clahe({ | ||
* width: 3, | ||
* height: 3, | ||
* }) | ||
* .toBuffer(); | ||
* | ||
* @param {Object} options | ||
* @param {number} options.width - Integral width of the search window, in pixels. | ||
* @param {number} options.height - Integral height of the search window, in pixels. | ||
* @param {number} [options.maxSlope=3] - Integral level of brightening, between 0 and 100, where 0 disables contrast limiting. | ||
* @returns {Sharp} | ||
* @throws {Error} Invalid parameters | ||
*/ | ||
function clahe (options) { | ||
if (is.plainObject(options)) { | ||
if (is.integer(options.width) && options.width > 0) { | ||
this.options.claheWidth = options.width; | ||
} else { | ||
throw is.invalidParameterError('width', 'integer greater than zero', options.width); | ||
} | ||
if (is.integer(options.height) && options.height > 0) { | ||
this.options.claheHeight = options.height; | ||
} else { | ||
throw is.invalidParameterError('height', 'integer greater than zero', options.height); | ||
} | ||
if (is.defined(options.maxSlope)) { | ||
if (is.integer(options.maxSlope) && is.inRange(options.maxSlope, 0, 100)) { | ||
this.options.claheMaxSlope = options.maxSlope; | ||
} else { | ||
throw is.invalidParameterError('maxSlope', 'integer between 0 and 100', options.maxSlope); | ||
} | ||
} | ||
} else { | ||
throw is.invalidParameterError('options', 'plain object', options); | ||
} | ||
return this; | ||
} | ||
/** | ||
* Convolve the image with the specified kernel. | ||
@@ -385,3 +649,3 @@ * | ||
* @param {number} kernel.width - width of the kernel in pixels. | ||
* @param {number} kernel.height - width of the kernel in pixels. | ||
* @param {number} kernel.height - height of the kernel in pixels. | ||
* @param {Array<number>} kernel.kernel - Array of length `width*height` containing the kernel values. | ||
@@ -420,3 +684,3 @@ * @param {number} [kernel.scale=sum] - the scale of the kernel in pixels. | ||
/** | ||
* Any pixel value greather than or equal to the threshold value will be set to 255, otherwise it will be set to 0. | ||
* Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0. | ||
* @param {number} [threshold=128] - a value in the range 0-255 representing the level at which the threshold will be applied. | ||
@@ -474,5 +738,22 @@ * @param {Object} [options] | ||
/** | ||
* Apply the linear formula a * input + b to the image (levels adjustment) | ||
* @param {number} [a=1.0] multiplier | ||
* @param {number} [b=0.0] offset | ||
* Apply the linear formula `a` * input + `b` to the image to adjust image levels. | ||
* | ||
* When a single number is provided, it will be used for all image channels. | ||
* When an array of numbers is provided, the array length must match the number of channels. | ||
* | ||
* @example | ||
* await sharp(input) | ||
* .linear(0.5, 2) | ||
* .toBuffer(); | ||
* | ||
* @example | ||
* await sharp(rgbInput) | ||
* .linear( | ||
* [0.25, 0.5, 0.75], | ||
* [150, 100, 50] | ||
* ) | ||
* .toBuffer(); | ||
* | ||
* @param {(number|number[])} [a=[]] multiplier | ||
* @param {(number|number[])} [b=[]] offset | ||
* @returns {Sharp} | ||
@@ -482,16 +763,28 @@ * @throws {Error} Invalid parameters | ||
function linear (a, b) { | ||
if (!is.defined(a) && is.number(b)) { | ||
a = 1.0; | ||
} else if (is.number(a) && !is.defined(b)) { | ||
b = 0.0; | ||
} | ||
if (!is.defined(a)) { | ||
this.options.linearA = 1.0; | ||
this.options.linearA = []; | ||
} else if (is.number(a)) { | ||
this.options.linearA = [a]; | ||
} else if (Array.isArray(a) && a.length && a.every(is.number)) { | ||
this.options.linearA = a; | ||
} else { | ||
throw is.invalidParameterError('a', 'numeric', a); | ||
throw is.invalidParameterError('a', 'number or array of numbers', a); | ||
} | ||
if (!is.defined(b)) { | ||
this.options.linearB = 0.0; | ||
this.options.linearB = []; | ||
} else if (is.number(b)) { | ||
this.options.linearB = [b]; | ||
} else if (Array.isArray(b) && b.length && b.every(is.number)) { | ||
this.options.linearB = b; | ||
} else { | ||
throw is.invalidParameterError('b', 'numeric', b); | ||
throw is.invalidParameterError('b', 'number or array of numbers', b); | ||
} | ||
if (this.options.linearA.length !== this.options.linearB.length) { | ||
throw new Error('Expected a and b to be arrays of the same length'); | ||
} | ||
return this; | ||
@@ -501,3 +794,3 @@ } | ||
/** | ||
* Recomb the image with the specified matrix. | ||
* Recombine the image with the specified matrix. | ||
* | ||
@@ -515,3 +808,3 @@ * @since 0.21.1 | ||
* .toBuffer(function(err, data, info) { | ||
* // data contains the raw pixel data after applying the recomb | ||
* // data contains the raw pixel data after applying the matrix | ||
* // With this example input, a sepia filter has been applied | ||
@@ -542,3 +835,5 @@ * }); | ||
/** | ||
* Transforms the image using brightness, saturation and hue rotation. | ||
* Transforms the image using brightness, saturation, hue rotation, and lightness. | ||
* Brightness and lightness both operate on luminance, with the difference being that | ||
* brightness is multiplicative whereas lightness is additive. | ||
* | ||
@@ -548,19 +843,34 @@ * @since 0.22.1 | ||
* @example | ||
* sharp(input) | ||
* // increase brightness by a factor of 2 | ||
* const output = await sharp(input) | ||
* .modulate({ | ||
* brightness: 2 // increase lightness by a factor of 2 | ||
* }); | ||
* brightness: 2 | ||
* }) | ||
* .toBuffer(); | ||
* | ||
* sharp(input) | ||
* @example | ||
* // hue-rotate by 180 degrees | ||
* const output = await sharp(input) | ||
* .modulate({ | ||
* hue: 180 // hue-rotate by 180 degrees | ||
* }); | ||
* hue: 180 | ||
* }) | ||
* .toBuffer(); | ||
* | ||
* // decreate brightness and saturation while also hue-rotating by 90 degrees | ||
* sharp(input) | ||
* @example | ||
* // increase lightness by +50 | ||
* const output = await sharp(input) | ||
* .modulate({ | ||
* lightness: 50 | ||
* }) | ||
* .toBuffer(); | ||
* | ||
* @example | ||
* // decrease brightness and saturation while also hue-rotating by 90 degrees | ||
* const output = await sharp(input) | ||
* .modulate({ | ||
* brightness: 0.5, | ||
* saturation: 0.5, | ||
* hue: 90 | ||
* }); | ||
* hue: 90, | ||
* }) | ||
* .toBuffer(); | ||
* | ||
@@ -571,2 +881,3 @@ * @param {Object} [options] | ||
* @param {number} [options.hue] Degrees for hue rotation | ||
* @param {number} [options.lightness] Lightness addend | ||
* @returns {Sharp} | ||
@@ -599,2 +910,9 @@ */ | ||
} | ||
if ('lightness' in options) { | ||
if (is.number(options.lightness)) { | ||
this.options.lightness = options.lightness; | ||
} else { | ||
throw is.invalidParameterError('lightness', 'number', options.lightness); | ||
} | ||
} | ||
return this; | ||
@@ -617,2 +935,3 @@ } | ||
flatten, | ||
unflatten, | ||
gamma, | ||
@@ -622,2 +941,3 @@ negate, | ||
normalize, | ||
clahe, | ||
convolve, | ||
@@ -624,0 +944,0 @@ threshold, |
@@ -0,5 +1,9 @@ | ||
// Copyright 2013 Lovell Fuller and others. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
'use strict'; | ||
const path = require('path'); | ||
const is = require('./is'); | ||
const sharp = require('../build/Release/sharp.node'); | ||
const sharp = require('./sharp'); | ||
@@ -12,11 +16,24 @@ const formats = new Map([ | ||
['jpg', 'jpeg'], | ||
['jpe', 'jpeg'], | ||
['tile', 'tile'], | ||
['dz', 'tile'], | ||
['png', 'png'], | ||
['raw', 'raw'], | ||
['tiff', 'tiff'], | ||
['tif', 'tiff'], | ||
['webp', 'webp'], | ||
['gif', 'gif'] | ||
['gif', 'gif'], | ||
['jp2', 'jp2'], | ||
['jpx', 'jp2'], | ||
['j2k', 'jp2'], | ||
['j2c', 'jp2'], | ||
['jxl', 'jxl'] | ||
]); | ||
const errMagickSave = new Error('GIF output requires libvips with support for ImageMagick'); | ||
const jp2Regex = /\.(jp[2x]|j2[kc])$/i; | ||
const errJp2Save = () => new Error('JP2 output requires libvips with support for OpenJPEG'); | ||
const bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math.log2(colours))); | ||
/** | ||
@@ -26,8 +43,10 @@ * Write output image data to a file. | ||
* If an explicit output format is not selected, it will be inferred from the extension, | ||
* with JPEG, PNG, WebP, AVIF, TIFF, DZI, and libvips' V format supported. | ||
* with JPEG, PNG, WebP, AVIF, TIFF, GIF, DZI, and libvips' V format supported. | ||
* Note that raw pixel data is only supported for buffer output. | ||
* | ||
* By default all metadata will be removed, which includes EXIF-based orientation. | ||
* See {@link withMetadata} for control over this. | ||
* See {@link #withmetadata|withMetadata} for control over this. | ||
* | ||
* The caller is responsible for ensuring directory structures and permissions exist. | ||
* | ||
* A `Promise` is returned when `callback` is not provided. | ||
@@ -50,2 +69,4 @@ * | ||
* When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. | ||
* When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region. | ||
* May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. | ||
* @returns {Promise<Object>} - when no callback is provided | ||
@@ -58,6 +79,6 @@ * @throws {Error} Invalid parameters | ||
err = new Error('Missing output file path'); | ||
} else if (this.options.input.file === fileOut) { | ||
} else if (is.string(this.options.input.file) && path.resolve(this.options.input.file) === path.resolve(fileOut)) { | ||
err = new Error('Cannot use same file for input and output'); | ||
} else if (this.options.formatOut === 'input' && fileOut.toLowerCase().endsWith('.gif') && !this.constructor.format.magick.output.file) { | ||
err = errMagickSave; | ||
} else if (jp2Regex.test(path.extname(fileOut)) && !this.constructor.format.jp2k.output.file) { | ||
err = errJp2Save(); | ||
} | ||
@@ -79,8 +100,10 @@ if (err) { | ||
* Write output to a Buffer. | ||
* JPEG, PNG, WebP, AVIF, TIFF and raw pixel data output are supported. | ||
* JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported. | ||
* | ||
* If no explicit format is set, the output format will match the input image, except GIF and SVG input which become PNG output. | ||
* Use {@link #toformat|toFormat} or one of the format-specific functions such as {@link jpeg}, {@link png} etc. to set the output format. | ||
* | ||
* If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output. | ||
* | ||
* By default all metadata will be removed, which includes EXIF-based orientation. | ||
* See {@link withMetadata} for control over this. | ||
* See {@link #withmetadata|withMetadata} for control over this. | ||
* | ||
@@ -93,2 +116,3 @@ * `callback`, if present, gets three arguments `(err, data, info)` where: | ||
* When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. | ||
* May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. | ||
* | ||
@@ -109,2 +133,3 @@ * A `Promise` is returned when `callback` is not provided. | ||
* sharp(input) | ||
* .png() | ||
* .toBuffer({ resolveWithObject: true }) | ||
@@ -115,6 +140,6 @@ * .then(({ data, info }) => { ... }) | ||
* @example | ||
* const data = await sharp('my-image.jpg') | ||
* const { data, info } = await sharp('my-image.jpg') | ||
* // output the raw pixels | ||
* .raw() | ||
* .toBuffer(); | ||
* .toBuffer({ resolveWithObject: true }); | ||
* | ||
@@ -127,3 +152,5 @@ * // create a more type safe way to work with the raw pixel data | ||
* // When you are done changing the pixelArray, sharp takes the `pixelArray` as an input | ||
* await sharp(pixelArray).toFile('my-changed-image.jpg'); | ||
* const { width, height, channels } = info; | ||
* await sharp(pixelArray, { raw: { width, height, channels } }) | ||
* .toFile('my-changed-image.jpg'); | ||
* | ||
@@ -141,2 +168,3 @@ * @param {Object} [options] | ||
} | ||
this.options.fileOut = ''; | ||
return this._pipeline(is.fn(options) ? options : callback); | ||
@@ -147,4 +175,4 @@ } | ||
* Include all metadata (EXIF, XMP, IPTC) from the input image in the output image. | ||
* This will also convert to and add a web-friendly sRGB ICC profile unless a custom | ||
* output profile is provided. | ||
* This will also convert to and add a web-friendly sRGB ICC profile if appropriate, | ||
* unless a custom output profile is provided. | ||
* | ||
@@ -154,2 +182,4 @@ * The default behaviour, when `withMetadata` is not used, is to convert to the device-independent | ||
* | ||
* EXIF metadata is unsupported for TIFF output. | ||
* | ||
* @example | ||
@@ -161,5 +191,31 @@ * sharp('input.jpg') | ||
* | ||
* @example | ||
* // Set output EXIF metadata | ||
* const data = await sharp(input) | ||
* .withMetadata({ | ||
* exif: { | ||
* IFD0: { | ||
* Copyright: 'The National Gallery' | ||
* }, | ||
* IFD3: { | ||
* GPSLatitudeRef: 'N', | ||
* GPSLatitude: '51/1 30/1 3230/100', | ||
* GPSLongitudeRef: 'W', | ||
* GPSLongitude: '0/1 7/1 4366/100' | ||
* } | ||
* } | ||
* }) | ||
* .toBuffer(); | ||
* | ||
* @example | ||
* // Set output metadata to 96 DPI | ||
* const data = await sharp(input) | ||
* .withMetadata({ density: 96 }) | ||
* .toBuffer(); | ||
* | ||
* @param {Object} [options] | ||
* @param {number} [options.orientation] value between 1 and 8, used to update the EXIF `Orientation` tag. | ||
* @param {string} [options.icc] filesystem path to output ICC profile, defaults to sRGB. | ||
* @param {string} [options.icc='srgb'] Filesystem path to output ICC profile, relative to `process.cwd()`, defaults to built-in sRGB. | ||
* @param {Object<Object>} [options.exif={}] Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. | ||
* @param {number} [options.density] Number of pixels per inch (DPI). | ||
* @returns {Sharp} | ||
@@ -178,2 +234,9 @@ * @throws {Error} Invalid parameters | ||
} | ||
if (is.defined(options.density)) { | ||
if (is.number(options.density) && options.density > 0) { | ||
this.options.withMetadataDensity = options.density; | ||
} else { | ||
throw is.invalidParameterError('density', 'positive number', options.density); | ||
} | ||
} | ||
if (is.defined(options.icc)) { | ||
@@ -186,2 +249,21 @@ if (is.string(options.icc)) { | ||
} | ||
if (is.defined(options.exif)) { | ||
if (is.object(options.exif)) { | ||
for (const [ifd, entries] of Object.entries(options.exif)) { | ||
if (is.object(entries)) { | ||
for (const [k, v] of Object.entries(entries)) { | ||
if (is.string(v)) { | ||
this.options.withMetadataStrs[`exif-${ifd.toLowerCase()}-${k}`] = v; | ||
} else { | ||
throw is.invalidParameterError(`exif.${ifd}.${k}`, 'string', v); | ||
} | ||
} | ||
} else { | ||
throw is.invalidParameterError(`exif.${ifd}`, 'object', entries); | ||
} | ||
} | ||
} else { | ||
throw is.invalidParameterError('exif', 'object', options.exif); | ||
} | ||
} | ||
} | ||
@@ -216,4 +298,2 @@ return this; | ||
* | ||
* Some of these options require the use of a globally-installed libvips compiled with support for mozjpeg. | ||
* | ||
* @example | ||
@@ -228,2 +308,8 @@ * // Convert any input to very high quality JPEG output | ||
* | ||
* @example | ||
* // Use mozjpeg to reduce output JPEG file size (slower) | ||
* const data = await sharp(input) | ||
* .jpeg({ mozjpeg: true }) | ||
* .toBuffer(); | ||
* | ||
* @param {Object} [options] - output options | ||
@@ -235,8 +321,9 @@ * @param {number} [options.quality=80] - quality, integer 1-100 | ||
* @param {boolean} [options.optimizeCoding=true] - alternative spelling of optimiseCoding | ||
* @param {boolean} [options.trellisQuantisation=false] - apply trellis quantisation, requires libvips compiled with support for mozjpeg | ||
* @param {boolean} [options.overshootDeringing=false] - apply overshoot deringing, requires libvips compiled with support for mozjpeg | ||
* @param {boolean} [options.optimiseScans=false] - optimise progressive scans, forces progressive, requires libvips compiled with support for mozjpeg | ||
* @param {boolean} [options.optimizeScans=false] - alternative spelling of optimiseScans, requires libvips compiled with support for mozjpeg | ||
* @param {number} [options.quantisationTable=0] - quantization table to use, integer 0-8, requires libvips compiled with support for mozjpeg | ||
* @param {number} [options.quantizationTable=0] - alternative spelling of quantisationTable, requires libvips compiled with support for mozjpeg | ||
* @param {boolean} [options.mozjpeg=false] - use mozjpeg defaults, equivalent to `{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }` | ||
* @param {boolean} [options.trellisQuantisation=false] - apply trellis quantisation | ||
* @param {boolean} [options.overshootDeringing=false] - apply overshoot deringing | ||
* @param {boolean} [options.optimiseScans=false] - optimise progressive scans, forces progressive | ||
* @param {boolean} [options.optimizeScans=false] - alternative spelling of optimiseScans | ||
* @param {number} [options.quantisationTable=0] - quantization table to use, integer 0-8 | ||
* @param {number} [options.quantizationTable=0] - alternative spelling of quantisationTable | ||
* @param {boolean} [options.force=true] - force JPEG output, otherwise attempt to use input format | ||
@@ -265,2 +352,19 @@ * @returns {Sharp} | ||
} | ||
const optimiseCoding = is.bool(options.optimizeCoding) ? options.optimizeCoding : options.optimiseCoding; | ||
if (is.defined(optimiseCoding)) { | ||
this._setBooleanOption('jpegOptimiseCoding', optimiseCoding); | ||
} | ||
if (is.defined(options.mozjpeg)) { | ||
if (is.bool(options.mozjpeg)) { | ||
if (options.mozjpeg) { | ||
this.options.jpegTrellisQuantisation = true; | ||
this.options.jpegOvershootDeringing = true; | ||
this.options.jpegOptimiseScans = true; | ||
this.options.jpegProgressive = true; | ||
this.options.jpegQuantisationTable = 3; | ||
} | ||
} else { | ||
throw is.invalidParameterError('mozjpeg', 'boolean', options.mozjpeg); | ||
} | ||
} | ||
const trellisQuantisation = is.bool(options.trellisQuantization) ? options.trellisQuantization : options.trellisQuantisation; | ||
@@ -280,6 +384,2 @@ if (is.defined(trellisQuantisation)) { | ||
} | ||
const optimiseCoding = is.bool(options.optimizeCoding) ? options.optimizeCoding : options.optimiseCoding; | ||
if (is.defined(optimiseCoding)) { | ||
this._setBooleanOption('jpegOptimiseCoding', optimiseCoding); | ||
} | ||
const quantisationTable = is.number(options.quantizationTable) ? options.quantizationTable : options.quantisationTable; | ||
@@ -300,9 +400,8 @@ if (is.defined(quantisationTable)) { | ||
* | ||
* PNG output is always full colour at 8 or 16 bits per pixel. | ||
* By default, PNG output is full colour at 8 or 16 bits per pixel. | ||
* Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel. | ||
* Set `palette` to `true` for slower, indexed PNG output. | ||
* | ||
* Some of these options require the use of a globally-installed libvips compiled with support for libimagequant (GPL). | ||
* | ||
* @example | ||
* // Convert any input to PNG output | ||
* // Convert any input to full colour PNG output | ||
* const data = await sharp(input) | ||
@@ -312,11 +411,18 @@ * .png() | ||
* | ||
* @example | ||
* // Convert any input to indexed PNG output (slower) | ||
* const data = await sharp(input) | ||
* .png({ palette: true }) | ||
* .toBuffer(); | ||
* | ||
* @param {Object} [options] | ||
* @param {boolean} [options.progressive=false] - use progressive (interlace) scan | ||
* @param {number} [options.compressionLevel=9] - zlib compression level, 0-9 | ||
* @param {number} [options.compressionLevel=6] - zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest) | ||
* @param {boolean} [options.adaptiveFiltering=false] - use adaptive row filtering | ||
* @param {boolean} [options.palette=false] - quantise to a palette-based image with alpha transparency support, requires libvips compiled with support for libimagequant | ||
* @param {number} [options.quality=100] - use the lowest number of colours needed to achieve given quality, sets `palette` to `true`, requires libvips compiled with support for libimagequant | ||
* @param {number} [options.colours=256] - maximum number of palette entries, sets `palette` to `true`, requires libvips compiled with support for libimagequant | ||
* @param {number} [options.colors=256] - alternative spelling of `options.colours`, sets `palette` to `true`, requires libvips compiled with support for libimagequant | ||
* @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, sets `palette` to `true`, requires libvips compiled with support for libimagequant | ||
* @param {boolean} [options.palette=false] - quantise to a palette-based image with alpha transparency support | ||
* @param {number} [options.quality=100] - use the lowest number of colours needed to achieve given quality, sets `palette` to `true` | ||
* @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest), sets `palette` to `true` | ||
* @param {number} [options.colours=256] - maximum number of palette entries, sets `palette` to `true` | ||
* @param {number} [options.colors=256] - alternative spelling of `options.colours`, sets `palette` to `true` | ||
* @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, sets `palette` to `true` | ||
* @param {boolean} [options.force=true] - force PNG output, otherwise attempt to use input format | ||
@@ -341,5 +447,13 @@ * @returns {Sharp} | ||
} | ||
const colours = options.colours || options.colors; | ||
if (is.defined(colours)) { | ||
if (is.integer(colours) && is.inRange(colours, 2, 256)) { | ||
this.options.pngBitdepth = bitdepthFromColourCount(colours); | ||
} else { | ||
throw is.invalidParameterError('colours', 'integer between 2 and 256', colours); | ||
} | ||
} | ||
if (is.defined(options.palette)) { | ||
this._setBooleanOption('pngPalette', options.palette); | ||
} else if (is.defined(options.quality) || is.defined(options.colours || options.colors) || is.defined(options.dither)) { | ||
} else if ([options.quality, options.effort, options.colours, options.colors, options.dither].some(is.defined)) { | ||
this._setBooleanOption('pngPalette', true); | ||
@@ -355,8 +469,7 @@ } | ||
} | ||
const colours = options.colours || options.colors; | ||
if (is.defined(colours)) { | ||
if (is.integer(colours) && is.inRange(colours, 2, 256)) { | ||
this.options.pngColours = colours; | ||
if (is.defined(options.effort)) { | ||
if (is.integer(options.effort) && is.inRange(options.effort, 1, 10)) { | ||
this.options.pngEffort = options.effort; | ||
} else { | ||
throw is.invalidParameterError('colours', 'integer between 2 and 256', colours); | ||
throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort); | ||
} | ||
@@ -385,2 +498,8 @@ } | ||
* | ||
* @example | ||
* // Optimise the file size of an animated WebP | ||
* const outputWebp = await sharp(inputWebp, { animated: true }) | ||
* .webp({ effort: 6 }) | ||
* .toBuffer(); | ||
* | ||
* @param {Object} [options] - output options | ||
@@ -392,6 +511,8 @@ * @param {number} [options.quality=80] - quality, integer 1-100 | ||
* @param {boolean} [options.smartSubsample=false] - use high quality chroma subsampling | ||
* @param {number} [options.reductionEffort=4] - level of CPU effort to reduce file size, integer 0-6 | ||
* @param {number} [options.pageHeight] - page height for animated output | ||
* @param {string} [options.preset='default'] - named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text | ||
* @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 6 (slowest) | ||
* @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation | ||
* @param {number[]} [options.delay] - list of delays between animation frames (in milliseconds) | ||
* @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds) | ||
* @param {boolean} [options.minSize=false] - prevent use of animation key frames to minimise file size (slow) | ||
* @param {boolean} [options.mixed=false] - allow mixture of lossy and lossless animation frames (slow) | ||
* @param {boolean} [options.force=true] - force WebP output, otherwise attempt to use input format | ||
@@ -402,33 +523,47 @@ * @returns {Sharp} | ||
function webp (options) { | ||
if (is.object(options) && is.defined(options.quality)) { | ||
if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { | ||
this.options.webpQuality = options.quality; | ||
} else { | ||
throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); | ||
if (is.object(options)) { | ||
if (is.defined(options.quality)) { | ||
if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { | ||
this.options.webpQuality = options.quality; | ||
} else { | ||
throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); | ||
} | ||
} | ||
} | ||
if (is.object(options) && is.defined(options.alphaQuality)) { | ||
if (is.integer(options.alphaQuality) && is.inRange(options.alphaQuality, 0, 100)) { | ||
this.options.webpAlphaQuality = options.alphaQuality; | ||
} else { | ||
throw is.invalidParameterError('alphaQuality', 'integer between 0 and 100', options.alphaQuality); | ||
if (is.defined(options.alphaQuality)) { | ||
if (is.integer(options.alphaQuality) && is.inRange(options.alphaQuality, 0, 100)) { | ||
this.options.webpAlphaQuality = options.alphaQuality; | ||
} else { | ||
throw is.invalidParameterError('alphaQuality', 'integer between 0 and 100', options.alphaQuality); | ||
} | ||
} | ||
} | ||
if (is.object(options) && is.defined(options.lossless)) { | ||
this._setBooleanOption('webpLossless', options.lossless); | ||
} | ||
if (is.object(options) && is.defined(options.nearLossless)) { | ||
this._setBooleanOption('webpNearLossless', options.nearLossless); | ||
} | ||
if (is.object(options) && is.defined(options.smartSubsample)) { | ||
this._setBooleanOption('webpSmartSubsample', options.smartSubsample); | ||
} | ||
if (is.object(options) && is.defined(options.reductionEffort)) { | ||
if (is.integer(options.reductionEffort) && is.inRange(options.reductionEffort, 0, 6)) { | ||
this.options.webpReductionEffort = options.reductionEffort; | ||
} else { | ||
throw is.invalidParameterError('reductionEffort', 'integer between 0 and 6', options.reductionEffort); | ||
if (is.defined(options.lossless)) { | ||
this._setBooleanOption('webpLossless', options.lossless); | ||
} | ||
if (is.defined(options.nearLossless)) { | ||
this._setBooleanOption('webpNearLossless', options.nearLossless); | ||
} | ||
if (is.defined(options.smartSubsample)) { | ||
this._setBooleanOption('webpSmartSubsample', options.smartSubsample); | ||
} | ||
if (is.defined(options.preset)) { | ||
if (is.string(options.preset) && is.inArray(options.preset, ['default', 'photo', 'picture', 'drawing', 'icon', 'text'])) { | ||
this.options.webpPreset = options.preset; | ||
} else { | ||
throw is.invalidParameterError('preset', 'one of: default, photo, picture, drawing, icon, text', options.preset); | ||
} | ||
} | ||
if (is.defined(options.effort)) { | ||
if (is.integer(options.effort) && is.inRange(options.effort, 0, 6)) { | ||
this.options.webpEffort = options.effort; | ||
} else { | ||
throw is.invalidParameterError('effort', 'integer between 0 and 6', options.effort); | ||
} | ||
} | ||
if (is.defined(options.minSize)) { | ||
this._setBooleanOption('webpMinSize', options.minSize); | ||
} | ||
if (is.defined(options.mixed)) { | ||
this._setBooleanOption('webpMixed', options.mixed); | ||
} | ||
} | ||
trySetAnimationOptions(options, this.options); | ||
@@ -439,12 +574,45 @@ return this._updateFormatOut('webp', options); | ||
/** | ||
* Use these GIF options for output image. | ||
* Use these GIF options for the output image. | ||
* | ||
* Requires libvips compiled with support for ImageMagick or GraphicsMagick. | ||
* The prebuilt binaries do not include this - see | ||
* {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}. | ||
* The first entry in the palette is reserved for transparency. | ||
* | ||
* The palette of the input image will be re-used if possible. | ||
* | ||
* @since 0.30.0 | ||
* | ||
* @example | ||
* // Convert PNG to GIF | ||
* await sharp(pngBuffer) | ||
* .gif() | ||
* .toBuffer(); | ||
* | ||
* @example | ||
* // Convert animated WebP to animated GIF | ||
* await sharp('animated.webp', { animated: true }) | ||
* .toFile('animated.gif'); | ||
* | ||
* @example | ||
* // Create a 128x128, cropped, non-dithered, animated thumbnail of an animated GIF | ||
* const out = await sharp('in.gif', { animated: true }) | ||
* .resize({ width: 128, height: 128 }) | ||
* .gif({ dither: 0 }) | ||
* .toBuffer(); | ||
* | ||
* @example | ||
* // Lossy file size reduction of animated GIF | ||
* await sharp('in.gif', { animated: true }) | ||
* .gif({ interFrameMaxError: 8 }) | ||
* .toFile('optim.gif'); | ||
* | ||
* @param {Object} [options] - output options | ||
* @param {number} [options.pageHeight] - page height for animated output | ||
* @param {boolean} [options.reuse=true] - re-use existing palette, otherwise generate new (slow) | ||
* @param {boolean} [options.progressive=false] - use progressive (interlace) scan | ||
* @param {number} [options.colours=256] - maximum number of palette entries, including transparency, between 2 and 256 | ||
* @param {number} [options.colors=256] - alternative spelling of `options.colours` | ||
* @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest) | ||
* @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) | ||
* @param {number} [options.interFrameMaxError=0] - maximum inter-frame error for transparency, between 0 (lossless) and 32 | ||
* @param {number} [options.interPaletteMaxError=3] - maximum inter-palette error for palette reuse, between 0 and 256 | ||
* @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation | ||
* @param {number[]} [options.delay] - list of delays between animation frames (in milliseconds) | ||
* @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds) | ||
* @param {boolean} [options.force=true] - force GIF output, otherwise attempt to use input format | ||
@@ -454,6 +622,46 @@ * @returns {Sharp} | ||
*/ | ||
/* istanbul ignore next */ | ||
function gif (options) { | ||
if (!this.constructor.format.magick.output.buffer) { | ||
throw errMagickSave; | ||
if (is.object(options)) { | ||
if (is.defined(options.reuse)) { | ||
this._setBooleanOption('gifReuse', options.reuse); | ||
} | ||
if (is.defined(options.progressive)) { | ||
this._setBooleanOption('gifProgressive', options.progressive); | ||
} | ||
const colours = options.colours || options.colors; | ||
if (is.defined(colours)) { | ||
if (is.integer(colours) && is.inRange(colours, 2, 256)) { | ||
this.options.gifBitdepth = bitdepthFromColourCount(colours); | ||
} else { | ||
throw is.invalidParameterError('colours', 'integer between 2 and 256', colours); | ||
} | ||
} | ||
if (is.defined(options.effort)) { | ||
if (is.number(options.effort) && is.inRange(options.effort, 1, 10)) { | ||
this.options.gifEffort = options.effort; | ||
} else { | ||
throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort); | ||
} | ||
} | ||
if (is.defined(options.dither)) { | ||
if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) { | ||
this.options.gifDither = options.dither; | ||
} else { | ||
throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither); | ||
} | ||
} | ||
if (is.defined(options.interFrameMaxError)) { | ||
if (is.number(options.interFrameMaxError) && is.inRange(options.interFrameMaxError, 0, 32)) { | ||
this.options.gifInterFrameMaxError = options.interFrameMaxError; | ||
} else { | ||
throw is.invalidParameterError('interFrameMaxError', 'number between 0.0 and 32.0', options.interFrameMaxError); | ||
} | ||
} | ||
if (is.defined(options.interPaletteMaxError)) { | ||
if (is.number(options.interPaletteMaxError) && is.inRange(options.interPaletteMaxError, 0, 256)) { | ||
this.options.gifInterPaletteMaxError = options.interPaletteMaxError; | ||
} else { | ||
throw is.invalidParameterError('interPaletteMaxError', 'number between 0.0 and 256.0', options.interPaletteMaxError); | ||
} | ||
} | ||
} | ||
@@ -464,3 +672,81 @@ trySetAnimationOptions(options, this.options); | ||
/* istanbul ignore next */ | ||
/** | ||
* Use these JP2 options for output image. | ||
* | ||
* Requires libvips compiled with support for OpenJPEG. | ||
* The prebuilt binaries do not include this - see | ||
* {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}. | ||
* | ||
* @example | ||
* // Convert any input to lossless JP2 output | ||
* const data = await sharp(input) | ||
* .jp2({ lossless: true }) | ||
* .toBuffer(); | ||
* | ||
* @example | ||
* // Convert any input to very high quality JP2 output | ||
* const data = await sharp(input) | ||
* .jp2({ | ||
* quality: 100, | ||
* chromaSubsampling: '4:4:4' | ||
* }) | ||
* .toBuffer(); | ||
* | ||
* @since 0.29.1 | ||
* | ||
* @param {Object} [options] - output options | ||
* @param {number} [options.quality=80] - quality, integer 1-100 | ||
* @param {boolean} [options.lossless=false] - use lossless compression mode | ||
* @param {number} [options.tileWidth=512] - horizontal tile size | ||
* @param {number} [options.tileHeight=512] - vertical tile size | ||
* @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling | ||
* @returns {Sharp} | ||
* @throws {Error} Invalid options | ||
*/ | ||
function jp2 (options) { | ||
if (!this.constructor.format.jp2k.output.buffer) { | ||
throw errJp2Save(); | ||
} | ||
if (is.object(options)) { | ||
if (is.defined(options.quality)) { | ||
if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { | ||
this.options.jp2Quality = options.quality; | ||
} else { | ||
throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); | ||
} | ||
} | ||
if (is.defined(options.lossless)) { | ||
if (is.bool(options.lossless)) { | ||
this.options.jp2Lossless = options.lossless; | ||
} else { | ||
throw is.invalidParameterError('lossless', 'boolean', options.lossless); | ||
} | ||
} | ||
if (is.defined(options.tileWidth)) { | ||
if (is.integer(options.tileWidth) && is.inRange(options.tileWidth, 1, 32768)) { | ||
this.options.jp2TileWidth = options.tileWidth; | ||
} else { | ||
throw is.invalidParameterError('tileWidth', 'integer between 1 and 32768', options.tileWidth); | ||
} | ||
} | ||
if (is.defined(options.tileHeight)) { | ||
if (is.integer(options.tileHeight) && is.inRange(options.tileHeight, 1, 32768)) { | ||
this.options.jp2TileHeight = options.tileHeight; | ||
} else { | ||
throw is.invalidParameterError('tileHeight', 'integer between 1 and 32768', options.tileHeight); | ||
} | ||
} | ||
if (is.defined(options.chromaSubsampling)) { | ||
if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) { | ||
this.options.jp2ChromaSubsampling = options.chromaSubsampling; | ||
} else { | ||
throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling); | ||
} | ||
} | ||
} | ||
return this._updateFormatOut('jp2', options); | ||
} | ||
/** | ||
* Set animation options if available. | ||
@@ -470,3 +756,2 @@ * @private | ||
* @param {Object} [source] - output options | ||
* @param {number} [source.pageHeight] - page height for animated output | ||
* @param {number} [source.loop=0] - number of animation iterations, use 0 for infinite animation | ||
@@ -478,9 +763,2 @@ * @param {number[]} [source.delay] - list of delays between animation frames (in milliseconds) | ||
function trySetAnimationOptions (source, target) { | ||
if (is.object(source) && is.defined(source.pageHeight)) { | ||
if (is.integer(source.pageHeight) && source.pageHeight > 0) { | ||
target.pageHeight = source.pageHeight; | ||
} else { | ||
throw is.invalidParameterError('pageHeight', 'integer larger than 0', source.pageHeight); | ||
} | ||
} | ||
if (is.object(source) && is.defined(source.loop)) { | ||
@@ -494,3 +772,6 @@ if (is.integer(source.loop) && is.inRange(source.loop, 0, 65535)) { | ||
if (is.object(source) && is.defined(source.delay)) { | ||
if ( | ||
// We allow singular values as well | ||
if (is.integer(source.delay) && is.inRange(source.delay, 0, 65535)) { | ||
target.delay = [source.delay]; | ||
} else if ( | ||
Array.isArray(source.delay) && | ||
@@ -501,3 +782,3 @@ source.delay.every(is.integer) && | ||
} else { | ||
throw is.invalidParameterError('delay', 'array of integers between 0 and 65535', source.delay); | ||
throw is.invalidParameterError('delay', 'integer or an array of integers between 0 and 65535', source.delay); | ||
} | ||
@@ -510,2 +791,5 @@ } | ||
* | ||
* The `density` can be set in pixels/inch via {@link #withmetadata|withMetadata} | ||
* instead of providing `xres` and `yres` in pixels/mm. | ||
* | ||
* @example | ||
@@ -524,3 +808,3 @@ * // Convert SVG input to LZW-compressed, 1 bit per pixel TIFF output | ||
* @param {boolean} [options.force=true] - force TIFF output, otherwise attempt to use input format | ||
* @param {string} [options.compression='jpeg'] - compression options: lzw, deflate, jpeg, ccittfax4 | ||
* @param {string} [options.compression='jpeg'] - compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k | ||
* @param {string} [options.predictor='horizontal'] - compression predictor options: none, horizontal, float | ||
@@ -533,2 +817,3 @@ * @param {boolean} [options.pyramid=false] - write an image pyramid | ||
* @param {number} [options.yres=1.0] - vertical resolution in pixels/mm | ||
* @param {string} [options.resolutionUnit='inch'] - resolution unit options: inch, cm | ||
* @param {number} [options.bitdepth=8] - reduce bitdepth to 1, 2 or 4 bit | ||
@@ -593,6 +878,6 @@ * @returns {Sharp} | ||
if (is.defined(options.compression)) { | ||
if (is.string(options.compression) && is.inArray(options.compression, ['lzw', 'deflate', 'jpeg', 'ccittfax4', 'none'])) { | ||
if (is.string(options.compression) && is.inArray(options.compression, ['none', 'jpeg', 'deflate', 'packbits', 'ccittfax4', 'lzw', 'webp', 'zstd', 'jp2k'])) { | ||
this.options.tiffCompression = options.compression; | ||
} else { | ||
throw is.invalidParameterError('compression', 'one of: lzw, deflate, jpeg, ccittfax4, none', options.compression); | ||
throw is.invalidParameterError('compression', 'one of: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k', options.compression); | ||
} | ||
@@ -608,2 +893,10 @@ } | ||
} | ||
// resolutionUnit | ||
if (is.defined(options.resolutionUnit)) { | ||
if (is.string(options.resolutionUnit) && is.inArray(options.resolutionUnit, ['inch', 'cm'])) { | ||
this.options.tiffResolutionUnit = options.resolutionUnit; | ||
} else { | ||
throw is.invalidParameterError('resolutionUnit', 'one of: inch, cm', options.resolutionUnit); | ||
} | ||
} | ||
} | ||
@@ -619,2 +912,14 @@ return this._updateFormatOut('tiff', options); | ||
* | ||
* AVIF image sequences are not supported. | ||
* | ||
* @example | ||
* const data = await sharp(input) | ||
* .avif({ effort: 2 }) | ||
* .toBuffer(); | ||
* | ||
* @example | ||
* const data = await sharp(input) | ||
* .avif({ lossless: true }) | ||
* .toBuffer(); | ||
* | ||
* @since 0.27.0 | ||
@@ -625,4 +930,4 @@ * | ||
* @param {boolean} [options.lossless=false] - use lossless compression | ||
* @param {number} [options.speed=5] - CPU effort vs file size, 0 (slowest/smallest) to 8 (fastest/largest) | ||
* @param {string} [options.chromaSubsampling='4:2:0'] - set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling, requires libvips v8.11.0 | ||
* @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest) | ||
* @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling | ||
* @returns {Sharp} | ||
@@ -638,5 +943,10 @@ * @throws {Error} Invalid options | ||
* | ||
* Support for patent-encumbered HEIC images requires the use of a | ||
* Support for patent-encumbered HEIC images using `hevc` compression requires the use of a | ||
* globally-installed libvips compiled with support for libheif, libde265 and x265. | ||
* | ||
* @example | ||
* const data = await sharp(input) | ||
* .heif({ compression: 'hevc' }) | ||
* .toBuffer(); | ||
* | ||
* @since 0.23.0 | ||
@@ -648,4 +958,4 @@ * | ||
* @param {boolean} [options.lossless=false] - use lossless compression | ||
* @param {number} [options.speed=5] - CPU effort vs file size, 0 (slowest/smallest) to 8 (fastest/largest) | ||
* @param {string} [options.chromaSubsampling='4:2:0'] - set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling, requires libvips v8.11.0 | ||
* @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest) | ||
* @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling | ||
* @returns {Sharp} | ||
@@ -677,7 +987,7 @@ * @throws {Error} Invalid options | ||
} | ||
if (is.defined(options.speed)) { | ||
if (is.integer(options.speed) && is.inRange(options.speed, 0, 8)) { | ||
this.options.heifSpeed = options.speed; | ||
if (is.defined(options.effort)) { | ||
if (is.integer(options.effort) && is.inRange(options.effort, 0, 9)) { | ||
this.options.heifEffort = options.effort; | ||
} else { | ||
throw is.invalidParameterError('speed', 'integer between 0 and 8', options.speed); | ||
throw is.invalidParameterError('effort', 'integer between 0 and 9', options.effort); | ||
} | ||
@@ -697,3 +1007,68 @@ } | ||
/** | ||
* Force output to be raw, uncompressed, 8-bit unsigned integer (unit8) pixel data. | ||
* Use these JPEG-XL (JXL) options for output image. | ||
* | ||
* This feature is experimental, please do not use in production systems. | ||
* | ||
* Requires libvips compiled with support for libjxl. | ||
* The prebuilt binaries do not include this - see | ||
* {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}. | ||
* | ||
* Image metadata (EXIF, XMP) is unsupported. | ||
* | ||
* @since 0.31.3 | ||
* | ||
* @param {Object} [options] - output options | ||
* @param {number} [options.distance=1.0] - maximum encoding error, between 0 (highest quality) and 15 (lowest quality) | ||
* @param {number} [options.quality] - calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified | ||
* @param {number} [options.decodingTier=0] - target decode speed tier, between 0 (highest quality) and 4 (lowest quality) | ||
* @param {boolean} [options.lossless=false] - use lossless compression | ||
* @param {number} [options.effort=7] - CPU effort, between 3 (fastest) and 9 (slowest) | ||
* @returns {Sharp} | ||
* @throws {Error} Invalid options | ||
*/ | ||
function jxl (options) { | ||
if (is.object(options)) { | ||
if (is.defined(options.quality)) { | ||
if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { | ||
// https://github.com/libjxl/libjxl/blob/0aeea7f180bafd6893c1db8072dcb67d2aa5b03d/tools/cjxl_main.cc#L640-L644 | ||
this.options.jxlDistance = options.quality >= 30 | ||
? 0.1 + (100 - options.quality) * 0.09 | ||
: 53 / 3000 * options.quality * options.quality - 23 / 20 * options.quality + 25; | ||
} else { | ||
throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); | ||
} | ||
} else if (is.defined(options.distance)) { | ||
if (is.number(options.distance) && is.inRange(options.distance, 0, 15)) { | ||
this.options.jxlDistance = options.distance; | ||
} else { | ||
throw is.invalidParameterError('distance', 'number between 0.0 and 15.0', options.distance); | ||
} | ||
} | ||
if (is.defined(options.decodingTier)) { | ||
if (is.integer(options.decodingTier) && is.inRange(options.decodingTier, 0, 4)) { | ||
this.options.jxlDecodingTier = options.decodingTier; | ||
} else { | ||
throw is.invalidParameterError('decodingTier', 'integer between 0 and 4', options.decodingTier); | ||
} | ||
} | ||
if (is.defined(options.lossless)) { | ||
if (is.bool(options.lossless)) { | ||
this.options.jxlLossless = options.lossless; | ||
} else { | ||
throw is.invalidParameterError('lossless', 'boolean', options.lossless); | ||
} | ||
} | ||
if (is.defined(options.effort)) { | ||
if (is.integer(options.effort) && is.inRange(options.effort, 3, 9)) { | ||
this.options.jxlEffort = options.effort; | ||
} else { | ||
throw is.invalidParameterError('effort', 'integer between 3 and 9', options.effort); | ||
} | ||
} | ||
} | ||
return this._updateFormatOut('jxl', options); | ||
} | ||
/** | ||
* Force output to be raw, uncompressed pixel data. | ||
* Pixel ordering is left-to-right, top-to-bottom, without padding. | ||
@@ -703,3 +1078,3 @@ * Channel ordering will be RGB or RGBA for non-greyscale colourspaces. | ||
* @example | ||
* // Extract raw RGB pixel data from JPEG input | ||
* // Extract raw, unsigned 8-bit RGB pixel data from JPEG input | ||
* const { data, info } = await sharp('input.jpg') | ||
@@ -710,3 +1085,3 @@ * .raw() | ||
* @example | ||
* // Extract alpha channel as raw pixel data from PNG input | ||
* // Extract alpha channel as raw, unsigned 16-bit pixel data from PNG input | ||
* const data = await sharp('input.png') | ||
@@ -716,8 +1091,22 @@ * .ensureAlpha() | ||
* .toColourspace('b-w') | ||
* .raw() | ||
* .raw({ depth: 'ushort' }) | ||
* .toBuffer(); | ||
* | ||
* @param {Object} [options] - output options | ||
* @param {string} [options.depth='uchar'] - bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex | ||
* @returns {Sharp} | ||
* @throws {Error} Invalid options | ||
*/ | ||
function raw () { | ||
function raw (options) { | ||
if (is.object(options)) { | ||
if (is.defined(options.depth)) { | ||
if (is.string(options.depth) && is.inArray(options.depth, | ||
['char', 'uchar', 'short', 'ushort', 'int', 'uint', 'float', 'complex', 'double', 'dpcomplex'] | ||
)) { | ||
this.options.rawDepth = options.depth; | ||
} else { | ||
throw is.invalidParameterError('depth', 'one of: char, uchar, short, ushort, int, uint, float, complex, double, dpcomplex', options.depth); | ||
} | ||
} | ||
} | ||
return this._updateFormatOut('raw'); | ||
@@ -728,7 +1117,12 @@ } | ||
* Use tile-based deep zoom (image pyramid) output. | ||
* | ||
* Set the format and options for tile images via the `toFormat`, `jpeg`, `png` or `webp` functions. | ||
* Use a `.zip` or `.szi` file extension with `toFile` to write to a compressed archive file format. | ||
* | ||
* Warning: multiple sharp instances concurrently producing tile output can expose a possible race condition in some versions of libgsf. | ||
* The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`. | ||
* | ||
* Requires libvips compiled with support for libgsf. | ||
* The prebuilt binaries do not include this - see | ||
* {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}. | ||
* | ||
* @example | ||
@@ -745,2 +1139,13 @@ * sharp('input.tiff') | ||
* | ||
* @example | ||
* const zipFileWithTiles = await sharp(input) | ||
* .tile({ basename: "tiles" }) | ||
* .toBuffer(); | ||
* | ||
* @example | ||
* const iiififier = sharp().tile({ layout: "iiif" }); | ||
* readableStream | ||
* .pipe(iiififier) | ||
* .pipe(writeableStream); | ||
* | ||
* @param {Object} [options] | ||
@@ -754,5 +1159,7 @@ * @param {number} [options.size=256] tile size in pixels, a value between 1 and 8192. | ||
* @param {string} [options.container='fs'] tile container, with value `fs` (filesystem) or `zip` (compressed file). | ||
* @param {string} [options.layout='dz'] filesystem layout, possible values are `dz`, `iiif`, `zoomify` or `google`. | ||
* @param {string} [options.layout='dz'] filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`. | ||
* @param {boolean} [options.centre=false] centre image in tile. | ||
* @param {boolean} [options.center=false] alternative spelling of centre. | ||
* @param {string} [options.id='https://example.com/iiif'] when `layout` is `iiif`/`iiif3`, sets the `@id`/`id` attribute of `info.json` | ||
* @param {string} [options.basename] the name of the directory within the zip file when container is `zip`. | ||
* @returns {Sharp} | ||
@@ -792,6 +1199,6 @@ * @throws {Error} Invalid parameters | ||
if (is.defined(options.layout)) { | ||
if (is.string(options.layout) && is.inArray(options.layout, ['dz', 'google', 'iiif', 'zoomify'])) { | ||
if (is.string(options.layout) && is.inArray(options.layout, ['dz', 'google', 'iiif', 'iiif3', 'zoomify'])) { | ||
this.options.tileLayout = options.layout; | ||
} else { | ||
throw is.invalidParameterError('layout', 'one of: dz, google, iiif, zoomify', options.layout); | ||
throw is.invalidParameterError('layout', 'one of: dz, google, iiif, iiif3, zoomify', options.layout); | ||
} | ||
@@ -832,2 +1239,18 @@ } | ||
} | ||
// @id attribute for IIIF layout | ||
if (is.defined(options.id)) { | ||
if (is.string(options.id)) { | ||
this.options.tileId = options.id; | ||
} else { | ||
throw is.invalidParameterError('id', 'string', options.id); | ||
} | ||
} | ||
// Basename for zip container | ||
if (is.defined(options.basename)) { | ||
if (is.string(options.basename)) { | ||
this.options.tileBasename = options.basename; | ||
} else { | ||
throw is.invalidParameterError('basename', 'string', options.basename); | ||
} | ||
} | ||
} | ||
@@ -844,2 +1267,38 @@ // Format | ||
/** | ||
* Set a timeout for processing, in seconds. | ||
* Use a value of zero to continue processing indefinitely, the default behaviour. | ||
* | ||
* The clock starts when libvips opens an input image for processing. | ||
* Time spent waiting for a libuv thread to become available is not included. | ||
* | ||
* @example | ||
* // Ensure processing takes no longer than 3 seconds | ||
* try { | ||
* const data = await sharp(input) | ||
* .blur(1000) | ||
* .timeout({ seconds: 3 }) | ||
* .toBuffer(); | ||
* } catch (err) { | ||
* if (err.message.includes('timeout')) { ... } | ||
* } | ||
* | ||
* @since 0.29.2 | ||
* | ||
* @param {Object} options | ||
* @param {number} options.seconds - Number of seconds after which processing will be stopped | ||
* @returns {Sharp} | ||
*/ | ||
function timeout (options) { | ||
if (!is.plainObject(options)) { | ||
throw is.invalidParameterError('options', 'object', options); | ||
} | ||
if (is.integer(options.seconds) && is.inRange(options.seconds, 0, 3600)) { | ||
this.options.timeoutSeconds = options.seconds; | ||
} else { | ||
throw is.invalidParameterError('seconds', 'integer between 0 and 3600', options.seconds); | ||
} | ||
return this; | ||
} | ||
/** | ||
* Update the output format unless options.force is false, | ||
@@ -920,2 +1379,3 @@ * in which case revert to input format. | ||
this.push(null); | ||
this.on('end', () => this.emit('close')); | ||
}); | ||
@@ -936,2 +1396,3 @@ }); | ||
this.push(null); | ||
this.on('end', () => this.emit('close')); | ||
}); | ||
@@ -991,2 +1452,3 @@ } | ||
jpeg, | ||
jp2, | ||
png, | ||
@@ -997,5 +1459,7 @@ webp, | ||
heif, | ||
jxl, | ||
gif, | ||
raw, | ||
tile, | ||
timeout, | ||
// Private | ||
@@ -1002,0 +1466,0 @@ _updateFormatOut, |
@@ -0,1 +1,4 @@ | ||
// Copyright 2013 Lovell Fuller and others. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
'use strict'; | ||
@@ -10,6 +13,8 @@ | ||
const platform = env.npm_config_platform || process.platform; | ||
/* istanbul ignore next */ | ||
const libc = (platform === 'linux' && detectLibc.isNonGlibcLinux) ? detectLibc.family : ''; | ||
const libc = process.env.npm_config_libc || | ||
/* istanbul ignore next */ | ||
(detectLibc.isNonGlibcLinuxSync() ? detectLibc.familySync() : ''); | ||
const libcId = platform !== 'linux' || libc === detectLibc.GLIBC ? '' : libc; | ||
const platformId = [`${platform}${libc}`]; | ||
const platformId = [`${platform}${libcId}`]; | ||
@@ -16,0 +21,0 @@ if (arch === 'arm') { |
@@ -0,1 +1,4 @@ | ||
// Copyright 2013 Lovell Fuller and others. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
'use strict'; | ||
@@ -40,2 +43,14 @@ | ||
/** | ||
* How to extend the image. | ||
* @member | ||
* @private | ||
*/ | ||
const extendWith = { | ||
background: 'background', | ||
copy: 'copy', | ||
repeat: 'repeat', | ||
mirror: 'mirror' | ||
}; | ||
/** | ||
* Strategies for automagic cover behaviour. | ||
@@ -97,6 +112,13 @@ * @member | ||
/** | ||
* @private | ||
*/ | ||
function isResizeExpected (options) { | ||
return options.width !== -1 || options.height !== -1; | ||
} | ||
/** | ||
* Resize image to `width`, `height` or `width x height`. | ||
* | ||
* When both a `width` and `height` are provided, the possible methods by which the image should **fit** these are: | ||
* - `cover`: (default) Preserving aspect ratio, ensure the image covers both provided dimensions by cropping/clipping to fit. | ||
* - `cover`: (default) Preserving aspect ratio, attempt to ensure the image covers both provided dimensions by cropping/clipping to fit. | ||
* - `contain`: Preserving aspect ratio, contain within both provided dimensions using "letterboxing" where necessary. | ||
@@ -109,3 +131,5 @@ * - `fill`: Ignore the aspect ratio of the input and stretch to both provided dimensions. | ||
* | ||
* When using a `fit` of `cover` or `contain`, the default **position** is `centre`. Other options are: | ||
* <img alt="Examples of various values for the fit property when resizing" width="100%" style="aspect-ratio: 998/243" src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/api-resize-fit.svg"> | ||
* | ||
* When using a **fit** of `cover` or `contain`, the default **position** is `centre`. Other options are: | ||
* - `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`. | ||
@@ -129,2 +153,5 @@ * - `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`. | ||
* | ||
* Only one resize can occur per pipeline. | ||
* Previous calls to `resize` in the same pipeline will be ignored. | ||
* | ||
* @example | ||
@@ -190,2 +217,16 @@ * sharp(input) | ||
* @example | ||
* sharp(input) | ||
* .resize(200, 200, { | ||
* fit: sharp.fit.outside, | ||
* withoutReduction: true | ||
* }) | ||
* .toFormat('jpeg') | ||
* .toBuffer() | ||
* .then(function(outputBuffer) { | ||
* // outputBuffer contains JPEG image data | ||
* // of at least 200 pixels wide and 200 pixels high while maintaining aspect ratio | ||
* // and no smaller than the input image | ||
* }); | ||
* | ||
* @example | ||
* const scaleByHalf = await sharp(input) | ||
@@ -198,24 +239,28 @@ * .metadata() | ||
* | ||
* @param {number} [width] - pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height. | ||
* @param {number} [height] - pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width. | ||
* @param {number} [width] - How many pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height. | ||
* @param {number} [height] - How many pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width. | ||
* @param {Object} [options] | ||
* @param {String} [options.width] - alternative means of specifying `width`. If both are present this take priority. | ||
* @param {String} [options.height] - alternative means of specifying `height`. If both are present this take priority. | ||
* @param {String} [options.fit='cover'] - how the image should be resized to fit both provided dimensions, one of `cover`, `contain`, `fill`, `inside` or `outside`. | ||
* @param {String} [options.position='centre'] - position, gravity or strategy to use when `fit` is `cover` or `contain`. | ||
* @param {String|Object} [options.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour when using a `fit` of `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency. | ||
* @param {String} [options.kernel='lanczos3'] - the kernel to use for image reduction. | ||
* @param {Boolean} [options.withoutEnlargement=false] - do not enlarge if the width *or* height are already less than the specified dimensions, equivalent to GraphicsMagick's `>` geometry option. | ||
* @param {Boolean} [options.fastShrinkOnLoad=true] - take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern on some images. | ||
* @param {number} [options.width] - An alternative means of specifying `width`. If both are present this takes priority. | ||
* @param {number} [options.height] - An alternative means of specifying `height`. If both are present this takes priority. | ||
* @param {String} [options.fit='cover'] - How the image should be resized/cropped to fit the target dimension(s), one of `cover`, `contain`, `fill`, `inside` or `outside`. | ||
* @param {String} [options.position='centre'] - A position, gravity or strategy to use when `fit` is `cover` or `contain`. | ||
* @param {String|Object} [options.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency. | ||
* @param {String} [options.kernel='lanczos3'] - The kernel to use for image reduction. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load. | ||
* @param {Boolean} [options.withoutEnlargement=false] - Do not scale up if the width *or* height are already less than the target dimensions, equivalent to GraphicsMagick's `>` geometry option. This may result in output dimensions smaller than the target dimensions. | ||
* @param {Boolean} [options.withoutReduction=false] - Do not scale down if the width *or* height are already greater than the target dimensions, equivalent to GraphicsMagick's `<` geometry option. This may still result in a crop to reach the target dimensions. | ||
* @param {Boolean} [options.fastShrinkOnLoad=true] - Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern or round-down of an auto-scaled dimension. | ||
* @returns {Sharp} | ||
* @throws {Error} Invalid parameters | ||
*/ | ||
function resize (width, height, options) { | ||
if (is.defined(width)) { | ||
if (is.object(width) && !is.defined(options)) { | ||
options = width; | ||
} else if (is.integer(width) && width > 0) { | ||
this.options.width = width; | ||
function resize (widthOrOptions, height, options) { | ||
if (isResizeExpected(this.options)) { | ||
this.options.debuglog('ignoring previous resize options'); | ||
} | ||
if (is.defined(widthOrOptions)) { | ||
if (is.object(widthOrOptions) && !is.defined(options)) { | ||
options = widthOrOptions; | ||
} else if (is.integer(widthOrOptions) && widthOrOptions > 0) { | ||
this.options.width = widthOrOptions; | ||
} else { | ||
throw is.invalidParameterError('width', 'positive integer', width); | ||
throw is.invalidParameterError('width', 'positive integer', widthOrOptions); | ||
} | ||
@@ -285,2 +330,6 @@ } else { | ||
} | ||
// Without reduction | ||
if (is.defined(options.withoutReduction)) { | ||
this._setBooleanOption('withoutReduction', options.withoutReduction); | ||
} | ||
// Shrink on load | ||
@@ -291,2 +340,5 @@ if (is.defined(options.fastShrinkOnLoad)) { | ||
} | ||
if (isRotationExpected(this.options) && isResizeExpected(this.options)) { | ||
this.options.rotateBeforePreExtract = true; | ||
} | ||
return this; | ||
@@ -296,3 +348,4 @@ } | ||
/** | ||
* Extends/pads the edges of the image with the provided background colour. | ||
* Extend / pad / extrude one or more edges of the image with either | ||
* the provided background colour or pixels derived from the image. | ||
* This operation will always occur after resizing and extraction, if any. | ||
@@ -314,7 +367,26 @@ * | ||
* | ||
* @example | ||
* // Add a row of 10 red pixels to the bottom | ||
* sharp(input) | ||
* .extend({ | ||
* bottom: 10, | ||
* background: 'red' | ||
* }) | ||
* ... | ||
* | ||
* @example | ||
* // Extrude image by 8 pixels to the right, mirroring existing right hand edge | ||
* sharp(input) | ||
* .extend({ | ||
* right: 8, | ||
* background: 'mirror' | ||
* }) | ||
* ... | ||
* | ||
* @param {(number|Object)} extend - single pixel count to add to all edges or an Object with per-edge counts | ||
* @param {number} [extend.top] | ||
* @param {number} [extend.left] | ||
* @param {number} [extend.bottom] | ||
* @param {number} [extend.right] | ||
* @param {number} [extend.top=0] | ||
* @param {number} [extend.left=0] | ||
* @param {number} [extend.bottom=0] | ||
* @param {number} [extend.right=0] | ||
* @param {String} [extend.extendWith='background'] - populate new pixels using this method, one of: background, copy, repeat, mirror. | ||
* @param {String|Object} [extend.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency. | ||
@@ -330,14 +402,39 @@ * @returns {Sharp} | ||
this.options.extendRight = extend; | ||
} else if ( | ||
is.object(extend) && | ||
is.integer(extend.top) && extend.top >= 0 && | ||
is.integer(extend.bottom) && extend.bottom >= 0 && | ||
is.integer(extend.left) && extend.left >= 0 && | ||
is.integer(extend.right) && extend.right >= 0 | ||
) { | ||
this.options.extendTop = extend.top; | ||
this.options.extendBottom = extend.bottom; | ||
this.options.extendLeft = extend.left; | ||
this.options.extendRight = extend.right; | ||
} else if (is.object(extend)) { | ||
if (is.defined(extend.top)) { | ||
if (is.integer(extend.top) && extend.top >= 0) { | ||
this.options.extendTop = extend.top; | ||
} else { | ||
throw is.invalidParameterError('top', 'positive integer', extend.top); | ||
} | ||
} | ||
if (is.defined(extend.bottom)) { | ||
if (is.integer(extend.bottom) && extend.bottom >= 0) { | ||
this.options.extendBottom = extend.bottom; | ||
} else { | ||
throw is.invalidParameterError('bottom', 'positive integer', extend.bottom); | ||
} | ||
} | ||
if (is.defined(extend.left)) { | ||
if (is.integer(extend.left) && extend.left >= 0) { | ||
this.options.extendLeft = extend.left; | ||
} else { | ||
throw is.invalidParameterError('left', 'positive integer', extend.left); | ||
} | ||
} | ||
if (is.defined(extend.right)) { | ||
if (is.integer(extend.right) && extend.right >= 0) { | ||
this.options.extendRight = extend.right; | ||
} else { | ||
throw is.invalidParameterError('right', 'positive integer', extend.right); | ||
} | ||
} | ||
this._setBackgroundColourOption('extendBackground', extend.background); | ||
if (is.defined(extend.extendWith)) { | ||
if (is.string(extendWith[extend.extendWith])) { | ||
this.options.extendWith = extendWith[extend.extendWith]; | ||
} else { | ||
throw is.invalidParameterError('extendWith', 'one of: background, copy, repeat, mirror', extend.extendWith); | ||
} | ||
} | ||
} else { | ||
@@ -380,3 +477,6 @@ throw is.invalidParameterError('extend', 'integer or object', extend); | ||
function extract (options) { | ||
const suffix = this.options.width === -1 && this.options.height === -1 ? 'Pre' : 'Post'; | ||
const suffix = isResizeExpected(this.options) || this.options.widthPre !== -1 ? 'Post' : 'Pre'; | ||
if (this.options[`width${suffix}`] !== -1) { | ||
this.options.debuglog('ignoring previous extract options'); | ||
} | ||
['left', 'top', 'width', 'height'].forEach(function (name) { | ||
@@ -391,4 +491,6 @@ const value = options[name]; | ||
// Ensure existing rotation occurs before pre-resize extraction | ||
if (suffix === 'Pre' && isRotationExpected(this.options)) { | ||
this.options.rotateBeforePreExtract = true; | ||
if (isRotationExpected(this.options) && !isResizeExpected(this.options)) { | ||
if (this.options.widthPre === -1 || this.options.widthPost === -1) { | ||
this.options.rotateBeforePreExtract = true; | ||
} | ||
} | ||
@@ -399,21 +501,74 @@ return this; | ||
/** | ||
* Trim "boring" pixels from all edges that contain values similar to the top-left pixel. | ||
* Images consisting entirely of a single colour will calculate "boring" using the alpha channel, if any. | ||
* Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel. | ||
* | ||
* Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels. | ||
* | ||
* If the result of this operation would trim an image to nothing then no change is made. | ||
* | ||
* The `info` response Object, obtained from callback of `.toFile()` or `.toBuffer()`, | ||
* will contain `trimOffsetLeft` and `trimOffsetTop` properties. | ||
* | ||
* @param {number} [threshold=10] the allowed difference from the top-left pixel, a number greater than zero. | ||
* @example | ||
* // Trim pixels with a colour similar to that of the top-left pixel. | ||
* sharp(input) | ||
* .trim() | ||
* .toFile(output, function(err, info) { | ||
* ... | ||
* }); | ||
* @example | ||
* // Trim pixels with the exact same colour as that of the top-left pixel. | ||
* sharp(input) | ||
* .trim(0) | ||
* .toFile(output, function(err, info) { | ||
* ... | ||
* }); | ||
* @example | ||
* // Trim only pixels with a similar colour to red. | ||
* sharp(input) | ||
* .trim("#FF0000") | ||
* .toFile(output, function(err, info) { | ||
* ... | ||
* }); | ||
* @example | ||
* // Trim all "yellow-ish" pixels, being more lenient with the higher threshold. | ||
* sharp(input) | ||
* .trim({ | ||
* background: "yellow", | ||
* threshold: 42, | ||
* }) | ||
* .toFile(output, function(err, info) { | ||
* ... | ||
* }); | ||
* | ||
* @param {string|number|Object} trim - the specific background colour to trim, the threshold for doing so or an Object with both. | ||
* @param {string|Object} [trim.background='top-left pixel'] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel. | ||
* @param {number} [trim.threshold=10] - the allowed difference from the above colour, a positive number. | ||
* @returns {Sharp} | ||
* @throws {Error} Invalid parameters | ||
*/ | ||
function trim (threshold) { | ||
if (!is.defined(threshold)) { | ||
function trim (trim) { | ||
if (!is.defined(trim)) { | ||
this.options.trimThreshold = 10; | ||
} else if (is.number(threshold) && threshold > 0) { | ||
this.options.trimThreshold = threshold; | ||
} else if (is.string(trim)) { | ||
this._setBackgroundColourOption('trimBackground', trim); | ||
this.options.trimThreshold = 10; | ||
} else if (is.number(trim)) { | ||
if (trim >= 0) { | ||
this.options.trimThreshold = trim; | ||
} else { | ||
throw is.invalidParameterError('threshold', 'positive number', trim); | ||
} | ||
} else if (is.object(trim)) { | ||
this._setBackgroundColourOption('trimBackground', trim.background); | ||
if (!is.defined(trim.threshold)) { | ||
this.options.trimThreshold = 10; | ||
} else if (is.number(trim.threshold) && trim.threshold >= 0) { | ||
this.options.trimThreshold = trim.threshold; | ||
} else { | ||
throw is.invalidParameterError('threshold', 'positive number', trim); | ||
} | ||
} else { | ||
throw is.invalidParameterError('threshold', 'number greater than zero', threshold); | ||
throw is.invalidParameterError('trim', 'string, number or object', trim); | ||
} | ||
if (this.options.trimThreshold && isRotationExpected(this.options)) { | ||
if (isRotationExpected(this.options)) { | ||
this.options.rotateBeforePreExtract = true; | ||
@@ -420,0 +575,0 @@ } |
@@ -0,6 +1,14 @@ | ||
// Copyright 2013 Lovell Fuller and others. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
'use strict'; | ||
const fs = require('fs'); | ||
const path = require('path'); | ||
const events = require('events'); | ||
const detectLibc = require('detect-libc'); | ||
const is = require('./is'); | ||
const sharp = require('../build/Release/sharp.node'); | ||
const platformAndArch = require('./platform')(); | ||
const sharp = require('./sharp'); | ||
@@ -15,2 +23,6 @@ /** | ||
const format = sharp.format(); | ||
format.heif.output.alias = ['avif', 'heic']; | ||
format.jpeg.output.alias = ['jpe', 'jpg']; | ||
format.tiff.output.alias = ['tif']; | ||
format.jp2k.output.alias = ['j2c', 'j2k', 'jp2', 'jpx']; | ||
@@ -29,7 +41,7 @@ /** | ||
bicubic: 'bicubic', | ||
/** [LBB interpolation](https://github.com/jcupitt/libvips/blob/master/libvips/resample/lbb.cpp#L100). Prevents some "[acutance](http://en.wikipedia.org/wiki/Acutance)" but typically reduces performance by a factor of 2. */ | ||
/** [LBB interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100). Prevents some "[acutance](http://en.wikipedia.org/wiki/Acutance)" but typically reduces performance by a factor of 2. */ | ||
locallyBoundedBicubic: 'lbb', | ||
/** [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. */ | ||
nohalo: 'nohalo', | ||
/** [VSQBS interpolation](https://github.com/jcupitt/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents "staircasing" when enlarging. */ | ||
/** [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents "staircasing" when enlarging. */ | ||
vertexSplitQuadraticBasisSpline: 'vsqbs' | ||
@@ -39,3 +51,3 @@ }; | ||
/** | ||
* An Object containing the version numbers of libvips and its dependencies. | ||
* An Object containing the version numbers of sharp, libvips and its dependencies. | ||
* @member | ||
@@ -49,6 +61,22 @@ * @example | ||
try { | ||
versions = require(`../vendor/${versions.vips}/versions.json`); | ||
} catch (err) {} | ||
versions = require(`../vendor/${versions.vips}/${platformAndArch}/versions.json`); | ||
} catch (_err) { /* ignore */ } | ||
versions.sharp = require('../package.json').version; | ||
/** | ||
* An Object containing the platform and architecture | ||
* of the current and installed vendored binaries. | ||
* @member | ||
* @example | ||
* console.log(sharp.vendor); | ||
*/ | ||
const vendor = { | ||
current: platformAndArch, | ||
installed: [] | ||
}; | ||
try { | ||
vendor.installed = fs.readdirSync(path.join(__dirname, `../vendor/${versions.vips}`)); | ||
} catch (_err) { /* ignore */ } | ||
/** | ||
* Gets or, when options are provided, sets the limits of _libvips'_ operation cache. | ||
@@ -90,11 +118,28 @@ * Existing entries in the cache will be trimmed after any change in limits. | ||
* Gets or, when a concurrency is provided, sets | ||
* the number of threads _libvips'_ should create to process each image. | ||
* The default value is the number of CPU cores. | ||
* A value of `0` will reset to this default. | ||
* the maximum number of threads _libvips_ should use to process _each image_. | ||
* These are from a thread pool managed by glib, | ||
* which helps avoid the overhead of creating new threads. | ||
* | ||
* The maximum number of images that can be processed in parallel | ||
* is limited by libuv's `UV_THREADPOOL_SIZE` environment variable. | ||
* | ||
* This method always returns the current concurrency. | ||
* | ||
* The default value is the number of CPU cores, | ||
* except when using glibc-based Linux without jemalloc, | ||
* where the default is `1` to help reduce memory fragmentation. | ||
* | ||
* A value of `0` will reset this to the number of CPU cores. | ||
* | ||
* Some image format libraries spawn additional threads, | ||
* e.g. libaom manages its own 4 threads when encoding AVIF images, | ||
* and these are independent of the value set here. | ||
* | ||
* The maximum number of images that sharp can process in parallel | ||
* is controlled by libuv's `UV_THREADPOOL_SIZE` environment variable, | ||
* which defaults to 4. | ||
* | ||
* https://nodejs.org/api/cli.html#uv_threadpool_sizesize | ||
* | ||
* For example, by default, a machine with 8 CPU cores will process | ||
* 4 images in parallel and use up to 8 threads per image, | ||
* so there will be up to 32 concurrent threads. | ||
* | ||
* @example | ||
@@ -111,2 +156,7 @@ * const threads = sharp.concurrency(); // 4 | ||
} | ||
/* istanbul ignore next */ | ||
if (detectLibc.familySync() === detectLibc.GLIBC && !sharp._isUsingJemalloc()) { | ||
// Reduce default concurrency to 1 when using glibc memory allocator | ||
sharp.concurrency(1); | ||
} | ||
@@ -162,2 +212,68 @@ /** | ||
/** | ||
* Block libvips operations at runtime. | ||
* | ||
* This is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable, | ||
* which when set will block all "untrusted" operations. | ||
* | ||
* @since 0.32.4 | ||
* | ||
* @example <caption>Block all TIFF input.</caption> | ||
* sharp.block({ | ||
* operation: ['VipsForeignLoadTiff'] | ||
* }); | ||
* | ||
* @param {Object} options | ||
* @param {Array<string>} options.operation - List of libvips low-level operation names to block. | ||
*/ | ||
function block (options) { | ||
if (is.object(options)) { | ||
if (Array.isArray(options.operation) && options.operation.every(is.string)) { | ||
sharp.block(options.operation, true); | ||
} else { | ||
throw is.invalidParameterError('operation', 'Array<string>', options.operation); | ||
} | ||
} else { | ||
throw is.invalidParameterError('options', 'object', options); | ||
} | ||
} | ||
/** | ||
* Unblock libvips operations at runtime. | ||
* | ||
* This is useful for defining a list of allowed operations. | ||
* | ||
* @since 0.32.4 | ||
* | ||
* @example <caption>Block all input except WebP from the filesystem.</caption> | ||
* sharp.block({ | ||
* operation: ['VipsForeignLoad'] | ||
* }); | ||
* sharp.unblock({ | ||
* operation: ['VipsForeignLoadWebpFile'] | ||
* }); | ||
* | ||
* @example <caption>Block all input except JPEG and PNG from a Buffer or Stream.</caption> | ||
* sharp.block({ | ||
* operation: ['VipsForeignLoad'] | ||
* }); | ||
* sharp.unblock({ | ||
* operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer'] | ||
* }); | ||
* | ||
* @param {Object} options | ||
* @param {Array<string>} options.operation - List of libvips low-level operation names to unblock. | ||
*/ | ||
function unblock (options) { | ||
if (is.object(options)) { | ||
if (Array.isArray(options.operation) && options.operation.every(is.string)) { | ||
sharp.block(options.operation, false); | ||
} else { | ||
throw is.invalidParameterError('operation', 'Array<string>', options.operation); | ||
} | ||
} else { | ||
throw is.invalidParameterError('options', 'object', options); | ||
} | ||
} | ||
/** | ||
* Decorate the Sharp class with utility-related functions. | ||
@@ -174,3 +290,6 @@ * @private | ||
Sharp.versions = versions; | ||
Sharp.vendor = vendor; | ||
Sharp.queue = queue; | ||
Sharp.block = block; | ||
Sharp.unblock = unblock; | ||
}; |
{ | ||
"name": "sharp", | ||
"description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, AVIF and TIFF images", | ||
"version": "0.27.2", | ||
"description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images", | ||
"version": "0.32.6", | ||
"author": "Lovell Fuller <npm@lovell.info>", | ||
@@ -77,13 +77,26 @@ "homepage": "https://github.com/lovell/sharp", | ||
"Leon Radley <leon@radley.se>", | ||
"alza54 <alza54@thiocod.in>" | ||
"alza54 <alza54@thiocod.in>", | ||
"Jacob Smith <jacob@frende.me>", | ||
"Michael Nutt <michael@nutt.im>", | ||
"Brad Parham <baparham@gmail.com>", | ||
"Taneli Vatanen <taneli.vatanen@gmail.com>", | ||
"Joris Dugué <zaruike10@gmail.com>", | ||
"Chris Banks <christopher.bradley.banks@gmail.com>", | ||
"Ompal Singh <ompal.hitm09@gmail.com>", | ||
"Brodan <christopher.hranj@gmail.com", | ||
"Ankur Parihar <ankur.github@gmail.com>", | ||
"Brahim Ait elhaj <brahima@gmail.com>", | ||
"Mart Jansink <m.jansink@gmail.com>", | ||
"Lachlan Newman <lachnewman007@gmail.com>" | ||
], | ||
"scripts": { | ||
"install": "(node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)", | ||
"install": "(node install/libvips && node install/dll-copy && prebuild-install) || (node install/can-compile && node-gyp rebuild && node install/dll-copy)", | ||
"clean": "rm -rf node_modules/ build/ vendor/ .nyc_output/ coverage/ test/fixtures/output.*", | ||
"test": "semistandard && cpplint && npm run test-unit && npm run test-licensing", | ||
"test-unit": "nyc --reporter=lcov --branches=99 mocha --slow=5000 --timeout=60000 ./test/unit/*.js", | ||
"test": "npm run test-lint && npm run test-unit && npm run test-licensing && npm run test-types", | ||
"test-lint": "semistandard && cpplint", | ||
"test-unit": "nyc --reporter=lcov --reporter=text --check-coverage --branches=100 mocha", | ||
"test-licensing": "license-checker --production --summary --onlyAllow=\"Apache-2.0;BSD;ISC;MIT\"", | ||
"test-coverage": "./test/coverage/report.sh", | ||
"test-leak": "./test/leak/leak.sh", | ||
"docs-build": "documentation lint lib && node docs/build && node docs/search-index/build", | ||
"test-types": "tsd", | ||
"docs-build": "node docs/build && node docs/search-index/build", | ||
"docs-serve": "cd docs && npx serve", | ||
@@ -93,2 +106,3 @@ "docs-publish": "cd docs && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp" | ||
"main": "lib/index.js", | ||
"types": "lib/index.d.ts", | ||
"files": [ | ||
@@ -112,2 +126,3 @@ "binding.gyp", | ||
"svg", | ||
"jp2", | ||
"dzi", | ||
@@ -123,36 +138,48 @@ "image", | ||
"dependencies": { | ||
"array-flatten": "^3.0.0", | ||
"color": "^3.1.3", | ||
"detect-libc": "^1.0.3", | ||
"node-addon-api": "^3.1.0", | ||
"npmlog": "^4.1.2", | ||
"prebuild-install": "^6.0.1", | ||
"semver": "^7.3.4", | ||
"simple-get": "^4.0.0", | ||
"tar-fs": "^2.1.1", | ||
"color": "^4.2.3", | ||
"detect-libc": "^2.0.2", | ||
"node-addon-api": "^6.1.0", | ||
"prebuild-install": "^7.1.1", | ||
"semver": "^7.5.4", | ||
"simple-get": "^4.0.1", | ||
"tar-fs": "^3.0.4", | ||
"tunnel-agent": "^0.6.0" | ||
}, | ||
"devDependencies": { | ||
"async": "^3.2.0", | ||
"@types/node": "*", | ||
"async": "^3.2.4", | ||
"cc": "^3.0.1", | ||
"decompress-zip": "^0.3.3", | ||
"documentation": "^13.1.1", | ||
"exif-reader": "^1.0.3", | ||
"icc": "^2.0.0", | ||
"exif-reader": "^1.2.0", | ||
"extract-zip": "^2.0.1", | ||
"icc": "^3.0.0", | ||
"jsdoc-to-markdown": "^8.0.0", | ||
"license-checker": "^25.0.1", | ||
"mocha": "^8.3.0", | ||
"mock-fs": "^4.13.0", | ||
"mocha": "^10.2.0", | ||
"mock-fs": "^5.2.0", | ||
"nyc": "^15.1.0", | ||
"prebuild": "^10.0.1", | ||
"rimraf": "^3.0.2", | ||
"semistandard": "^16.0.0" | ||
"prebuild": "^12.0.0", | ||
"semistandard": "^16.0.1", | ||
"tsd": "^0.29.0" | ||
}, | ||
"license": "Apache-2.0", | ||
"config": { | ||
"libvips": "8.10.5", | ||
"libvips": "8.14.5", | ||
"integrity": { | ||
"darwin-arm64v8": "sha512-1QZzICfCJd4wAO0P6qmYI5e5VFMt9iCE4QgefI8VMMbdSzjIXA9L/ARN6pkMQPZ3h20Y9RtJ2W1skgCsvCIccw==", | ||
"darwin-x64": "sha512-sMIKMYXsdU9FlIfztj6Kt/SfHlhlDpP0Ups7ftVFqwjaszmYmpI9y/d/q3mLb4jrzuSiSUEislSWCwBnW7MPTw==", | ||
"linux-arm64v8": "sha512-CD8owELzkDumaom+O3jJ8fKamILAQdj+//KK/VNcHK3sngUcFpdjx36C8okwbux9sml/T7GTB/gzpvReDrAejQ==", | ||
"linux-armv6": "sha512-wk6IPHatDFVWKJy7lI1TJezHGHPQut1wF2bwx256KlZwXUQU3fcVcMpV1zxXjgLFewHq2+uhyMkoSGBPahWzlA==", | ||
"linux-armv7": "sha512-HEZC9KYtkmBK5rUR2MqBhrVarnQVZ/TwLUeLkKq0XuoM2pc/eXI6N0Fh5NGEFwdXI2XE8g1ySf+OYS6DDi+xCQ==", | ||
"linux-x64": "sha512-SlFWrITSW5XVUkaFPQOySAaSGXnhkGJCj8X2wGYYta9hk5piZldQyMp4zwy0z6UeRu1qKTKtZvmq28W3Gnh9xA==", | ||
"linuxmusl-arm64v8": "sha512-ga9iX7WUva3sG/VsKkOD318InLlCfPIztvzCZKZ2/+izQXRbQi8VoXWMHgEN4KHACv45FTl7mJ/8CRqUzhS8wQ==", | ||
"linuxmusl-x64": "sha512-yeaHnpfee1hrZLok2l4eFceHzlfq8gN3QOu0R4Mh8iMK5O5vAUu97bdtxeZZeJJvHw8tfh2/msGi0qysxKN8bw==", | ||
"win32-arm64v8": "sha512-kR91hy9w1+GEXK56hLh51+hBCBo7T+ijM4Slkmvb/2PsYZySq5H7s61n99iDYl6kTJP2y9sW5Xcvm3uuXDaDgg==", | ||
"win32-ia32": "sha512-HrnofEbzHNpHJ0vVnjsTj5yfgVdcqdWshXuwFO2zc8xlEjA83BvXZ0lVj9MxPxkxJ2ta+/UlLr+CFzc5bOceMw==", | ||
"win32-x64": "sha512-BwKckinJZ0Fu/EcunqiLPwOLEBWp4xf8GV7nvmVuKKz5f6B+GxoA2k9aa2wueqv4r4RJVgV/aWXZWFKOIjre/Q==" | ||
}, | ||
"runtime": "napi", | ||
"target": 3 | ||
"target": 7 | ||
}, | ||
"engines": { | ||
"node": ">=10" | ||
"node": ">=14.15.0" | ||
}, | ||
@@ -164,3 +191,3 @@ "funding": { | ||
"napi_versions": [ | ||
3 | ||
7 | ||
] | ||
@@ -178,3 +205,6 @@ }, | ||
] | ||
}, | ||
"tsd": { | ||
"directory": "test/types/" | ||
} | ||
} |
# sharp | ||
<img src="https://cdn.jsdelivr.net/gh/lovell/sharp@master/docs/image/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right"> | ||
<img src="https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right"> | ||
The typical use case for this high speed Node.js module | ||
is to convert large images in common formats to | ||
smaller, web-friendly JPEG, PNG, WebP and AVIF images of varying dimensions. | ||
smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions. | ||
@@ -19,5 +19,13 @@ Resizing an image is typically 4x-5x faster than using the | ||
Most modern macOS, Windows and Linux systems running Node.js v10+ | ||
Most modern macOS, Windows and Linux systems running Node.js >= 14.15.0 | ||
do not require any additional install or runtime dependencies. | ||
## Documentation | ||
Visit [sharp.pixelplumbing.com](https://sharp.pixelplumbing.com/) for complete | ||
[installation instructions](https://sharp.pixelplumbing.com/install), | ||
[API documentation](https://sharp.pixelplumbing.com/api-constructor), | ||
[benchmark tests](https://sharp.pixelplumbing.com/performance) and | ||
[changelog](https://sharp.pixelplumbing.com/changelog). | ||
## Examples | ||
@@ -47,2 +55,3 @@ | ||
.resize(200) | ||
.jpeg({ mozjpeg: true }) | ||
.toBuffer() | ||
@@ -89,21 +98,10 @@ .then( data => { ... }) | ||
[![Test Coverage](https://coveralls.io/repos/lovell/sharp/badge.svg?branch=master)](https://coveralls.io/r/lovell/sharp?branch=master) | ||
[![N-API v3](https://img.shields.io/badge/N--API-v3-green.svg)](https://nodejs.org/dist/latest/docs/api/n-api.html#n_api_n_api_version_matrix) | ||
## Contributing | ||
### Documentation | ||
Visit [sharp.pixelplumbing.com](https://sharp.pixelplumbing.com/) for complete | ||
[installation instructions](https://sharp.pixelplumbing.com/install), | ||
[API documentation](https://sharp.pixelplumbing.com/api-constructor), | ||
[benchmark tests](https://sharp.pixelplumbing.com/performance) and | ||
[changelog](https://sharp.pixelplumbing.com/changelog). | ||
### Contributing | ||
A [guide for contributors](https://github.com/lovell/sharp/blob/master/.github/CONTRIBUTING.md) | ||
A [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md) | ||
covers reporting bugs, requesting features and submitting code changes. | ||
### Licensing | ||
## Licensing | ||
Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 Lovell Fuller and contributors. | ||
Copyright 2013 Lovell Fuller and others. | ||
@@ -110,0 +108,0 @@ Licensed under the Apache License, Version 2.0 (the "License"); |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 5 instances in 1 package
Mixed license
License(Experimental) Package contains multiple licenses.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Mixed license
License(Experimental) Package contains multiple licenses.
Found 1 instance in 1 package
609870
8
42
6830
14
115
19
+ Addedb4a@1.6.7(transitive)
+ Addedbare-events@2.5.0(transitive)
+ Addedbare-fs@2.3.5(transitive)
+ Addedbare-os@2.4.4(transitive)
+ Addedbare-path@2.1.3(transitive)
+ Addedbare-stream@2.3.2(transitive)
+ Addedcolor@4.2.3(transitive)
+ Addedcolor-convert@2.0.1(transitive)
+ Addedcolor-name@1.1.4(transitive)
+ Addeddetect-libc@2.0.3(transitive)
+ Addedfast-fifo@1.3.2(transitive)
+ Addednode-abi@3.71.0(transitive)
+ Addednode-addon-api@6.1.0(transitive)
+ Addedprebuild-install@7.1.2(transitive)
+ Addedqueue-tick@1.0.1(transitive)
+ Addedsafe-buffer@5.2.1(transitive)
+ Addedstreamx@2.20.1(transitive)
+ Addedstring_decoder@1.3.0(transitive)
+ Addedtar-fs@3.0.6(transitive)
+ Addedtar-stream@3.1.7(transitive)
+ Addedtext-decoder@1.2.1(transitive)
- Removedarray-flatten@^3.0.0
- Removednpmlog@^4.1.2
- Removedansi-regex@2.1.1(transitive)
- Removedaproba@1.2.0(transitive)
- Removedare-we-there-yet@1.1.7(transitive)
- Removedarray-flatten@3.0.0(transitive)
- Removedcode-point-at@1.1.0(transitive)
- Removedcolor@3.2.1(transitive)
- Removedcolor-convert@1.9.3(transitive)
- Removedcolor-name@1.1.3(transitive)
- Removedconsole-control-strings@1.1.0(transitive)
- Removedcore-util-is@1.0.3(transitive)
- Removeddecompress-response@4.2.1(transitive)
- Removeddelegates@1.0.0(transitive)
- Removeddetect-libc@1.0.3(transitive)
- Removedgauge@2.7.4(transitive)
- Removedhas-unicode@2.0.1(transitive)
- Removedis-fullwidth-code-point@1.0.0(transitive)
- Removedisarray@1.0.0(transitive)
- Removedmimic-response@2.1.0(transitive)
- Removednode-abi@2.30.1(transitive)
- Removednode-addon-api@3.2.1(transitive)
- Removednpmlog@4.1.2(transitive)
- Removednumber-is-nan@1.0.1(transitive)
- Removedobject-assign@4.1.1(transitive)
- Removedprebuild-install@6.1.4(transitive)
- Removedprocess-nextick-args@2.0.1(transitive)
- Removedreadable-stream@2.3.8(transitive)
- Removedsafe-buffer@5.1.2(transitive)
- Removedsemver@5.7.2(transitive)
- Removedset-blocking@2.0.0(transitive)
- Removedsignal-exit@3.0.7(transitive)
- Removedsimple-get@3.1.1(transitive)
- Removedstring-width@1.0.2(transitive)
- Removedstring_decoder@1.1.1(transitive)
- Removedstrip-ansi@3.0.1(transitive)
- Removedwide-align@1.1.5(transitive)
Updatedcolor@^4.2.3
Updateddetect-libc@^2.0.2
Updatednode-addon-api@^6.1.0
Updatedprebuild-install@^7.1.1
Updatedsemver@^7.5.4
Updatedsimple-get@^4.0.1
Updatedtar-fs@^3.0.4