2011-09-21 69 views
1

我有兩個BufferedImage對象,srcdest。兩者都是灰度,src是1bpc(基本上B & W),dest可能真的是任何類型的色彩空間/ bpc/etc。Bufferedimage位掩碼操作 - 將圖像的顏色應用於另一個圖像作爲蒙版

我需要能夠使用src作爲位掩碼在dest上畫一些顏色。基本上,如果src中的像素是黑色的,則應將dest更改爲繪製顏色。但是如果src中的像素是白色,則應該單獨保留dest

如果重要,我也在繪製操作中應用仿射變換。

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

在純B & W世界,這將涉及到的像素值的簡單|在一起 - 但看起來有可能做到這一點使用圖像操作的正確道路。

Gut本能說這是一個設置複合和某種阿爾法的問題 - 但我完全喪失了使用什麼值。我對圖形2D的更高級的方面有很少的經驗 - 任何指針將不勝感激。

回答

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