Andreas Tolfsen

Converting RGB to HEX in Java

Java's java.awt.Color is a very handy utility class for dealing with colours. It basically allows you to have an object representation for any colour in the sRGB colour model.

I was recently working on a bug in OperaDriver that the WebElement.getCssValue("background-color") method call returned an RGB value instead of a HEX value in Opera. According to the WebDriver specification, getCssValue():

Get the value of a given CSS property. This is probably not going to return what you expect it to unless you've already had a look at the element using something like firebug. Seriously, even then you'll be lucky for this to work cross-browser. Colour values should be returned as hex strings, so, for example if the "background-color" property is set as "green" in the HTML source, the returned value will be "#008000"
(My outlining)

… which frankly to me seems like a very silly thing to do. Although most can, many colours cannot be represented within a #AABBCC HEX range. Think about RGBa from CSS 3 that introduced alpha transparency support. Now, Opera returns RGB or RGBa as standard which to me seems like a much better approach compared to the lossy format HEX.

Anyways, rant aside. I had to convert our perfectly good values from RGB to HEX. This turned out to be a bit tricky using the java.awt.Color interface. It does support converting from HEX to RGB using the Color.decode() method, but not the other way around.

I spent a good hour on implementing a method for converting from RGB to HEX, and I hope you find it useful:


import java.awt.Color;

public class OperaColor extends Color {

  public OperaColor(int r, int g, int b) {

   * Returns the HEX value representing the colour in the default sRGB ColorModel.
   * @return the HEX value of the colour in the default sRGB ColorModel
  public String getHex() {
    return toHex(getRed(), getGreen(), getBlue());

   * Returns a web browser-friendly HEX value representing the colour in the default sRGB
   * ColorModel.
   * @param r red
   * @param g green
   * @param b blue
   * @return a browser-friendly HEX value
  public static String toHex(int r, int g, int b) {
    return "#" + toBrowserHexValue(r) + toBrowserHexValue(g) + toBrowserHexValue(b);

  private static String toBrowserHexValue(int number) {
    StringBuilder builder = new StringBuilder(Integer.toHexString(number & 0xff));
    while (builder.length() < 2) {
    return builder.toString().toUpperCase();


The toHex(r,g,b) method is static is callable from anywhere. This is utilized by getHex() if calling it on an instantiated object. To use the static method:


… will yield "#64FF60".

To use the object-oriented way:

OperaColor color = new OperaColor(100,255,96);

This is used in OperaColor inside of OperaDriver.