我正在尝试更改像素的alpha值以使图像半透明。这是我的代码:
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));
}
}
输出是这样的:
before: 331b1aff
after: ff1b1aff
before: 331918ff
after: ff1918ff
before: 331e1bff
after: ff1e1bff
before: 332623ff
after: ff2623ff
before: 332e29ff
after: ff2e29ff
如您所见,似乎setRGB省略了alpha值并将其设置为“ff”。我怎样才能解决这个问题,为什么它首先会发生?
答案 0 :(得分:2)
这可能是因为你的BufferedImage
颜色模型不支持alpha或者可能只使用一个比特来表示alpha。
你从哪里得到image
?它的颜色模型也是ARGB吗?使用image.getColorModel().
hasAlpha()进行检查。如果没有,请确保在创建图像时它具有适当的颜色模型,如果无法更改,请使用所需的颜色模型创建新图像并首先复制源图像。
答案 1 :(得分:2)
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
可以像这样制作:
...
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));
...