基本思想是在原始图像上应用AlphaComposite蒙版,该图像已填充LinearGradientPaint
所以,我们首先加载原始图像……
BufferedImage original = ImageIO.read(new File("/an/image/somewhere"));
然后我们创建一个相同大小的掩蔽图像……
BufferedImage alphaMask = new BufferedImage(original.getWidth(), original.getHeight(), BufferedImage.TYPE_INT_ARGB);
然后我们用LinearGradientPaint填充掩蔽图像……
Graphics2D g2d = alphaMask.createGraphics();
LinearGradientPaint lgp = new LinearGradientPaint(
new Point(0, 0),
new Point(alphaMask.getWidth(), 0),
new float[]{0, 1},
new Color[]{new Color(0, 0, 0, 255), new Color(0, 0, 0 , 0)});
g2d.setPaint(lgp);
g2d.fillRect(0, 0, alphaMask.getWidth(), alphaMask.getHeight());
g2d.dispose();
这里重要的是,我们实际上并不关心物理颜色,只关心它的alpha属性,因为这将决定两个图像如何被掩盖在一起……
然后,我们应用面具……
BufferedImage faded = applyMask(original, alphaMask, AlphaComposite.DST_IN);
实际上这称为实用方法…
public static BufferedImage applyMask(BufferedImage sourceImage, BufferedImage maskImage, int method) {
BufferedImage maskedImage = null;
if (sourceImage != null) {
int width = maskImage.getWidth();
int height = maskImage.getHeight();
maskedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D mg = maskedImage.createGraphics();
int x = (width - sourceImage.getWidth()) / 2;
int y = (height - sourceImage.getHeight()) / 2;
mg.drawImage(sourceImage, x, y, null);
mg.setComposite(AlphaComposite.getInstance(method));
mg.drawImage(maskImage, 0, 0, null);
mg.dispose();
}
return maskedImage;
}
这基本上使用AlphaComposite中的“目的地”将蒙版应用到原始图像上,这导致……
(原件在左边,alpha在右边)
为了证明这一点,我将框架内容窗格的背景颜色更改为RED