Expose erode and dilate operations #4243

This commit is contained in:
Quentin Pinçon
2025-03-27 12:59:02 +00:00
committed by Lovell Fuller
parent 03e1b19764
commit 031c808aa5
17 changed files with 249 additions and 0 deletions

View File

@@ -263,6 +263,8 @@ const Sharp = function (input, options) {
trimBackground: [],
trimThreshold: -1,
trimLineArt: false,
dilateWidth: 0,
erodeWidth: 0,
gamma: 0,
gammaOut: 0,
greyscale: false,

16
lib/index.d.ts vendored
View File

@@ -504,6 +504,22 @@ declare namespace sharp {
*/
blur(sigma?: number | boolean | BlurOptions): Sharp;
/**
* Expand foreground objects using the dilate morphological operator.
* @param {Number} [width=1] dilation width in pixels.
* @throws {Error} Invalid parameters
* @returns A sharp instance that can be used to chain operations
*/
dilate(width?: number): Sharp;
/**
* Shrink foreground objects using the erode morphological operator.
* @param {Number} [width=1] erosion width in pixels.
* @throws {Error} Invalid parameters
* @returns A sharp instance that can be used to chain operations
*/
erode(width?: number): Sharp;
/**
* Merge alpha transparency channel, if any, with background.
* @param flatten true to enable and false to disable (defaults to true)

View File

@@ -443,6 +443,52 @@ function blur (options) {
return this;
}
/**
* Expand foreground objects using the dilate morphological operator.
*
* @example
* const output = await sharp(input)
* .dilate()
* .toBuffer();
*
* @param {Number} [width=1] dilation width in pixels.
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
function dilate (width) {
if (!is.defined(width)) {
this.options.dilateWidth = 1;
} else if (is.integer(width) && width > 0) {
this.options.dilateWidth = width;
} else {
throw is.invalidParameterError('dilate', 'positive integer', dilate);
}
return this;
}
/**
* Shrink foreground objects using the erode morphological operator.
*
* @example
* const output = await sharp(input)
* .erode()
* .toBuffer();
*
* @param {Number} [width=1] erosion width in pixels.
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
function erode (width) {
if (!is.defined(width)) {
this.options.erodeWidth = 1;
} else if (is.integer(width) && width > 0) {
this.options.erodeWidth = width;
} else {
throw is.invalidParameterError('erode', 'positive integer', erode);
}
return this;
}
/**
* Merge alpha transparency channel, if any, with a background, then remove the alpha channel.
*
@@ -958,6 +1004,8 @@ module.exports = function (Sharp) {
flop,
affine,
sharpen,
erode,
dilate,
median,
blur,
flatten,