2

If I have a Color object, how can I convert it's RGB values to a hexadecimal integer? I've been searching for ages, and all I've found are "Hexadecimal to RGB", or it doesn't return an Integer value, or something else that I don't want.

I want it to return the hexadecimal as an int value, not a string, or anything else. Can anyone help?

Here is my code where I need to convert a colour to hex, using someone's answer to try to convert it:

public static void loadImageGraphics(BufferedImage image, int x, int y, int width, int height) {
    for(int yy = 0; yy < height; yy++) {
        for(int xx = 0; xx < width; xx++) {
            Color c = new Color(image.getRGB(xx, yy));
            pixels[x + y * width] = c.getRed() * (0xFF)^2 + c.getGreen() * 0xFF + c.getBlue();
        }
    }
}

Thanks!

sparklyllama
  • 1,276
  • 4
  • 20
  • 28
  • 1
    An integer is just a value. It only becomes a hexadecimal representation when you convert it to a string. – Henry Jan 20 '14 at 07:05
  • Other solutions here http://stackoverflow.com/questions/3607858/how-to-convert-a-rgb-color-value-to-an-hexadecimal-value-in-java – gowtham Jan 20 '14 at 07:25
  • String hexColor = String.format("#%02x%02x%02x", 158, 255, 168); – Mirza Adil Mar 04 '20 at 12:10

2 Answers2

3

This utility function is working fine for me:

public static String convertColorToHexadeimal(Color color)
{
        String hex = Integer.toHexString(color.getRGB() & 0xffffff);
        if(hex.length() < 6) 
        {
            if(hex.length()==5)
                hex = "0" + hex;
            if(hex.length()==4)
                hex = "00" + hex;
            if(hex.length()==3)
                hex = "000" + hex;
        }
        hex = "#" + hex;
        return hex;
}
Tech Enthusiast
  • 279
  • 1
  • 5
  • 18
  • This returns a string. I tried to add a `Integer.parseInt()`, but I get a `NumberFormatException`. – sparklyllama Jan 20 '14 at 07:04
  • @sparklyllama: You can *write* an integer in base-16, just like `0xffffff` is `16777215`. – Blender Jan 20 '14 at 07:11
  • Color c = Color.RED; String hex = convertColorToHexadeimal(c); System.out.println("hex:"+hex); String hexRed = hex.substring(0, 2); String hexGreen = hex.substring(2, 4); String hexBlue = hex.substring(4, 6); System.out.println(convert(hexRed)); System.out.println(convert(hexGreen)); System.out.println(convert(hexBlue)); public static int convert(String n) { return Integer.valueOf(n, 16); } – Tech Enthusiast Jan 20 '14 at 07:17
  • Actually, I'm getting a `NumberFormatException` in the `convert` method. – sparklyllama Jan 20 '14 at 07:25
  • You can use smart line of code -> String hexColor = String.format("#%02x%02x%02x", 158, 255, 168); – Mirza Adil Mar 04 '20 at 12:10
0

You can use this smart line of code.

String hexColor = String.format("#%02x%02x%02x", 158, 255, 168);

String hexColor = String.format("#%02x%02x%02x", R, G, B);

Mirza Adil
  • 352
  • 5
  • 9