nodejs Sharp: transparent into white
Asked Answered
C

4

14

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()
)
Cincinnatus answered 14/12, 2017 at 16:38 Comment(1)
lol I want the oppositeHorsefaced
H
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.

Heartwood answered 13/4, 2018 at 3:44 Comment(0)
I
33

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 } })
Issy answered 24/12, 2019 at 3:3 Comment(1)
Note: You also can use .flatten({ background: '#ffffff' }) to make it's white.Issy
Z
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})
Zanezaneski answered 11/4, 2018 at 11:24 Comment(0)
H
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.

Heartwood answered 13/4, 2018 at 3:44 Comment(0)
V
2

Just add :

.flatten({ background: '#fff' })
Vishnu answered 27/6, 2022 at 14:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.