0

I'm wondering how a person could change the alpha transparency of a color, if given the hex color code. For example if given Color.red.getRGB() how could I change it's alpha to 0x80?

To put this in context, I'm working on a static method to tint a BufferedImage, by creating a graphics device from the given image, and rendering a half transparent mask with that, disposing of the graphics, and returning the image. It works, but you have to define the alpha yourself in the given hex color code. I want to give a Color object, and double between 0 and 1.0 to determine the intensity of the tinting. Here's my code so far:

public static Image tintImage(Image loadImg, int color) {
    Image gImage = loadImg;
    Graphics2D g = gImage.image.createGraphics();
    Image image = new Image(new BufferedImage(loadImg.width, loadImg.height, BufferedImage.TYPE_INT_ARGB));
    for(int x = 0; x < loadImg.width; x++) {
        for(int y = 0; y < loadImg.height; y++) {
            if(loadImg.image.getRGB(x, y) >> 24 != 0x00) {
                image.image.setRGB(x, y, color);
            }
        }
    }
    g.drawImage(image.image, 0, 0, null);
    g.dispose();

    return gImage;
}
  • Also consider `RescaleOp`, seen [here](http://stackoverflow.com/a/5864503/230513), to adjust the image's color bands. – trashgod Oct 04 '13 at 23:31

1 Answers1

2

You can construct a new Color from the old one with the lower alpha.

Color cNew = new Color(cOld.getRed(), cOld.getGreen(), cOld.getBlue(), 0x80);

Using the Color(int r, int g, int b, int a) constructor.

arynaq
  • 6,710
  • 9
  • 44
  • 74