合并两个图像

我需要在Java中合并两个图像(BufferedImage)。 如果没有透明度,这不成问题。 基本图像已经有一些透明度。 我想保持原样,并在其上应用“蒙版”,第二个图像。 这第二个图像没有不透明的像素,事实上它几乎是完全透明的,只是有一些透明度较低的像素来提供某种“光效”,就像reflection一样。 重要的细节:我不想在屏幕上,使用graphics来做到这一点,我需要获得与合并结果的BufferedImage。

任何人都可以帮我吗? 谢谢!

细节:合并保持透明度的两张图片。 这是我需要做的。

注意:这个在Java中设置BufferedImage alpha蒙版并没有做我所需要的,因为它不能很好的处理两个图像的透明度 – 它修改了第一个图片的透明度。

只需创build一个具有透明度的新BufferedImage,然后在其上绘制其他两个图像(全透明或半透明)。 这是它的样子:

图像加覆盖

示例代码(图片被称为“image.png”和“overlay.png”):

File path = ... // base path of the images // load source images BufferedImage image = ImageIO.read(new File(path, "image.png")); BufferedImage overlay = ImageIO.read(new File(path, "overlay.png")); // create the new image, canvas size is the max. of both image sizes int w = Math.max(image.getWidth(), overlay.getWidth()); int h = Math.max(image.getHeight(), overlay.getHeight()); BufferedImage combined = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); // paint both images, preserving the alpha channels Graphics g = combined.getGraphics(); g.drawImage(image, 0, 0, null); g.drawImage(overlay, 0, 0, null); // Save as new image ImageIO.write(combined, "PNG", new File(path, "combined.png")); 

我不能给你一个具体的答案,但java.awt.AlphaComposite这里是你的朋友。 你将得到绝对的控制你想要两个图像合并。 然而,这不是直接的使用 – 你需要先学习一些graphics理论。

不知道更多关于你想要达到的效果,我只想指出,你也可以直接绘制到BufferedImage上。 所以你可以在屏幕上做任何事情,你可以在图像本身做正确的。

所以如果你想要的是一个在另一个之上绘制的,那真的很容易。 只需抓住基础图像的graphics对象,并将其他的绘制到其上。

再次,取决于你正在做的确切的效果,可能无法正常工作。 更多的细节将允许更好的帮助。 例如,这是AlphaComposite的一项工作,就像其他响应者提到的那样,或者是一个自定义的ImageOp(或现有的ImageOps的某种组合)。