Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get RGB value from hexadecimal color code in java

I have a decimal color code (eg: 4898901). I am converting it into a hexadecimal equivalent of that as 4ac055. How to get the red, green and blue component value from the hexadecimal color code?

like image 890
androidGuy Avatar asked Sep 15 '11 07:09

androidGuy


2 Answers

Assuming this is a string:

// edited to support big numbers bigger than 0x80000000
int color = (int)Long.parseLong(myColorString, 16);
int r = (color >> 16) & 0xFF;
int g = (color >> 8) & 0xFF;
int b = (color >> 0) & 0xFF;
like image 197
MByD Avatar answered Oct 03 '22 22:10

MByD


If you have a string this way is a lot nicer:

Color color =  Color.decode("0xFF0000");
int red = color.getRed();
int blue = color.getBlue();
int green = color.getGreen();

If you have a number then do it this way:

Color color = new Color(0xFF0000);

Then of course to get the colours you just do:

float red = color.getRed();
float green = color.getGreen();
float blue = color.getBlue();
like image 43
Daniel Ryan Avatar answered Oct 03 '22 22:10

Daniel Ryan