Java Color Decode decodeHexColor(String hexString)

Here you can find the source of decodeHexColor(String hexString)

Description

decode Hex Color

License

Apache License

Declaration

private static Color decodeHexColor(String hexString) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.awt.Color;

public class Main {
    private static Color decodeHexColor(String hexString) {
        if (hexString.length() == 6 || hexString.length() == 8) {
            // RGB color
            int r = parseHexColorComponent(hexString, 0);
            int g = parseHexColorComponent(hexString, 2);
            int b = parseHexColorComponent(hexString, 4);
            if (hexString.length() == 8) {
                // RGBA color
                int a = parseHexColorComponent(hexString, 6);
                return new Color(r, g, b, a);
            }/*from  w ww  . jav a 2  s. com*/
            return new Color(r, g, b);
        } else {
            throw new IllegalArgumentException("Color is not a valid hex string: #" + hexString);
        }
    }

    private static int parseHexColorComponent(String hexString, int offset) {
        try {
            return Integer.parseInt(hexString.substring(offset, offset + 2), 16);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Color is not a valid hex string: #" + hexString);
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new IllegalArgumentException("Color is not a valid hex string: #" + hexString, e);
        }
    }
}

Related

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