Returns RGBA from a HEX string (# should not be included) - Java 2D Graphics

Java examples for 2D Graphics:Color RGB

Description

Returns RGBA from a HEX string (# should not be included)

Demo Code


//package com.java2s;

public class Main {
    /**/*from ww w.j av a  2  s.  c o  m*/
     * Returns RGBA from a HEX string (# should not be included)
     * @param stringValue
     * @return
     * @throws Exception
     */
    public static String RGBAFromHEX(String stringValue) throws Exception {
        int r = 0, g = 0, b = 0;
        if (stringValue.length() == 3) {
            String sh = stringValue.substring(0, 1);
            r = Integer.parseInt(sh + sh, 16);
            sh = stringValue.substring(1, 2);
            g = Integer.parseInt(sh + sh, 16);
            sh = stringValue.substring(2, 3);
            b = Integer.parseInt(sh + sh, 16);
        } else if (stringValue.length() == 6) {
            r = Integer.parseInt(stringValue.substring(0, 2), 16);
            g = Integer.parseInt(stringValue.substring(2, 4), 16);
            b = Integer.parseInt(stringValue.substring(4, 6), 16);
        } else {
            throw new Exception("Invalid hex value");
        }
        return String.format("rgba(%s, %s, %s, %s)", r, g, b, 1F);
    }
}

Related Tutorials