How to convert hex to rgb using Java?

后端 未结 19 2103
-上瘾入骨i
-上瘾入骨i 2020-11-27 13:46

How can I convert hex color to RGB code in Java? Mostly in Google, samples are on how to convert from RGB to hex.

19条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 13:55

    A hex color code is #RRGGBB

    RR, GG, BB are hex values ranging from 0-255

    Let's call RR XY where X and Y are hex character 0-9A-F, A=10, F=15

    The decimal value is X*16+Y

    If RR = B7, the decimal for B is 11, so value is 11*16 + 7 = 183

    public int[] getRGB(String rgb){
        int[] ret = new int[3];
        for(int i=0; i<3; i++){
            ret[i] = hexToInt(rgb.charAt(i*2), rgb.charAt(i*2+1));
        }
        return ret;
    }
    
    public int hexToInt(char a, char b){
        int x = a < 65 ? a-48 : a-55;
        int y = b < 65 ? b-48 : b-55;
        return x*16+y;
    }
    

提交回复
热议问题