Returns the HTML color code (6 or 8 digit). - Java 2D Graphics

Java examples for 2D Graphics:Color HTML

Description

Returns the HTML color code (6 or 8 digit).

Demo Code

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

public class Main {
    /**/*from www  . j  a va2  s .  co m*/
     * Returns the HTML color code (6 or 8 digit).
     * @param col The color to convert
     * @return the HTML color code (6 or 8 digit)
     */
    public static String color2html(Color col) {
        return color2html(col, true);
    }

    /**
     * Returns the HTML color code (6 or 8 digit).
     * @param col The color to convert
     * @param withAlpha if {@code true} and alpha value < 255, return 8-digit color code, else always 6-digit
     * @return the HTML color code (6 or 8 digit)
     * @since 6655
     */
    public static String color2html(Color col, boolean withAlpha) {
        if (col == null)
            return null;
        String code = "#" + int2hex(col.getRed()) + int2hex(col.getGreen())
                + int2hex(col.getBlue());
        if (withAlpha) {
            int alpha = col.getAlpha();
            if (alpha < 255) {
                code += int2hex(alpha);
            }
        }
        return code;
    }

    private static String int2hex(int i) {
        String s = Integer.toHexString(i / 16)
                + Integer.toHexString(i % 16);
        return s.toUpperCase();
    }
}

Related Tutorials