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

How can one remove the background of an image by changing its alpha channel? #4064

Open
Gui153 opened this issue Apr 12, 2024 · 1 comment
Open
Labels

Comments

@Gui153
Copy link

Gui153 commented Apr 12, 2024

Question about an existing feature

What are you trying to achieve?

I am trying to remove the background from a logo by turning the background alpha channel to 0.
Currently I am resizing the image into a square.
Then create a clone which I turn into gray scale and then black and white.
Then I want to use this black and white image to change the alpha channel of the original image based on this output.

When you searched for similar issues, what did you find that might be related?

Nothing

Please provide a minimal, standalone code sample, without other dependencies, that demonstrates this question

// nodebuffer is the image buffer
//Size is a variable that ranges from 1 to 1024
const sharp = require("sharp");
const convert = await sharp(nodeBuffer)
.resize(Size, Size, {
fit: "contain",
background: "#FFFFFF",
})
.toBuffer();

const mask = await sharp(nodeBuffer)
.resize(Size, Size, {
fit: "contain",
background: "#000000",
})
.grayscale()
.negate() // Invert black and white regions
.toBuffer({ resolveWithObject: true });
//convert to strictly black and white
const BlackAndWhite = await sharp(mask.data)
.threshold(50) // Adjust threshold value as needed
.png()
.toBuffer();

fs.writeFileSync("./testGrayScale.png", mask.data);
fs.writeFileSync("./testNegate.png", BlackAndWhite);

const resultImage = await originalImage
.joinChannel( BlackAndWhite , { raw: { width: Size, height: Size, channels: 1 } })
.png() // Output as PNG to support transparency.
.toFile('testMask2.png');

Please provide sample image(s) that help explain this question

original logo
https://utfs.io/f/ef6f724b-0fc6-49a7-9586-5a02eeeb90fd-evqvdh.png
mask
https://utfs.io/f/424e43b3-fffe-44be-8b40-5fa3b17fcc6f-pyzg38.png
result
red cocacola logo with invisible background

@lovell
Copy link
Owner

lovell commented Apr 12, 2024

You'll need to ensure that the BlackAndWhite image is single-channel, which can be achieved using toColourspace.

  const BlackAndWhite = await sharp(mask.data)
   .threshold(50) // Adjust threshold value as needed
+  .toColourspace('b-w')
   .png()
   .toBuffer();

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