Java BufferedImage分别获得红色,绿色和蓝色

del*_*ber 49 java bufferedimage

getRGB()方法返回单个int.如何将红色,绿色和蓝色单独作为0到255之间的值?

Joã*_*lva 114

像素由4字节(32位)整数表示,如下所示:

00000000 00000000 00000000 11111111
^ Alpha  ^Red     ^Green   ^Blue
Run Code Online (Sandbox Code Playgroud)

因此,要获得各个颜色组件,您只需要一些二进制算术:

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

这确实是java.awt.Color类方法的作用:

  553       /**
  554        * Returns the red component in the range 0-255 in the default sRGB
  555        * space.
  556        * @return the red component.
  557        * @see #getRGB
  558        */
  559       public int getRed() {
  560           return (getRGB() >> 16) & 0xFF;
  561       }
  562   
  563       /**
  564        * Returns the green component in the range 0-255 in the default sRGB
  565        * space.
  566        * @return the green component.
  567        * @see #getRGB
  568        */
  569       public int getGreen() {
  570           return (getRGB() >> 8) & 0xFF;
  571       }
  572   
  573       /**
  574        * Returns the blue component in the range 0-255 in the default sRGB
  575        * space.
  576        * @return the blue component.
  577        * @see #getRGB
  578        */
  579       public int getBlue() {
  580           return (getRGB() >> 0) & 0xFF;
  581       }
Run Code Online (Sandbox Code Playgroud)


Mic*_*zek 71

Java的Color类可以进行转换:

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


Mat*_*nen 8

你需要一些基本的二进制算术来分割它:

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

(或者可能反过来说,我老实说不记得了,文档没有给我一个即时答案)


Def*_*efd 7

对于简单的颜色操作,您可以使用

bufImg.getRaster().getPixel(x,y,outputChannels)
Run Code Online (Sandbox Code Playgroud)

outputChannels是一个用于存储获取的像素的数组.它的长度取决于图像的实际通道数.例如,RGB图像具有3个通道; RGBA图像有4个通道.

此方法有3种输出类型:int,float和double.要获得颜色值范围为0~255,实际参数outputChannels应为int []数组.