I want crop product images with white background so the product is centered:
Before: http://i.imgur.com/1herTTx.jpg
After: http://i.imgur.com/RkB2VV5.jpg
Any ideas how do achieve this?
Hi @vermin1337 -
You'll want to look at the trim method
Then you'll want to get the width and height from the trimmed buffer
This is the output from the below code: http://imgur.com/a/6fovG
I used the linked "before" image from your question.
let sharp = require('sharp')
let image = sharp('./input.jpg').trim().toBuffer(function (err, data, info) {
let w = info.width
let h = info.height
let padding = 10
let ext = {}
if ( w / h > 1 ) {
let amt = (w - h) / 2 + padding
ext = {
top: amt,
bottom: amt,
left: padding,
right: padding
}
} else {
amt = (h - w) / 2 + padding
ext = {
top: padding,
bottom: padding,
left: amt,
right: amt
}
}
sharp(data)
.background({r: 255, g: 255, b: 255, alpha: 1})
.extend(ext)
.toFile('./output.jpg')
})
// .toFile('./output.jpg')
@joemanfoo Beautiful!
Thanks! In some cases the amt value is an float, should have parseInt(amt).
I'll share my final solution based in this example:
https://gist.github.com/inonjs/8e6d0b8b22479a387738de0379ccb1c7
Most helpful comment
Hi @vermin1337 -
You'll want to look at the trim method
Then you'll want to get the width and height from the trimmed buffer
This is the output from the below code: http://imgur.com/a/6fovG
I used the linked "before" image from your question.