Ensure trim is no-op when it would reduce to nothing #3223

This commit is contained in:
Lovell Fuller 2022-07-08 21:06:58 +01:00
parent 6c2e2be41d
commit cbf741cac7
5 changed files with 29 additions and 3 deletions

View File

@ -239,6 +239,8 @@ Trim "boring" pixels from all edges that contain values similar to the top-left
Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels.
If the result of this operation would trim an image to nothing then no change is made.
The `info` response Object, obtained from callback of `.toFile()` or `.toBuffer()`,
will contain `trimOffsetLeft` and `trimOffsetTop` properties.

View File

@ -17,6 +17,9 @@ Requires libvips v8.13.0
* Add support for WebP and PackBits `compression` options with TIFF output.
[#3198](https://github.com/lovell/sharp/issues/3198)
* Ensure `trim` operation is a no-op when it would reduce an image to nothing.
[#3223](https://github.com/lovell/sharp/issues/3223)
## v0.30 - *dresser*
Requires libvips v8.12.2

View File

@ -433,6 +433,8 @@ function extract (options) {
*
* Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels.
*
* If the result of this operation would trim an image to nothing then no change is made.
*
* The `info` response Object, obtained from callback of `.toFile()` or `.toBuffer()`,
* will contain `trimOffsetLeft` and `trimOffsetTop` properties.
*

View File

@ -297,10 +297,10 @@ namespace sharp {
}
}
}
if (width == 0 || height == 0) {
throw VError("Unexpected error while trimming. Try to lower the tolerance");
if (width > 0 && height > 0) {
return image.extract_area(left, top, width, height);
}
return image.extract_area(left, top, width, height);
return image;
}
/*

View File

@ -140,6 +140,25 @@ describe('Trim borders', function () {
assert.strictEqual(trimOffsetLeft, -13);
});
it('Ensure trim of image with all pixels same is no-op', async () => {
const { info } = await sharp({
create: {
width: 5,
height: 5,
channels: 3,
background: 'red'
}
})
.trim()
.toBuffer({ resolveWithObject: true });
const { width, height, trimOffsetTop, trimOffsetLeft } = info;
assert.strictEqual(width, 5);
assert.strictEqual(height, 5);
assert.strictEqual(trimOffsetTop, 0);
assert.strictEqual(trimOffsetLeft, 0);
});
describe('Invalid thresholds', function () {
[-1, 'fail', {}].forEach(function (threshold) {
it(JSON.stringify(threshold), function () {