Monday, January 4, 2010

Image Transparency

How to make an image transparent in Java?

Here is one method for making a specific color transparent for any image.
public BufferedImage clearColor(Image image, Color color) {
int width = image.getWidth(null);
int height = image.getHeight(null);

BufferedImage bImg =
new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);

// transfer the source image a new 32 bit per pixel
// image need to give some images a 8 bit alpha
// channel, makes our images uniform, color depth
Graphics g = bImg.getGraphics();
g.drawImage(image, 0, 0, null);

// go through all the colors
int total = width * height;
int x = 0, y = 0;
int c[] = new int[4];

WritableRaster wr = bImg.getRaster();
for (int i = 0; i < total; ++i) {
// avoid nested loops
y = i / width; // truncated
x = i - y * width;
wr.getPixel(x, y, c);
if (c[2] == color.getBlue() &&
c[1] == color.getGreen() &&
c[0] == color.getRed()) {

//clear the color at x,y
bImg.setRGB(x, y, 0);
}
}
return bImg;
}
Another method would be to edit the image in an image editor and make the background color transparent saving the image to a format that supports transparency.

Here is the example snippet:

No comments:

Post a Comment