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

@@ -74,6 +74,7 @@ module.exports = {
inputPng: getPath('50020484-00001.png'), // http://c.searspartsdirect.com/lis_png/PLDM/50020484-00001.png
inputPngGradients: getPath('gradients-rgb8.png'),
inputPngWithSlightGradientBorder: getPath('slight-gradient-border.png'),
inputPngWithTransparency: getPath('blackbug.png'), // public domain
inputPngCompleteTransparency: getPath('full-transparent.png'),
inputPngWithGreyAlpha: getPath('grey-8bit-alpha.png'),

BIN
test/fixtures/slight-gradient-border.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

View File

@@ -599,7 +599,7 @@ const vertexSplitQuadraticBasisSpline: string = sharp.interpolators.vertexSplitQ
// Triming
sharp(input).trim({ background: '#000' }).toBuffer();
sharp(input).trim({ threshold: 10, lineArt: true }).toBuffer();
sharp(input).trim({ background: '#bf1942', threshold: 30 }).toBuffer();
sharp(input).trim({ background: '#bf1942', threshold: 30, margin: 20 }).toBuffer();
// Text input
sharp({

View File

@@ -222,6 +222,9 @@ describe('Trim borders', () => {
},
'Invalid lineArt': {
lineArt: 'fail'
},
'Invalid margin': {
margin: -1
}
}).forEach(([description, parameter]) => {
it(description, () => {
@@ -289,4 +292,42 @@ describe('Trim borders', () => {
assert.strictEqual(trimOffsetLeft, 0);
});
});
describe('Adds margin around content', () => {
it('Should trim complex gradients', async () => {
const { info } = await sharp(fixtures.inputPngGradients)
.trim({ threshold: 50, margin: 100 })
.toBuffer({ resolveWithObject: true });
const { width, height, trimOffsetTop, trimOffsetLeft } = info;
assert.strictEqual(width, 1000);
assert.strictEqual(height, 443);
assert.strictEqual(trimOffsetTop, -557);
assert.strictEqual(trimOffsetLeft, 0);
});
it('Should trim simple gradients', async () => {
const { info } = await sharp(fixtures.inputPngWithSlightGradientBorder)
.trim({ threshold: 70, margin: 50 })
.toBuffer({ resolveWithObject: true });
const { width, height, trimOffsetTop, trimOffsetLeft } = info;
assert.strictEqual(width, 900);
assert.strictEqual(height, 900);
assert.strictEqual(trimOffsetTop, -50);
assert.strictEqual(trimOffsetLeft, -50);
});
it('Should not overflow image bounding box', async () => {
const { info } = await sharp(fixtures.inputPngWithSlightGradientBorder)
.trim({ threshold: 70, margin: 9999999 })
.toBuffer({ resolveWithObject: true });
const { width, height, trimOffsetTop, trimOffsetLeft } = info;
assert.strictEqual(width, 1000);
assert.strictEqual(height, 1000);
assert.strictEqual(trimOffsetTop, 0);
assert.strictEqual(trimOffsetLeft, 0);
});
});
});