Parses an html color. - Java 2D Graphics

Java examples for 2D Graphics:Color HTML

Description

Parses an html color.

Demo Code

/**//from   w  w  w .ja v a  2  s  .  c  o  m
 * This file is part of emf2gv : an eclipse plugin that allows to
 * generate a graphical representation of an EMF model.
 *
 * Copyright 2010-2011 Jean-Francois Brazeau
 * 
 * emf2gv is free software: you can redistribute it and/or modify
 * it under the terms of either:
 * 
 *      a) the GNU Lesser General Public License as published by
 *       the Free Software Foundation, either version 3 of the License, or
 *       (at your option) any later version.
 *  or
 *      b) the Eclipse Public License version 1.0 as published by
 *       the Eclipse Foundation.
 * 
 * emf2gv is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with emf2gv.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * You should have received a copy of the  Eclipse Public License
 * along with emf2gv.  If not, see <http://www.eclipse.org/legal/epl-v10.html>.
 */
//package com.java2s;
import java.awt.Color;

public class Main {
    public static void main(String[] argv) throws Exception {
        String htmlColor = "java2s.com";
        System.out.println(parseHtmlColor(htmlColor));
    }

    /**
     * Parses an html color.
     * 
     * @param htmlColor
     *            the html color to parse.
     * @return the color.
     */
    public static Color parseHtmlColor(String htmlColor) {
        Color result = null;
        if (htmlColor != null) {
            htmlColor = htmlColor.trim();
            if (htmlColor.startsWith("#")) {
                htmlColor = htmlColor.substring(1);
            }
            long color = Long.parseLong(htmlColor, 16);
            int r = (int) ((color >> 16) & 0xFF);
            int g = (int) ((color >> 8) & 0xFF);
            int b = (int) (color & 0xFF);
            result = new Color(r, g, b);
        }
        return result;
    }
}

Related Tutorials