How can I convert hex color to RGB code in Java? Mostly in Google, samples are on how to convert from RGB to hex.
I guess this should do it:
/**
*
* @param colorStr e.g. "#FFFFFF"
* @return
*/
public static Color hex2Rgb(String colorStr) {
return new Color(
Integer.valueOf( colorStr.substring( 1, 3 ), 16 ),
Integer.valueOf( colorStr.substring( 3, 5 ), 16 ),
Integer.valueOf( colorStr.substring( 5, 7 ), 16 ) );
}
Hexidecimal color codes are already rgb. The format is #RRGGBB
public static Color hex2Rgb(String colorStr) {
try {
// Create the color
return new Color(
// Using Integer.parseInt() with a radix of 16
// on string elements of 2 characters. Example: "FF 05 E5"
Integer.parseInt(colorStr.substring(0, 2), 16),
Integer.parseInt(colorStr.substring(2, 4), 16),
Integer.parseInt(colorStr.substring(4, 6), 16));
} catch (StringIndexOutOfBoundsException e){
// If a string with a length smaller than 6 is inputted
return new Color(0,0,0);
}
}
public static String rgbToHex(Color color) {
// Integer.toHexString(), built in Java method Use this to add a second 0 if the
// .Get the different RGB values and convert them. output will only be one character.
return Integer.toHexString(color.getRed()).toUpperCase() + (color.getRed() < 16 ? 0 : "") + // Add String
Integer.toHexString(color.getGreen()).toUpperCase() + (color.getGreen() < 16 ? 0 : "") +
Integer.toHexString(color.getBlue()).toUpperCase() + (color.getBlue() < 16 ? 0 : "");
}
I think that this wil work.
For JavaFX
import javafx.scene.paint.Color;
.
Color whiteColor = Color.valueOf("#ffffff");
If you don't want to use the AWT Color.decode, then just copy the contents of the method:
int i = Integer.decode("#FFFFFF");
int[] rgb = new int[]{(i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF};
Integer.decode handles the # or 0x, depending on how your string is formatted
Actually, there's an easier (built in) way of doing this:
Color.decode("#FFCCEE");