Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
mytradingcapital opened this issue Feb 29, 2024 · 4 comments
Labels

Comments

@mytradingcapital
Copy link

mytradingcapital commented Feb 29, 2024

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.');
  }
});
@lovell
Copy link
Owner

lovell commented Feb 29, 2024

Did you see tint?

@mytradingcapital
Copy link
Author

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

@lovell
Copy link
Owner

lovell commented Feb 29, 2024

I lose the transparent background

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

@mytradingcapital
Copy link
Author

mytradingcapital commented Feb 29, 2024

This is an exemple with full png

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants