Returns the Color for the given HTML code. - Java 2D Graphics

Java examples for 2D Graphics:Color HTML

Description

Returns the Color for the given HTML code.

Demo Code

// License: GPL. For details, see LICENSE file.
//package com.java2s;
import java.awt.Color;

public class Main {
    /**/*ww  w. j  a v  a 2s.  c o  m*/
     * Returns the {@code Color} for the given HTML code.
     * @param html the color code
     * @return the color
     */
    public static Color html2color(String html) {
        if (html.length() > 0 && html.charAt(0) == '#')
            html = html.substring(1);
        if (html.length() == 3) {
            return html2color(new String(new char[] { html.charAt(0),
                    html.charAt(0), html.charAt(1), html.charAt(1),
                    html.charAt(2), html.charAt(2) }));
        }
        if (html.length() != 6 && html.length() != 8)
            return null;
        try {
            return new Color(Integer.parseInt(html.substring(0, 2), 16),
                    Integer.parseInt(html.substring(2, 4), 16),
                    Integer.parseInt(html.substring(4, 6), 16),
                    (html.length() == 8 ? Integer.parseInt(
                            html.substring(6, 8), 16) : 255));
        } catch (NumberFormatException e) {
            return null;
        }
    }
}

Related Tutorials