sparklyllama
sparklyllama

Reputation: 1326

Convert RGB to Hexadecimal

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!

Upvotes: 2

Views: 5290

Answers (2)

Mirza Adil
Mirza Adil

Reputation: 412

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);

Upvotes: 0

Tech Enthusiast
Tech Enthusiast

Reputation: 287

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;
}

Upvotes: 3

Related Questions