lovell / lovell/sharp

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

Open
#4,015 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

question
Dominant language
JavaScript
Stars
32.7k
Forks
1.4k
Avg merge
1d 14h
Merged PRs (30d)
5

Description

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](https://i.stack.imgur.com/5cAqg.jpg)
[New Color](https://i.stack.imgur.com/Bh5mn.jpg)

Example BAD:
[Old Color](https://i.ibb.co/gW44RsB/Capture-d-cran-2024-02-29-103113.png)
[New Color background lose transparency](https://i.ibb.co/JyMMD6d/aa.jpg)

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the processImage function and reproduce the result using oldColor.png, the supplied hex color, and Sharp's composite operation. Inspect the generated PNG's alpha channel and compare it with the linked GOOD and BAD examples; done means the recolored image retains the original transparent background.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, nodejs
Domain
computer-graphics
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.