Convert a RGB Color Value to a Hexadecimal

In my Java application, I was able to get the value of JButton color in terms of Red, Green, Blue values; I have stored these values in three integers.

How to convert RGB values into the equivalent hexadecimal value?

Example of that like in this format #0033fA


You can use

String hex = String.format("#%02x%02x%02x", r, g, b);  

Use capital X's if you want your resulting hex-digits to be capitalized ( #FFFFFF vs. #ffffff ).


A one liner but without String.format:

Color your_color = Color.BLACK;

String hex = "#"+Integer.toHexString(your_color.getRGB()).substring(2);

You can add a .toUpperCase() if you want to switch to capital letters.


Random ra = new Random();
int r, g, b;
r=ra.nextInt(255);
g=ra.nextInt(255);
b=ra.nextInt(255);
Color color = new Color(r,g,b);
String hex = Integer.toHexString(color.getRGB() & 0xffffff);
if (hex.length() < 6) {
    hex = "0" + hex;
}
hex = "#" + hex;
链接地址: http://www.djcxy.com/p/87796.html

上一篇: 十进制颜色为RGB颜色

下一篇: 将RGB颜色值转换为十六进制