Java – Making a Certain Color on a BufferedImage Become Transparent

java

A very similar question that has been answered: How to make a color transparent in a BufferedImage and save as PNG

Unfortunately I couldn't formulate an answer for myself out of that source.

Q: I draw a BufferedImage to my Canvas and would simply like to create a method that turns every pixel with the a certain color (in this case: [214, 127, 255] / 0xD67FFF) into a transparent one. The BufferedImage is of type ARGB.

I do not want to save the BufferedImage as a file, simply display it on my canvas.

Thanks in advance.

Best Answer

Iterate over all the pixels and perform the check and make transparent.

for (int y = 0; y < image.getHeight(); ++y) {
    for (int x = 0; x < image.getWidth(); ++x) {
         int argb = image.getRGB(x, y);
         if ((argb & 0x00FFFFFF) == 0x00D67FFF)
         {
              image.setRGB(x, y, 0);
         }
    }
}

Make sure the BufferedImage uses an alpha channel, otherwise it will become black.
Note that this will affect your original image.

Edit: Note that I changed the check. Therefor it wouldn't have worked because of I assume your pixels were solid (alpha = 255).


(0xFFD67FFF & 0x00FFFFFF) will result in 0x00D67FFF
And, (0x00D67FFF == 0x00D67FFF)
Related Topic