将RGB值转换为Integer

Rah*_*med 48 java bufferedimage

因此在a中BufferedImage,您会收到一个整数,其中包含RGB值.到目前为止,我使用以下内容从中获取RGB值:

// rgbs is an array of integers, every single integer represents the
// RGB values combined in some way
int r = (int) ((Math.pow(256,3) + rgbs[k]) / 65536);
int g = (int) (((Math.pow(256,3) + rgbs[k]) / 256 ) % 256 );
int b = (int) ((Math.pow(256,3) + rgbs[k]) % 256);
Run Code Online (Sandbox Code Playgroud)

到目前为止,它的工作原理.

我需要做的是弄清楚如何获得一个整数,以便我可以使用BufferedImage.setRGB(),因为它采用了它给我的相同类型的数据.

cam*_*ckr 87

我认为代码是这样的:

int rgb = red;
rgb = (rgb << 8) + green;
rgb = (rgb << 8) + blue;
Run Code Online (Sandbox Code Playgroud)

此外,我相信您可以使用以下方式获取个人价值:

int red = (rgb >> 16) & 0xFF;
int green = (rgb >> 8) & 0xFF;
int blue = rgb & 0xFF;
Run Code Online (Sandbox Code Playgroud)


Kit*_*YMG 27

int rgb = ((r&0x0ff)<<16)|((g&0x0ff)<<8)|(b&0x0ff);
Run Code Online (Sandbox Code Playgroud)

如果您知道您的r,g和b值永远不会> 255或<0,则不需要&0x0ff

Additionaly

int red = (rgb>>16)&0x0ff;
int green=(rgb>>8) &0x0ff;
int blue= (rgb)    &0x0ff;
Run Code Online (Sandbox Code Playgroud)

无需倍增.


小智 20

int rgb = new Color(r, g, b).getRGB();
Run Code Online (Sandbox Code Playgroud)


小智 18

如果r,g,b =每种颜色的0到255的3个整数值

然后

rgb = 65536 * r + 256 * g + b;
Run Code Online (Sandbox Code Playgroud)

单个rgb值是r,g,b的复合值,总计16777216个可能的阴影.

  • 我会将其修改为 `rgb = 0xFFFF * r + 0xFF * g + b;` 以提高可读性 (2认同)
  • 0xFF = 255.必须是0x100.同样适用于0XFFFF (2认同)

Aja*_*ant 5

要获得单个颜色值,您可以对像素(x,y)使用如下所示的颜色。

import java.awt.Color;
import java.awt.image.BufferedImage;

Color c = new Color(buffOriginalImage.getRGB(x,y));
int red = c.getRed();
int green = c.getGreen();
int blue = c.getBlue();
Run Code Online (Sandbox Code Playgroud)

以上将为您提供范围为 0 到 255 的红色、绿色和蓝色的整数值。

要从 RGB 设置值,您可以通过以下方式进行:

Color myColour = new Color(red, green, blue);
int rgb = myColour.getRGB();

//Change the pixel at (x,y) ti rgb value
image.setRGB(x, y, rgb);
Run Code Online (Sandbox Code Playgroud)

请注意,以上更改了单个像素的值。因此,如果您需要更改整个图像的值,您可能需要使用两个 for 循环遍历图像。