简体   繁体   English

将 RGB 转换为十六进制

[英]Convert RGB to Hexadecimal

If I have a Color object, how can I convert it's RGB values to a hexadecimal integer?如果我有一个Color对象,如何将它的 RGB 值转换为十六进制整数? 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.我已经搜索了很长时间,我发现的只是“十六进制到 RGB”,或者它不返回整数值,或者我不想要的其他东西。

I want it to return the hexadecimal as an int value, not a string, or anything else.我希望它以int值的形式返回十六进制,而不是字符串或其他任何内容。 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!谢谢!

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

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", 158, 255, 168);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM