How to convert hex to rgb using Java?

后端 未结 19 1940
-上瘾入骨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 14:18

    To elaborate on the answer @xhh provided, you can append the red, green, and blue to format your string as "rgb(0,0,0)" before returning it.

    /**
    * 
    * @param colorStr e.g. "#FFFFFF"
    * @return String - formatted "rgb(0,0,0)"
    */
    public static String hex2Rgb(String colorStr) {
        Color c = new Color(
            Integer.valueOf(hexString.substring(1, 3), 16), 
            Integer.valueOf(hexString.substring(3, 5), 16), 
            Integer.valueOf(hexString.substring(5, 7), 16));
    
        StringBuffer sb = new StringBuffer();
        sb.append("rgb(");
        sb.append(c.getRed());
        sb.append(",");
        sb.append(c.getGreen());
        sb.append(",");
        sb.append(c.getBlue());
        sb.append(")");
        return sb.toString();
    }
    
    0 讨论(0)
提交回复
热议问题