Java Color to Hex toHexColor(final Color color)

Here you can find the source of toHexColor(final Color color)

Description

Converts java.awt.Color object to hex string.

License

Open Source License

Parameter

Parameter Description
color java.awt.Color object

Return

hex color representation (ex. "8822DDC0", where 88 - red, 22 - green, DD - blue, C0 - alpha).

Declaration

public static String toHexColor(final Color color) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.awt.Color;

public class Main {
    /**//from  ww  w.  j  a  v a  2  s .  c  o m
     * Converts java.awt.Color object to hex string.
     *
     * @param color java.awt.Color object
     * @return hex color representation (ex. "8822DDC0", where 88 - red, 22 - green, DD - blue, C0 - alpha).
     */
    public static String toHexColor(final Color color) {
        final String red = pad(Integer.toHexString(color.getRed()));
        final String green = pad(Integer.toHexString(color.getGreen()));
        final String blue = pad(Integer.toHexString(color.getBlue()));
        final String alpha = pad(Integer.toHexString(color.getAlpha()));
        return red + green + blue + alpha;
    }

    /**
     * Adds zero to the beginning if hexadecimal representation contains only one symbol.
     *
     * @param hex hexadecimal number
     * @return hexadecimal number represented with two symbols
     */
    private static String pad(final String hex) {
        return (hex.length() == 1) ? "0" + hex : hex;
    }
}

Related

  1. toHex(java.awt.Color color)
  2. toHex0x(Color col)
  3. toHexCode(String prefix, Color color)
  4. toHexColor(Color col)
  5. toHexColor(Color col)
  6. toHexColor(final Color color)
  7. toHexString(Color c)
  8. toHexString(Color col)
  9. toHexString(Color col)