Skip to content

Instantly share code, notes, and snippets.

@jonshipman
Created May 6, 2024 16:25
Show Gist options
  • Save jonshipman/5ae6b67c176fb891e02241e58636c87d to your computer and use it in GitHub Desktop.
Save jonshipman/5ae6b67c176fb891e02241e58636c87d to your computer and use it in GitHub Desktop.
Sharp Nodejs Trim to the bottom right pixel color
import sharp from 'sharp';
export async function trimImage(input: Buffer) {
try {
const metadata = await sharp(input).metadata();
const width = metadata.width || 0;
const height = metadata.height || 0;
if (!width || !height) return input;
const [red, green, blue] = await sharp(input)
.raw()
.toBuffer()
.then((data) => {
const offset = 3 * (width * height + width);
const r = data[offset];
const g = data[offset + 1];
const b = data[offset + 2];
return [r, g, b];
});
return sharp(input)
.trim({ background: `rgb(${red},${green},${blue})` })
.toBuffer();
} catch (error) {
console.error(`Error trimming image: ${input}`, error);
}
return input;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment