Returns a java.awt.Color by reading the RGB values from a hexadecimal string of format #RRGGBB - Java 2D Graphics

Java examples for 2D Graphics:Color RGB

Description

Returns a java.awt.Color by reading the RGB values from a hexadecimal string of format #RRGGBB

Demo Code


//package com.java2s;
import java.awt.Color;

public class Main {
    public static void main(String[] argv) throws Exception {
        String rgbHexString = "java2s.com";
        System.out.println(parseColorFromRgbHexString(rgbHexString));
    }//from  w  ww  .  j  ava2s  .  com

    /**
     * Returns a java.awt.Color by reading the RGB values from a hexadecimal
     * string of format #RRGGBB (the same format used by toRgbHex). An
     * IllegalArgumentException is thrown if the string format is not valid.
     * 
     * @param rgbHexString
     * @return
     */
    public static Color parseColorFromRgbHexString(final String rgbHexString) {
        String t = rgbHexString;
        Color ret = null;
        if (t.charAt(0) != '#') {
            throw new IllegalArgumentException(
                    "color RGB value must begin with hash (#) mark");
        }
        if (t.length() == 4) {
            // convert three hex value to six hex value
            t = new String(new char[] { t.charAt(0), t.charAt(1),
                    t.charAt(1), t.charAt(2), t.charAt(2), t.charAt(3),
                    t.charAt(3) });
        }
        if (t.length() != 7) {
            throw new IllegalArgumentException("format expected to be "
                    + "in the format #RGB or #RRGGBB; " + "format was "
                    + rgbHexString);
        }
        // parse as six hex value
        int rValue, gValue, bValue = 0;
        try {
            rValue = Integer.parseInt(t.substring(1, 3), 16);
            gValue = Integer.parseInt(t.substring(3, 5), 16);
            bValue = Integer.parseInt(t.substring(5, 7), 16);
            ret = new Color(rValue, gValue, bValue);
        } catch (final Exception e) {
            throw new IllegalArgumentException("bad RGB hex format");
        }
        return ret;
    }
}

Related Tutorials