Java-将十六进制颜色转换为十进制颜色

时间:2019-06-15 10:58:38

标签: java colors hex decimal

我想将十六进制颜色(如#FF0000)转换为十进制颜色(如16711680)。我该怎么做?

我已经尝试使用Color类,但是找不到正确转换颜色的方法。

Color hexcolor = Color.decode("#FF0000");
//And then?

2 个答案:

答案 0 :(得分:3)

验证输入的一种方法是:

public static int parseHex(final String color) {
    final Matcher mx = Pattern.compile("^#([0-9a-z]{6})$", CASE_INSENSITIVE).matcher(color);
    if(!mx.find())
        throw new IllegalArgumentException("invalid color value");
    return Integer.parseInt(mx.group(1), 16);
}

尽管不是必需的,但您可以分别解析每个颜色分量:

public static int parseColor(final String color) {
    final Matcher mx = Pattern.compile("^#([0-9a-z]{2})([0-9a-z]{2})([0-9a-z]{2})$", CASE_INSENSITIVE).matcher(color);
    if(!mx.find())
        throw new IllegalArgumentException("invalid color value");
    final int R = Integer.parseInt(mx.group(1), 16);
    final int G = Integer.parseInt(mx.group(2), 16);
    final int B = Integer.parseInt(mx.group(3), 16);
    return (R << 16) + (G << 8) + B;
}

如果对Color的依赖不是问题,则可以使用:

public static int parseColor(final String color) {
    final Color c = Color.decode(color);
    return (c.getRed() << 16) + (c.getGreen() << 8) + c.getBlue();
}

相反,您也可以这样做:

public static int parseColor(final String color) {
    return 0xFFFFFF & (Color.decode(color).getRGB() >> 8);
}

但是由于需要了解内部表示,因此不建议这样做。

答案 1 :(得分:1)

由于vlumi的评论,我已经找到答案了。

https://www.javatpoint.com/java-hex-to-decimal

public static int convertHEXtoDecimal(String HEX) {
    String hex = HEX.replaceAll("#", "");
    String digits = "0123456789ABCDEF";
    hex = hex.toUpperCase();
    int val = 0;
    for (int i = 0; i < hex.length(); i++) {
        char c = hex.charAt(i);
        int d = digits.indexOf(c);
        val = 16 * val + d;
    }
    return val;
}
相关问题