Chris
Chris

Reputation: 618

How does image transparency work and how do I implement it?

I'm planning to make a colored overlay to put over a map of my city. However I want the overlay to only be semitransparent.

I know about rgba values and how the a value is what determines the transparency, but when working with the BufferedImage class, I can only assign one color to one pixel. Lets say you're given two images of the same size. How would I go about overlaying one over the other with the overlay having only half the opacity as the original image.

Upvotes: 1

Views: 89

Answers (1)

Chris K
Chris K

Reputation: 1723

Modify the alpha channel like this (opacity is from 0 to 255):

BufferedImage changeOpacity(BufferedImage img, int opacity) {
    final BufferedImage ret = new BufferedImage(img.getWidth(),
                                                img.getHeight(),
                                                BufferedImage.TYPE_INT_ARGB);
    final RescaleOp ro = new RescaleOp(new float[] {1f, 1f, 1f, ((float)opacity)/255f},
                                       new float[] {0f, 0f, 0f, 0f},
                                       null);
    ro.filter(img, ret);
    return ret;
}

Then overlay two images with alpha channels like this:

BufferedImage overlay(BufferedImage img1, BufferedImage img2) {
    final BufferedImage combined = new BufferedImage(img1.getWidth(),
                                                     img1.getHeight(),
                                                     BufferedImage.TYPE_INT_ARGB);
    final Graphics g = combined.getGraphics();
    g.drawImage(img1, 0, 0, null);
    g.drawImage(img2, 0, 0, null);
    return combined;
}

Upvotes: 1

Related Questions