Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert RGB values to Integer

So in a BufferedImage, you receive a single integer that has the RGB values represented in it. So far I use the following to get the RGB values from it:

// 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); 

And so far, it works.

What I need to do is figure out how to get an integer so I can use BufferedImage.setRGB(), because that takes the same type of data it gave me.

like image 661
Rahat Ahmed Avatar asked Jan 26 '11 04:01

Rahat Ahmed


People also ask

How do you convert RGB to decimal?

The equation is very basic math. 0 is 0 and 255 is 1, you simply take the number of bits in that channel and divide it by the maximum (255) to find it's normalized (decimal) value.

Why is RGB 255 and not 256?

RGB (Red, Green, Blue) are 8 bit each. The range for each individual colour is 0-255 (as 2^8 = 256 possibilities). The combination range is 256*256*256. By dividing by 255, the 0-255 range can be described with a 0.0-1.0 range where 0.0 means 0 (0x00) and 1.0 means 255 (0xFF).


1 Answers

I think the code is something like:

int rgb = red; rgb = (rgb << 8) + green; rgb = (rgb << 8) + blue; 

Also, I believe you can get the individual values using:

int red = (rgb >> 16) & 0xFF; int green = (rgb >> 8) & 0xFF; int blue = rgb & 0xFF; 
like image 64
camickr Avatar answered Sep 23 '22 02:09

camickr