sharp icon indicating copy to clipboard operation
sharp copied to clipboard

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

Open mytradingcapital opened this issue 4 months ago • 4 comments

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.');
  }
});

mytradingcapital avatar Feb 29 '24 10:02 mytradingcapital

Did you see tint?

lovell avatar Feb 29 '24 10:02 lovell

Thanks for your reply, but with tint(), the color is not natural and doesn't work with dark colors.

mytradingcapital avatar Feb 29 '24 13:02 mytradingcapital

I lose the transparent background

Your "New Color background lose transparency" example is a JPEG, which does not support an alpha channel.

lovell avatar Feb 29 '24 16:02 lovell

This is an exemple with full png

oldColor: https://ibb.co/zsWq6nH newColor: https://ibb.co/nfPHhjx

mytradingcapital avatar Feb 29 '24 16:02 mytradingcapital