关于java:bufferedImage.getRGB(x,y)不产生alpha

bufferedImage.getRGB(x, y) does not yield alpha

我有一个BufferedImage i,我想从该image的某个像素(包括Alpha值)获取颜色。 使用xy坐标识别像素。

这是我尝试过的:

1
Color c = new Color(i.getRGB(x, y));

由于某种原因,新的颜色对象包含正确的RGB,但是alpha丢失了。

我究竟做错了什么?

提前致谢


您使用的单参数Color构造函数将丢弃alpha信息。请改用两参数版本,并将true传递给hasalpha

1
Color c = new Color(i.getRGB(x, y), true);

相关的Javadoc:

Color(int rgb)

Creates an opaque sRGB color with the specified combined RGB value consisting of the red component in bits 16-23, the green component in bits 8-15, and the blue component in bits 0-7.

Color(int rgba, boolean hasalpha)

Creates an sRGB color with the specified combined RGBA value consisting of the alpha component in bits 24-31, the red component in bits 16-23, the green component in bits 8-15, and the blue component in bits 0-7.


Alpha不会丢失。

您必须使用(int,boolean)构造函数来获取像素信息,并指定布尔值是否具有alpha值,还是必须使用Red,Green,Blue和Alpha这4个值的构造函数。

JavaDoc中的(int,int,int,int)构造函数信息

为了缩短代码,您始终可以将以下所有代码替换为
Color color = new Color(i.getRGB(x, y), true);
告诉颜色构造函数像素信息确实包含Alpha值。

JavaDoc中的(int,boolean)构造函数信息

请注意,有时在检索alpha时,以下方式可能会返回-1,在这种情况下,这意味着它将循环回到255,因此您必须执行256-1才能获取实际的alpha值。此代码段演示了如何加载图像并在特定坐标(例如0,0)上获得该图像的颜色。以下示例可以向您展示如何检索每个颜色值(包括alpha),并将其重构为新的Color。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;

public class main {

    public static void main(String [] args){
        BufferedImage image = null;
        try {
            image = ImageIO.read(new URL("image.png"));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        int pixel = image.getRGB(0, 0);

        int alpha = (pixel >> 24) & 0xff;
        int red = (pixel >> 16) & 0xff;
        int green = (pixel >> 8) & 0xff;
        int blue = (pixel >> 0) & 0xff;

        Color color1 = new Color(red, green, blue, alpha);

        //Or use
        Color color2 = new Color(image .getRGB(0, 0), true);

    }
   }

您可以看到BufferedImages getRGB(int,int)JavaDoc,它说:

Returns an integer pixel in the default RGB color model (TYPE_INT_ARGB) and default sRGB colorspace. Color conversion takes place if this default model does not match the image ColorModel. There are only 8-bits of precision for each color component in the returned data when using this method.

这意味着还将获取Alpha值。