Making a Certain Color on a BufferedImage Become Transparent
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 开发者_JAVA技巧as a file, simply display it on my canvas.
Thanks in advance.
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)
For a complete solution, like loading, processing and writing, you can use this code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class TransparentConverter {
private static final Color backColor = Color.GREEN;
private static final int THRESHOLD = 70;
private static final int TRANSPARENT = 0; // 0x00000000;
static File base = new File("C:\\images");
static File base2 = new File("C:\\images2");
public static void main(String[] args) throws IOException {
System.out.println("TransparentConverter.main()");
for (File file : base.listFiles()) {
System.out.println(file);
BufferedImage initImage = ImageIO.read(file);
int width = initImage.getWidth(null),
height = initImage.getHeight(null);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
g.drawImage(initImage, 0, 0, null);
//System.out.println("before: " + image.getRGB(0, 0));
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int pixel = image.getRGB(x, y);
Color color = new Color(pixel);
int dr = Math.abs(color.getRed() - backColor.getRed()),
dg = Math.abs(color.getGreen() - backColor.getGreen()),
db = Math.abs(color.getBlue() - backColor.getBlue());
if (dr < THRESHOLD && dg < THRESHOLD && db < THRESHOLD) {
image.setRGB(x, y, TRANSPARENT);
}
}
}
//System.out.println(" after: " + image.getRGB(0, 0));
file = new File(base2, file.getName());
//System.out.println(" " + file);
ImageIO.write(image, "png", file);
}
}
}
精彩评论