views:

1269

answers:

4

How do I change the global alpha value of a BufferedImage in Java? (I.E. make every pixel in the image that has a alpha value of 100 have a alpha value of 80)

A: 

I'm 99% sure the methods that claim to deal with an "RGB" value packed into an int actually deal with ARGB. So you ought to be able to do something like:

for (all x,y values of image) {
  int argb = img.getRGB(x, y);
  int oldAlpha = (argb >>> 24);
  if (oldAlpha == 100) {
    argb = (80 << 24) | (argb & 0xffffff);
    img.setRGB(x, y, argb);
  }
}

For speed, you could maybe use the methods to retrieve blocks of pixel values.

Neil Coffey
+1  A: 

I don't believe there's a single simple command to do this. A few options:

The first is the simplest to implement, IMO.

Michael Brewer-Davis
A: 

@Neil Coffey: thanks, i've been looking 4 this too however Your code didnt work for me so well (white background became black)

i coded something like this and that works perfect:

public void setAlpha(byte alpha) {       
    alpha %= 0xff; 
    for (int cx=0;cx<obj_img.getWidth();cx++) {          
        for (int cy=0;cy<obj_img.getHeight();cy++) {
            int color = obj_img.getRGB(cx, cy);

            int mc = (alpha << 24) | 0x00ffffff;
            int newcolor = color & mc;
            obj_img.setRGB(cx, cy, newcolor);            

        }

    }

}

where obj_img is BufferedImage.TYPE_INT_ARGB

and i change alpha with setAlpha((byte)125); alpha range is now 0-255

hope some1 uses this

A: 

Thanks for posting this... but it doesnt seem to work for me.... i am trying to make an image semi-transparent and them apply it as a texture over a plane in java 3d.... some how the alpha change has no effect... rgb responds though.... can u please help...