简体   繁体   中英

Java BufferedImage: Alpha change makes low alpha areas appear black

I have a method to change the alpha value of a BufferedImage in Java. This is my code:

public static void setAlpha(BufferedImage img, byte alpha) {
    alpha %= 0xff;
    for (int cx=0;cx<img.getWidth();cx++) {
        for (int cy=0;cy<img.getHeight();cy++) {
            int color = img.getRGB(cx, cy);
            color &= 0x00ffffff;
            color |= (alpha << 24);
            img.setRGB(cx, cy, color);
        }
    }
}

When I use this function all areas of the image that have been transparent before become black. Why?

EDIT:

Thank you very much for your help. Now I figured out, what the problem was. This is my working function:

public static void changeAlpha(BufferedImage img, float alphaPercent) {
    for (int cx=0;cx<img.getWidth();cx++) {
        for (int cy=0;cy<img.getHeight();cy++) {
            int color = img.getRGB(cx, cy);
            byte alpha = (byte) (color >> 24);
            alpha = (byte) ((float) (int) (alpha & 0xff) * alphaPercent);
            color &= 0x00ffffff;
            color |= ((alpha & 0xff) << 24);
            img.setRGB(cx, cy, color);
        }
    }
}

The statement

alpha %= 0xff;

seems a bit odd. As a Java byte is signed (and in range [-128...127]) this will never change alpha (x % 255 = x for any value in the byte range).

However, you want the alpha to be in range [0...255]. Normally, you do this using the & operator. But just changing the operator won't do, as you store the value in a byte , which will force the value into the range [-128...127] again...

Instead, try (inside your loop):

color |= ((alpha & 0xff) << 24);

Alternatively, you could write something like:

int alphaValue = alpha & 0xff;
for (...) {
    for (...) {
        // Inside the loop:
        color |= (alphaValue << 24);
    }
}

Finally, a note on transparency. If your pixels previously have been 100% transparent before, the color in that pixel does not matter. For that reason, it might be normalized to black (all 0 s) for efficiency. It might not be possible to restore the original color.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM