mirror of
https://github.com/lovell/sharp.git
synced 2025-12-19 07:15:08 +01:00
Allow ensureAlpha to set alpha transparency level #2634
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user