How can I convert hex color to RGB code in Java? Mostly in Google, samples are on how to convert from RGB to hex.
you can do it simply as below:
public static int[] getRGB(final String rgb)
{
final int[] ret = new int[3];
for (int i = 0; i < 3; i++)
{
ret[i] = Integer.parseInt(rgb.substring(i * 2, i * 2 + 2), 16);
}
return ret;
}
For Example
getRGB("444444") = 68,68,68
getRGB("FFFFFF") = 255,255,255
For Android development, I use:
int color = Color.parseColor("#123456");
Convert it to an integer, then divmod it twice by 16, 256, 4096, or 65536 depending on the length of the original hex string (3, 6, 9, or 12 respectively).
For Android Kotlin users:
"#FFF".longARGB()?.let{ Color.parceColor(it) }
"#FFFF".longARGB()?.let{ Color.parceColor(it) }
fun String?.longARGB(): String? {
if (this == null || !startsWith("#")) return null
// #RRGGBB or #AARRGGBB
if (length == 7 || length == 9) return this
// #RGB or #ARGB
if (length in 4..5) {
val rgb = "#${this[1]}${this[1]}${this[2]}${this[2]}${this[3]}${this[3]}"
if (length == 5) {
return "$rgb${this[4]}${this[4]}"
}
return rgb
}
return null
}
public static void main(String[] args) {
int hex = 0x123456;
int r = (hex & 0xFF0000) >> 16;
int g = (hex & 0xFF00) >> 8;
int b = (hex & 0xFF);
}
For shortened hex code like #fff or #000
int red = "colorString".charAt(1) == '0' ? 0 :
"colorString".charAt(1) == 'f' ? 255 : 228;
int green =
"colorString".charAt(2) == '0' ? 0 : "colorString".charAt(2) == 'f' ?
255 : 228;
int blue = "colorString".charAt(3) == '0' ? 0 :
"colorString".charAt(3) == 'f' ? 255 : 228;
Color.rgb(red, green,blue);