Add margin option to trim operation #4480

This commit is contained in:
Dmytro Tiapukhin
2026-01-02 09:32:31 +00:00
committed by Lovell Fuller
parent d161e45e06
commit a5e726002c
15 changed files with 109 additions and 9 deletions

View File

@@ -278,6 +278,7 @@ const Sharp = function (input, options) {
trimBackground: [],
trimThreshold: -1,
trimLineArt: false,
trimMargin: 0,
dilateWidth: 0,
erodeWidth: 0,
gamma: 0,

2
lib/index.d.ts vendored
View File

@@ -1606,6 +1606,8 @@ declare namespace sharp {
threshold?: number | undefined;
/** Does the input more closely resemble line art (e.g. vector) rather than being photographic? (optional, default false) */
lineArt?: boolean | undefined;
/** Leave a margin around trimmed content, value is in pixels. (optional, default 0) */
margin?: number | undefined;
}
interface RawOptions {

View File

@@ -540,10 +540,19 @@ function extract (options) {
* })
* .toBuffer();
*
* @example
* // Trim image leaving (up to) a 10 pixel margin around the trimmed content.
* const output = await sharp(input)
* .trim({
* margin: 10
* })
* .toBuffer();
*
* @param {Object} [options]
* @param {string|Object} [options.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} [options.threshold=10] - Allowed difference from the above colour, a positive number.
* @param {boolean} [options.lineArt=false] - Does the input more closely resemble line art (e.g. vector) rather than being photographic?
* @param {number} [options.margin=0] - Leave a margin around trimmed content, value is in pixels.
* @returns {Sharp}
* @throws {Error} Invalid parameters
*/
@@ -564,6 +573,13 @@ function trim (options) {
if (is.defined(options.lineArt)) {
this._setBooleanOption('trimLineArt', options.lineArt);
}
if (is.defined(options.margin)) {
if (is.integer(options.margin) && options.margin >= 0) {
this.options.trimMargin = options.margin;
} else {
throw is.invalidParameterError('margin', 'positive integer', options.margin);
}
}
} else {
throw is.invalidParameterError('trim', 'object', options);
}