[java] 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.

This question is related to java bufferedimage

The answer is


int rgb = ((r&0x0ff)<<16)|((g&0x0ff)<<8)|(b&0x0ff);

If you know that your r, g, and b values are never > 255 or < 0 you don't need the &0x0ff

Additionaly

int red = (rgb>>16)&0x0ff;
int green=(rgb>>8) &0x0ff;
int blue= (rgb)    &0x0ff;

No need for multipling.


int rgb = new Color(r, g, b).getRGB();

if r, g, b = 3 integer values from 0 to 255 for each color

then

rgb = 65536 * r + 256 * g + b;

the single rgb value is the composite value of r,g,b combined for a total of 16777216 possible shades.


To get individual colour values you can use Color like following for pixel(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();

The above will give you the integer values of Red, Green and Blue in range of 0 to 255.

To set the values from RGB you can do so by:

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

Please be advised that the above changes the value of a single pixel. So if you need to change the value entire image you may need to iterate over the image using two for loops.