简体   繁体   English

Java BufferedImage:Alpha更改使低Alpha区域显示为黑色

[英]Java BufferedImage: Alpha change makes low alpha areas appear black

I have a method to change the alpha value of a BufferedImage in Java. 我有一种方法可以更改Java中BufferedImage的alpha值。 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). 当对Java byte进行签名时(在[-128 ... 127]范围内),它将永远不会更改alpha (对于字节范围内的任何值,x%255 = x)。

However, you want the alpha to be in range [0...255]. 但是,您希望Alpha在[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... 但是只更改运算符是不会做的,因为您将值存储在一个byte ,这将迫使该值再次进入[-128 ... 127]范围...

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. 如果以前像素以前是100%透明的,则该像素中的颜色无关紧要。 For that reason, it might be normalized to black (all 0 s) for efficiency. 因此,可以将其归一化为黑色(全部为0 s)以提高效率。 It might not be possible to restore the original color. 可能无法恢复原始颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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