Allow ensureAlpha to set alpha transparency level #2634

This commit is contained in:
Lovell Fuller
2021-04-01 21:14:06 +01:00
parent fe0767df13
commit 8c33d0aa56
10 changed files with 91 additions and 32 deletions

View File

@@ -30,21 +30,39 @@ function removeAlpha () {
}
/**
* Ensure alpha channel, if missing. The added alpha channel will be fully opaque. This is a no-op if the image already has an alpha channel.
* Ensure the output image has an alpha transparency channel.
* If missing, the added alpha channel will have the specified
* transparency level, defaulting to fully-opaque (1).
* This is a no-op if the image already has an alpha channel.
*
* @since 0.21.2
*
* @example
* sharp('rgb.jpg')
* // rgba.png will be a 4 channel image with a fully-opaque alpha channel
* await sharp('rgb.jpg')
* .ensureAlpha()
* .toFile('rgba.png', function(err, info) {
* // rgba.png is a 4 channel image with a fully opaque alpha channel
* });
* .toFile('rgba.png')
*
* @example
* // rgba is a 4 channel image with a fully-transparent alpha channel
* const rgba = await sharp(rgb)
* .ensureAlpha(0)
* .toBuffer();
*
* @param {number} [alpha=1] - alpha transparency level (0=fully-transparent, 1=fully-opaque)
* @returns {Sharp}
* @throws {Error} Invalid alpha transparency level
*/
function ensureAlpha () {
this.options.ensureAlpha = true;
function ensureAlpha (alpha) {
if (is.defined(alpha)) {
if (is.number(alpha) && is.inRange(alpha, 0, 1)) {
this.options.ensureAlpha = alpha;
} else {
throw is.invalidParameterError('alpha', 'number between 0 and 1', alpha);
}
} else {
this.options.ensureAlpha = 1;
}
return this;
}

View File

@@ -221,7 +221,7 @@ const Sharp = function (input, options) {
joinChannelIn: [],
extractChannel: -1,
removeAlpha: false,
ensureAlpha: false,
ensureAlpha: -1,
colourspace: 'srgb',
composite: [],
// output