I am trying to change the alpha value of a pixel to make a image half transparent. Here is my code:
for(int x=0;x<image1.getWidth();x++) {
for(int y=0;y<image1.getHeight();y++) {
int rgb = image1.getRGB(x, y);
rgb = rgb | 0x000000ff; // make the image blue.
rgb = rgb & 0x33ffffff; // make the image transparent.
System.out.println("before: " + Integer.toHexString(rgb));
image1.setRGB(x, y, rgb);
int now_rgb= image1.getRGB(x, y);
System.out.println("after: " + Integer.toHexString(now_rgb));
}
}
The output is something like that:
before: 331b1aff
after: ff1b1aff
before: 331918ff
after: ff1918ff
before: 331e1bff
after: ff1e1bff
before: 332623ff
after: ff2623ff
before: 332e29ff
after: ff2e29ff
As you can see, its seems like the setRGB omitted the alpha value and set it to "ff". How can I resolve this problem, and why does it happen in the first place?
It's probably because your BufferedImage
's color model does not support alpha or possibly only uses a single bit for alpha.
Where did you get image
from? Is its color model also ARGB? Use image.getColorModel().
hasAlpha() to check. If not, make sure when you create your image it has an appropriate color model, and if it can't be changed, create a new image with the desired color model and copy the source image first.
Use an AlphaComposite:
BufferedImage img = //some code here
BufferedImage imgClone = //some clone of img, but let its type be BufferedImage.TYPE_INT_ARGB
Graphics2D imgCloneG = imgClone.createGraphics();
imgCloneG.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_IN, 0.5f));
imgCloneG.drawImage(img, 0, 0, null);
//imgClone is now img at half alpha
imgClone
can be made like this:
...
imgClone = new BufferedImage(img.getWidth(), img.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D imgCloneG = imgClone.createGraphics();
imgCloneG.drawImage(img, 0, 0, null);
imgCloneG.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_IN, 0.5f));
...
User contributions licensed under CC BY-SA 3.0