Reputation: 183
I am searching for a way to draw a PNG image (with an alpha channel) in Java which is of a grayscale color and then overlay a transparent color, say Green at 75% opacity, on top of it to change the color. To be clear, the resultant image will be a direct result of placing a transparent color over top of it, and will not be the result of any special type of blending.
For example, I would draw the following image:
And then overlay RGB color (102, 255, 0, alpha) on top of the image:
The method of drawing the color over the image will need to be such that it will not interfere with other images on the screen in close proximity. This would behave similarly to Adobe Photoshop's color overlay feature. Two images could have separate color overlays but the separate overlays will not conflict with eachother.
With thanks to leonbloy, I believe that AlphaComposit using "SRC_OVER" can solve this, I could then use a method to save the result as a new BufferedImage which would prevent the overlay from affecting any other image objects on screen.
I will post results as I test this.
Upvotes: 4
Views: 5797
Reputation: 183
I was able to use AlphaComposite, Graphics2D, and BufferedImage to acquire the desired effect.
@Override
public void paintComponent(Graphics g) {
BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D gbi = result.createGraphics();
BufferedImage x = null;
try {
x = ImageIO.read(getClass().getResource("/resources/someimage.png"));
} catch (IOException ex) {
Logger.getLogger(CanvasPanel.class.getName()).log(Level.SEVERE, null, ex);
}
gbi.drawImage(x, 0, 0, this);
gbi.setColor(selectedColor);
gbi.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.75f));
gbi.fillRect(0, 0, width, height);
g.drawImage(result, 0, 0, this);
}
Upvotes: 6