NodeJS Sharp - Change the color of an image while retaining the transparency of the background

74 Views Asked by At

for one of my projects, I need to change the color of an image based on the hex color chosen by the user. I managed to change the color of the image using Sharp, but I lose the transparent background. I would like help finding a solution to change the color of the image while keeping the background transparent.

Example GOOD: Old Color New Color

Example BAD: Old Color New Color background lose transparency

I don't have many solutions in mind, I've tried a few things that didn't work.

Here is my code

const sharp = require('sharp');
const Color = require('color');

async function processImage(img, color) {
  const cheminImage = img;
  const couleurHex = color;

  try {
    const metadata = await sharp(cheminImage).metadata();

    const data = await sharp({
      create: {
        width: metadata.width,
        height: metadata.height,
        channels: 4,
        background: { r: Color(couleurHex).red(), g: Color(couleurHex).green(), b: Color(couleurHex).blue(), alpha: Color(couleurHex).blue() }
      }
    })
      .composite([{
        input: cheminImage,
        blend: "multiply",
      }])
      .toFormat("png")
      .toBuffer();

    const image = `data:image/png;base64,${data.toString("base64")}`;
    return image;
  } catch (err) {
    console.error(err);
    return null;
  }
}

processImage("./oldColor.png", "#383e42").then((result) => {
  if (result) {
    console.log('Base64 Image:', result);
  } else {
    console.log('Failed to process the image.');
  }
});
0

There are 0 best solutions below