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
2009-03-19 00:32:53
+1
A:
I don't believe there's a single simple command to do this. A few options:
- copy into another image with an AlphaComposite specified (downside: not converted in place)
- directly manipulate the raster (downside: can lead to unmanaged images)
- use a filter or BufferedImageOp
The first is the simplest to implement, IMO.
Michael Brewer-Davis
2009-03-19 00:38:36
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