如何从Android设备上的位图获取RGB值?

问题描述:

我想在android中获取位图的RGB值,但到目前为止我无法做到这一点。我的目标是获取位图的每个像素的RGB值。 Android或其他任何特定功能?
另外我想知道我需要colorMatrix()函数吗?
这对我的项目非常重要。谢谢

I want to get RGB values of bitmap in android but I cant do this so far. My aim is to obtain RGB values for each pixel of bitmap. Is there any specific function for android or anything else ?? Also I wonder that do I need colorMatrix() function? It is very important for my project. Thanks

这可能会稍晚,但要清除使用& 0xff的混淆:

This may be slightly late, but to clear up the confusion with the use of &0xff:

在Java中,int是32位,因此每个像素的(A)RGB值以4个字节打包。
换句话说,在ARGB_8888模型中具有值R(123),G(93),B(49)= FF7B 5D31的像素。其中Alpha = FF,R = 7B,G = 5D,B = 31.但是这被存储为int -8692431。

In Java ints are 32 bits, so the (A)RGB values for each pixel are packed in 4 bytes. In other words, a pixel with the values R(123), G(93), B(49) = FF7B 5D31 in the ARGB_8888 model. Where Alpha = FF, R = 7B, G = 5D, B = 31. But this is stored as an int as -8692431.

因此,提取绿色值从-8692431开始,我们需要将5D向右移8位,如您所知。这给出00FF 7B5D。因此,如果我们只是采取该值,我们将留下16743261作为我们的绿色值。因此,我们按位 - 并且该值具有0xFF的掩码(相当于0000 00FF)并且将导致00FF 7B5D被屏蔽到0000 005D。所以我们已经提取了93的Green值。

So, to extract the Green value from -8692431, we need to shift the 5D by 8 bits to the right, as you know. This gives 00FF 7B5D. So, if we were just to take that value we would be left with 16743261 as our Green value. Therefore, we bitwise-and that value with the mask of 0xFF (which is equivalent to 0000 00FF) and will result in 00FF 7B5D being 'masked' to 0000 005D. So we have extracted our Green value of 93.

我们可以为每次提取使用相同的0xFF掩码,因为这些值都被移位以暴露所需的两个字节为最不重要的。因此,之前建议的代码为:

We can use the same mask of 0xFF for each extraction because the values have all been shifted to expose the desired two bytes as the least significant. Hence the previously suggested code of:

int p = pixel[index];

int R = (p >> 16) & 0xff;
int G = (p >> 8) & 0xff;
int B = p & 0xff;

如果它更清楚,你可以执行以下的等效操作:

If it makes it clearer, you can perform the equivalent operation of:

int R = (p & 0xff0000) >> 16;
int G = (p & 0x00ff00) >> 8;
int B = (p & 0x0000ff) >> 0;

为简洁起见,可以删除额外的0,并且可以将其写为

For brevity, the extra 0s can be dropped, and it can be written as

int R = (p & 0xff0000) >> 16;
int G = (p & 0xff00) >> 8;
int B = p & 0xff;

但是请注意,可以使用其他颜色模型,例如RGB_555,它将每个像素存储为2字节,RGB通道的精度不同。因此,在执行提取之前,应检查位图正在使用的模型,因为颜色的存储方式可能不同。

Note however, that alternative colour models may be used, such as RGB_555 which stores each pixel as just 2 bytes, with varying precision for the RGB channels. So you should check the model that your bitmap is using before you perform the extraction, because the colours may be stored differently.