Created
May 6, 2024 16:25
-
-
Save jonshipman/5ae6b67c176fb891e02241e58636c87d to your computer and use it in GitHub Desktop.
Sharp Nodejs Trim to the bottom right pixel color
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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