Change the alpha value of a BufferedImage?

William picture William · Mar 19, 2009 · Viewed 24k times · Source

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)

Answer

Felix picture Felix · Apr 17, 2009

@Neil Coffey: Thanks, I've been looking for this too; however, Your code didn't work very well for me (white background became black).

I coded something like this and it works perfectly:

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.

I change alpha with setAlpha((byte)125); alpha range is now 0-255.

Hope someone finds this useful.