Java BuffereImage位掩码操作-使用另一个图像作为掩码将颜色应用于图像

Java BuffereImage位掩码操作-使用另一个图像作为掩码将颜色应用于图像,java,bufferedimage,graphics2d,Java,Bufferedimage,Graphics2d,我有两个BuffereImage对象,src和dest。两者都是灰度,src是1bpc(基本上是黑白的,dest可以是任何一种颜色空间/bpc/等等 我需要能够使用src作为位掩码在dest上绘制一些颜色。基本上,如果src中的像素为黑色,则dest应更改为绘图颜色。但是,如果src中的像素为白色,则应单独保留dest 如果有关系的话,我还在绘制操作期间应用仿射变换 Graphics2D g = dest.createGraphics(); // do something here??? g.d

我有两个BuffereImage对象,
src
dest
。两者都是灰度,
src
是1bpc(基本上是黑白的,
dest
可以是任何一种颜色空间/bpc/等等

我需要能够使用
src
作为位掩码在
dest
上绘制一些颜色。基本上,如果
src
中的像素为黑色,则dest应更改为绘图颜色。但是,如果
src
中的像素为白色,则应单独保留
dest

如果有关系的话,我还在绘制操作期间应用仿射变换

Graphics2D g = dest.createGraphics();
// do something here???
g.drawImage(src, transform, null);
g.dispose();
在一个纯粹的黑白世界中,这将涉及一个简单的
|
像素值组合,但似乎有一种使用图像操作的正确方法


直觉告诉我,这是一个设置合成和某种阿尔法的问题,但我完全不知道该使用什么值。我对2d图形的更高级方面几乎没有经验-任何指针都会非常感激。

我认为我已经想出了一个有效的解决方案,使用

这当然是有效的,尽管我不确定是否遵循最佳实践:

BufferedImage dest; // input
BufferedImage src; // input

...

byte[] r = new byte[]{(byte)0,(byte)255}; // 255=black, we could set it to some other gray component as desired
byte[] g = new byte[]{(byte)0,(byte)255};
byte[] b = new byte[]{(byte)0,(byte)255};
byte[] a = new byte[]{(byte)255,(byte)0};
IndexColorModel bitmaskColorModel = new IndexColorModel(1, 2, r, g, b, a);

BufferedImage masked = new BufferedImage(bitmaskColorModel, src.getRaster(), false, null);

Graphics2D g = dest.createGraphics();
g.drawImage(masked, transform, null);
g.dispose();