Convert a RGB Color Value to a Hexadecimal String

Viewed 124193

In my Java application, I was able to get the Color of a JButton in terms of red, green and blue; I have stored these values in three ints.

How do I convert those RGB values into a String containing the equivalent hexadecimal representation? Such as #0033fA

6 Answers

Convert a java.awt.Color to a 24-bit hexadecimal RGB representation even if alpha channel value is zero (e.g. 0000ff):

String.format("%06x", 0xFFFFFF & Color.BLUE.getRGB())

For uppercase (e.g. 0000FF) :

String.format("%06X", 0xFFFFFF & Color.BLUE.getRGB())

slightly modified versions for RGBA from How to convert a color integer to a hex String in Android? and How to code and decode RGB to Hex

    public static String ColorToHex (Color color) {
    int red = color.getRed();
    int green = color.getGreen();
    int blue = color.getBlue();
    int alpha = color.getAlpha(); 

    String redHex = To00Hex(red);
    String greenHex = To00Hex(green);
    String blueHex = To00Hex(blue);
    String alphaHex = To00Hex(alpha);

    // hexBinary value: RRGGBBAA
    StringBuilder str = new StringBuilder("#");
    str.append(redHex);
    str.append(greenHex);
    str.append(blueHex);
    str.append(alphaHex);

    return str.toString();
}

private static String To00Hex(int value) {
    String hex = "00".concat(Integer.toHexString(value));
    hex=hex.toUpperCase();
    return hex.substring(hex.length()-2, hex.length());
} 

another way, this one could be related to the benchmark above:

public static String rgbToHex (Color color) {

   String hex = String.format("#%02x%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha() );
   hex=hex.toUpperCase();
       return hex;
}

a very simple benchmark shows that solution with String.format is 2+ times slower than StringBuilder for 10 million color conversions. For small amount of objects you cannot really see a difference.

I am not an expert so my opinion is subjective. I'm posting the benchmark code for any use, replace methods rgbToHex, rgbToHex2 with those you want to test:

   public static void benchmark /*ColorToHex*/ () {
       
 Color color = new Color(12,12,12,12);
   
     ArrayList<Color> colorlist = new ArrayList<Color>();
    // a list filled with a color i times
    for (int i = 0; i < 10000000; i++) {
      
        colorlist.add((color));
    }
   
   ArrayList<String> hexlist = new ArrayList<String>();
   System.out.println("START TIME... " + ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME) + "  TEST CASE 1...");
        for (int i = 0; i < colorlist.size(); i++) {
        hexlist.add(rgbToHex(colorlist.get(i)));
    }
        System.out.println("END TIME... " + ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME) + "  TEST CASE 1...");
        System.out.println("hexlist.get(0)... "+hexlist.get(0));
        
     ArrayList<String> hexlist2 = new ArrayList<String>();
   System.out.println("START TIME... " + ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME) + " TEST CASE 2...");
        for (int i = 0; i < colorlist.size(); i++) {
        hexlist2.add(rgbToHex1(colorlist.get(i)));
    }
     System.out.println("END TIME... " + ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME) + "  TEST CASE 2..."); 
     System.out.println("hexlist2.get(0)... "+hexlist2.get(0));

    }

it seems that there are issues with Integer.toHexString(color.getRGB()) try it with Color color = new Color(0,0,0,0); and you will find out that we have subtraction of zeros. #0 instead of #00000000 and we need all digits in order to have valid hex color values, 6 or 8 if with Alpha. So as far as I can see we need an improved use of Integer.toHexString to handle those cases. There should be other cases that cannot handle leading zeros at hex values. For example try with #0c0c0c0c that corresponds to Color color = new Color(12,12,12,12); The result will be #C0C0C0C witch is wrong.

Related