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

时间:2011-09-21 22:02:18

标签: java bufferedimage graphics2d

我有两个BufferedImage对象,srcdest。两者都是灰度,src是1bpc(基本上是B& W),而dest实际上可以是任何颜色空间/ bpc /等。

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

如果重要,我也在抽奖行动中应用仿射变换。

Graphics2D g = dest.createGraphics();
// do something here???
g.drawImage(src, transform, null);
g.dispose();

在一个纯粹的B& W世界中,这将涉及一个简单的|像素值 - 但似乎可能有一种正确的方法来使用图像操作。

Gut本能说这是设置Composite和某种alpha的问题 - 但我完全不知道要使用什么值。我对图形2d的更高级方面的经验很少 - 任何指针都会非常感激。

1 个答案:

答案 0 :(得分:0)

我认为我已经使用this article

提出了有效的解决方案

这肯定是有效的,虽然我不确定是否遵循最佳做法:

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();