我在图像透明度方面遇到了问题。内容如下:
我有 image1,我需要将 image2 重叠在上面。 image2 是具有透明度的 png。我想创建一个带有水印的图像,它将是 image1 之上的透明 image2。
当我打开具有透明度的 image2 并将其放入 JFrame 中只是为了预览它时,它以透明方式打开。但是,当我使用 BufferImage 对象的 getRGB 方法获取 image2 的像素并使用 setRGB 将其覆盖在 image1 上时,image2 失去透明度并获得白色背景。这是代码:
public class Test {
public static void main(String[] args) throws IOException {
BufferedImage image = ImageIO.read(new File("c:/images.jpg"));
BufferedImage image2 = ImageIO.read(new File("c:/images2.png"));
int w = image2.getWidth();
int h = image2.getHeight();
int[] pixels = image2.getRGB(0, 0, w, h, null, 0, w);
image2.setRGB(0, 0, w, h, pixels ,0 ,w);
// here goes the code to show it on JFrame
}
}
拜托,有人可以告诉我我做错了什么吗?我注意到这段代码正在丢失 image2 的 alpha。我怎样才能做到不失去 alpha?
最佳答案
问题是 setPixel 将使用直接接收像素的图像编码,而不解释原始图像的图形上下文。如果您使用 graphics 对象,就不会发生这种情况。
尝试:
public static void main(String[] args) throws IOException {
BufferedImage image = ImageIO.read(new File("c:/images.jpg"));
BufferedImage image2 = ImageIO.read(new File("c:/images2.png"));
int w = image2.getWidth();
int h = image2.getHeight();
Graphics2D graphics = image.createGraphics();
graphics.drawImage(image2, 0, 0, w, h, null);
graphics.dispose();
// here goes the code to show it on JFrame
}
关于java - 图像透明度 - 重叠时丢失 alpha,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13671061/