我需要在 Java 中合并两个图像 (BufferedImage)。如果没有透明度,那将不是问题。基本图像已经具有一定的透明度。我想保持原样并对其应用“蒙版”,即第二张图像。第二张图片没有不透明的像素,实际上它几乎是完全透明的,只是有一些不太透明的像素来提供某种“光效”,比如反射。重要细节:我不想在屏幕上执行此操作,使用图形,我需要获得一个带有结果合并的 BufferedImage。
谁能帮帮我? 谢谢!
细节:合并两个图像并保持透明度。这是我需要做的。
注意:这个 Set BufferedImage alpha mask in Java不符合我的要求,因为它不能很好地处理具有透明度的两个图像 - 它会修改第一张图片的透明度。
最佳答案
只需创建一个具有透明度的新 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);
g.dispose();
// Save as new image
ImageIO.write(combined, "PNG", new File(path, "combined.png"));
关于java - 合并两个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2318020/