Thursday, January 28, 2010

Jogl: Texture Transparency

So here's another JOGL example for drawing transparent textures. The code is a bit lengthy but the comments should help guide you to the important parts.

The most important piece of code is turning on blending.

// Really basic and most common alpha blend function


gl.glBegin(GL.GL_QUADS); // the gl draw mode
One thing you must note here is that the texture binding is done outside the glBegin and glEnd calls as well as telling the device to turn on blending and setting the blend function.

Other code to note is the creation of a texture from a BufferedImage, which is covered in a previous post so take a look at that first, Drawing HTML with JOGL Part 1: Textures. This example is based off of that code.

NOTE: Also, be sure to pay close attention to the order in which transparent textures are drawn.

And now the code:
This example uses JOGL version 1.1.1a and should work with the NetBeans plugin you can obtain the version from JOGL's website go to the "Archived Builds" page from the navigation menu on the left. Then find the jsr-231-1.1.1a folder

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,

// 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: