Java Color Decode decodeHtmlColorString(String colourString)

Here you can find the source of decodeHtmlColorString(String colourString)

Description

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

License

Open Source License

Parameter

Parameter Description
colourString The string to decode

Exception

Parameter Description
IllegalArgumentException if the color sequence is not valid

Return

The decoded color

Declaration

public static Color decodeHtmlColorString(String colourString) 

Method Source Code

//package com.java2s;
/**/*from www .  j  av a2s.c  om*/
 * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com
 *
 * The software in this package is published under the terms of the CPAL v1.0
 * license, a copy of which has been included with this distribution in the
 * LICENSE.md file.
 */

import java.awt.*;

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

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

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

Related

  1. decodeColor(int value)
  2. decodeColor(String color, Color defaultColor)
  3. decodeColor(String string)
  4. decodeColor(String value, Color dflt)
  5. decodeHexColor(String hexString)
  6. decodeRGB(String color)