In the latest version 0.21.3, trimming a png image fails.
In a previous version 0.20.8, the code completes successfully.
Here's my function in typescript:
async trim(dataUrl: string) {
dataUrl = dataUrl.replace(/^data:image\/png;base64,/, "");
dataUrl += dataUrl.replace('+', ' ');
let buffer = new Buffer(dataUrl, "base64");
return sharp(buffer)
.png()
.trim(1) //also tried default parameter
.toBuffer();
}
This is the output in console:
Error: Unexpected error while trimming. Try to lower the tolerance.
Hello, the following entry for v0.21.0 in the changelog is relevant here:
Switch from custom trim operation to vips_find_trim. #914
https://sharp.pixelplumbing.com/en/stable/changelog/#v0210-4th-october-2018
Please can you provide a sample image that behaves in this manner.
Thank you for your response @lovell.
I generate the image's dataUrl with fabricjs inside puppeteer, so it's basically canvas.toDataUrl().
Both 'jpeg' and 'png' produce this error. Here's the png that won't trim:

My node version is v10.15.1 on Windows10.
I did another test with the uploaded png:
Opened it with mspaint and just saved it in a new file.
It lost the transparent background, but sharp v0.21.3 trimmed it successfully.
Then we just need a way to automate mspaint :)
@Granga Thank you for the example PNG. I think this has something to do with the input being 2 channel greyscale+alpha but I'll need to take a closer look.
All of the pixels in this image are black and the text is contained only in the transparency layer.
By default sharp/libvips flattens to black hence the entire image is background.
We need to retrieve the background colour from the bKGD chunk in the PNG, if present, and flatten to that instead.
Hi,
using sharp 0.22.1 i get the same error when trying to trim() an empty image. Since resize doesn't crash on those, it would be nice if trim did not crash too.
Why you don't add vips_find_trim as sharp function to just get the information
https://jcupitt.github.io/libvips/API/current/libvips-arithmetic.html#vips-find-trim
I need to execute this on fully transparent picture to get right coordinates
vips find_trim --threshold 0 --background 0 image.png
With current implementation it's impossible.
An alternative approach would be to modify libvips to optionally include the alpha channel in the calculation.
Commit c41b873 adds this test case and the code change to handle it, which is to fallback to using the alpha channel to determine "boringness" if the initial search of the non-alpha channels fails.
v0.23.3 now available, thank you for the original report.
Most helpful comment
v0.23.3 now available, thank you for the original report.