nodejs Sharp: transparent into white

Serge picture Serge · Dec 14, 2017 · Viewed 7.6k times · Source

I am using Nodejs Sharp to transcode/resize png images into jpg. Is there way to replace transparent with white (or other light color) rather than black? I found solution for an older library but Sharp seems to be fastest and greatest.

.background does not work

.then( data => Sharp(data.Body)
  .resize(SIZES[resize_type].width, SIZES[resize_type].height)
  .max()
  .withoutEnlargement()
  .background("white")
  .toFormat('jpeg')
  .toBuffer()
)

Answer

nakorndev picture nakorndev · Dec 24, 2019

On version ^0.23 you can use flatten(options) as api document here: https://sharp.readthedocs.io/en/stable/api-operation/#flatten

sharp('input.png').flatten({ background: { r: 255, g: 255, b: 255 } })