Decode an HTML color string like '#F567BA;' into a Color - Java 2D Graphics

Java examples for 2D Graphics:Color String

Description

Decode an HTML color string like '#F567BA;' into a Color

Demo Code

/*//from  w ww .j a  v a 2 s.c o  m
 * Copyright 2005 Joe Walker
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;
import java.awt.Color;

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

    /**
     * Decode an HTML color string like '#F567BA;' into a {@link Color}
     * 
     * @param colorString The string to decode
     * @return The decoded color
     * @throws IllegalArgumentException if the color sequence is not valid
     */
    public static Color decodeHtmlColorString(String colorString) {
        Color color;

        if (colorString.startsWith("#")) {
            colorString = colorString.substring(1);
        }
        if (colorString.endsWith(";")) {
            colorString = colorString
                    .substring(0, colorString.length() - 1);
        }

        int red, green, blue;
        switch (colorString.length()) {
        case 6:
            red = Integer.parseInt(colorString.substring(0, 2), 16);
            green = Integer.parseInt(colorString.substring(2, 4), 16);
            blue = Integer.parseInt(colorString.substring(4, 6), 16);
            color = new Color(red, green, blue);
            break;
        case 3:
            red = 17 * Integer.parseInt(colorString.substring(0, 1), 16);
            green = 17 * Integer.parseInt(colorString.substring(1, 2), 16);
            blue = 17 * Integer.parseInt(colorString.substring(2, 3), 16);
            color = new Color(red, green, blue);
            break;
        case 1:
            red = green = blue = 17 * Integer.parseInt(
                    colorString.substring(0, 1), 16);
            color = new Color(red, green, blue);
            break;
        default:
            throw new IllegalArgumentException("Invalid color: "
                    + colorString);
        }
        return color;
    }
}

Related Tutorials