Sharp: Crop product images (find non-white pixels)

Created on 26 Aug 2017  路  3Comments  路  Source: lovell/sharp

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?

question

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.

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')

All 3 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jaydenseric picture jaydenseric  路  3Comments

Andresmag picture Andresmag  路  3Comments

henbenla picture henbenla  路  3Comments

terbooter picture terbooter  路  3Comments

natural-law picture natural-law  路  3Comments