Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

Java BufferedImage getting red, green and blue individually

The getRGB() method returns a single int. How can I get individually the red, green and blue colors all as the values between 0 and 255?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A pixel is represented by a 4-byte (32 bit) integer, like so:

00000000 00000000 00000000 11111111
^ Alpha  ^Red     ^Green   ^Blue

So, to get the individual color components, you just need a bit of binary arithmetic:

int rgb = getRGB(...);
int red = (rgb >> 16) & 0x000000FF;
int green = (rgb >>8 ) & 0x000000FF;
int blue = (rgb) & 0x000000FF;

This is indeed what the java.awt.Color class methods do:

  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       }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...