Returns a CSS friendly color in #RRGGBB format, where RR, GG, and BB are the red, green, and blue values of the color in hex. - Java 2D Graphics

Java examples for 2D Graphics:Color RGB

Description

Returns a CSS friendly color in #RRGGBB format, where RR, GG, and BB are the red, green, and blue values of the color in hex.

Demo Code


//package com.java2s;
import java.awt.Color;

public class Main {
    /**/* w ww .ja va 2  s .c o  m*/
     * Returns a CSS friendly color in #RRGGBB format, where RR, GG, and BB are
     * the red, green, and blue values of the color in hex. A leading hash sign
     * is always the first character.
     * 
     * @param color
     * @return
     */
    public static String toRgbHex(final Color color) {
        final StringBuffer hexString = new StringBuffer();
        hexString.append("#");
        hexString.append(Integer.toHexString(color.getRed()));
        if (hexString.length() < 3) {
            hexString.append("0");
        }
        hexString.append(Integer.toHexString(color.getGreen()));
        if (hexString.length() < 5) {
            hexString.append("0");
        }
        hexString.append(Integer.toHexString(color.getBlue()));
        if (hexString.length() < 7) {
            hexString.append("0");
        }

        return hexString.toString();
    }
}

Related Tutorials