Bufferedimage bitmask operations - apply a color to an image using another image as a mask
I have tw开发者_开发知识库o BufferedImage objects, src
and dest
. Both are grayscale, src
is 1bpc (B&W basically), and dest
could really be any sort of color space/bpc/etc.
I need to be able to draw some color onto dest
using src
as a bitmask. Basically, if the pixel in src
is black, then dest should be changed to the draw color. But if the pixel in src
is white, the dest
should be left alone.
If it matters, I am also applying an affine transform during the draw operation.
Graphics2D g = dest.createGraphics();
// do something here???
g.drawImage(src, transform, null);
g.dispose();
In a pure B&W world this would involve a simple |
of the pixel values together - but it seems like there's probably a correct way to do this using image operations.
Gut instinct says that this is a matter of setting the Composite and some sort of alpha - but I'm at a total loss as to what values to use. I have very little experience with the more advanced aspects of graphics 2d - any pointers would be greatly appreciated.
I think that I've come up with an effective solution using this article
This is certainly efficient, although I'm not sure if follows best practices or not:
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();
精彩评论