13

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()
)
mapmalith
  • 1,303
  • 21
  • 38
Serge
  • 3,387
  • 3
  • 16
  • 34

4 Answers4

28

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 } })
nakorndev
  • 803
  • 2
  • 11
  • 18
11

from the sharp documentation as it states that you can use the background for color manipulations and it states that

The default background is {r: 0, g: 0, b: 0, alpha: 1}, black without transparency.

so inorder to get white simply use

.background({r: 255, g: 255, b: 255, alpha: 1})
Nuwan Alawatta
  • 1,812
  • 21
  • 29
Fadi Abo Msalam
  • 6,739
  • 2
  • 20
  • 25
6

by the document, we should do the way as Msalam suggest but unluckily that is not enough. I figured out We should add .flatten(true) before ".resize(...)" to make it work correctly.

Bioz Nguyen
  • 1,842
  • 1
  • 9
  • 6
1

Just add :

.flatten({ background: '#fff' })
reyqueson
  • 459
  • 1
  • 7
  • 9