Java - Convert a HEX color to a decimal color

Stijn Bannink :

I want to convert a HEX color (Like #FF0000) to a decimal color (Like 16711680). How do I need to do this?

I've already tried using the Color class, but I can't find a method for converting the colors correctly.

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

One way validating input could be:

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);
}

Although not required, you can parse each color component separately:

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;
}

If depend of Color is not a problem, you can use:

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

On the other way, you can do too:

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

But since require to know the internal representation, this is not recommended.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=123038&siteId=1