sharp icon indicating copy to clipboard operation
sharp copied to clipboard

Include trimOffsetRight & trimOffsetBottom

Open Zirafnik opened this issue 1 year ago • 1 comments

Feature request

After trimming an image with .trim() you receive an info object, which includes the trimOffsetLeft and trimOffsetTop properties.

However, a picture can be asymmetric, meaning that .trim() will remove differing amounts of border on each side => trimOffsetLeft !== trimOffsetRight.

The current workaround is to calculate the right and bottom offset by hand, with the use of pre-processing metadata and properties included in the resulting info object,

This is the formula used:

Other Offset = Original Length - New Length - |Opposite Offset|

const image = sharp(inputFile);

const data = await image.metadata();
const buffer1 = await image
    .trim()
    .toBuffer({ resolveWithObject: true }); // we get new data after .trim()

const info = buffer1.info;

const trimOffset = {
    left: Math.abs(info.trimOffsetLeft),
    right: data.width - info.width - Math.abs(info.trimOffsetLeft),
    top: Math.abs(info.trimOffsetTop),
    bottom: data.height - info.height - Math.abs(info.trimOffsetTop),
};

Additionally, perhaps the original pre-processing values, such as original width & original height could be included in the resulting info object.

Zirafnik avatar Apr 26 '24 19:04 Zirafnik

Your approach to calculate these values looks correct and matches the advice previously given at https://github.com/lovell/sharp/issues/3696#issuecomment-1587898783

I'm unsure if this logic needs adding to and therefore fall under the maintenance burden of sharp.

lovell avatar Apr 26 '24 22:04 lovell

Closing as I'm not keen to add this logic to sharp itself - all the data required to calculate this is already exposed.

lovell avatar May 16 '24 12:05 lovell