diff --git a/docs/api-resize.md b/docs/api-resize.md index 392c391e..2af15c25 100644 --- a/docs/api-resize.md +++ b/docs/api-resize.md @@ -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. diff --git a/docs/changelog.md b/docs/changelog.md index 226b5eab..d501190a 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -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 diff --git a/lib/resize.js b/lib/resize.js index cbc90ce6..1338055a 100644 --- a/lib/resize.js +++ b/lib/resize.js @@ -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. * diff --git a/src/operations.cc b/src/operations.cc index 609bd1e9..a431691b 100644 --- a/src/operations.cc +++ b/src/operations.cc @@ -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; } /* diff --git a/test/unit/trim.js b/test/unit/trim.js index 3f187d99..0531323b 100644 --- a/test/unit/trim.js +++ b/test/unit/trim.js @@ -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 () {