如何使用Java将十六进制转换为rgb?

如何使用Java将十六进制转换为rgb?,java,colors,Java,Colors,如何在Java中将十六进制颜色转换为RGB代码?大多数情况下,谷歌的示例都是关于如何将RGB转换为十六进制的。将其转换为整数,然后根据原始十六进制字符串的长度(分别为3、6、9或12)将其除以16、256、4096或65536两次。十六进制颜色代码已经是RGB。格式是#RRGGBB我想应该这样做: /** * * @param colorStr e.g. "#FFFFFF" * @return */ public static Color hex2Rgb(String colorSt

如何在Java中将十六进制颜色转换为RGB代码?大多数情况下,谷歌的示例都是关于如何将RGB转换为十六进制的。

将其转换为整数,然后根据原始十六进制字符串的长度(分别为3、6、9或12)将其除以16、256、4096或65536两次。

十六进制颜色代码已经是RGB。格式是#RRGGBB

我想应该这样做:

/**
 * 
 * @param colorStr e.g. "#FFFFFF"
 * @return 
 */
public static Color hex2Rgb(String colorStr) {
    return new Color(
            Integer.valueOf( colorStr.substring( 1, 3 ), 16 ),
            Integer.valueOf( colorStr.substring( 3, 5 ), 16 ),
            Integer.valueOf( colorStr.substring( 5, 7 ), 16 ) );
}
十六进制颜色代码为#RRGGBB

RR、GG、BB是范围为0-255的十六进制值

让我们调用rrxy,其中X和Y是十六进制字符0-9A-F,A=10,F=15

十进制值为X*16+Y

如果RR=B7,则B的小数点为11,因此值为11*16+7=183

public int[] getRGB(String rgb){
    int[] ret = new int[3];
    for(int i=0; i<3; i++){
        ret[i] = hexToInt(rgb.charAt(i*2), rgb.charAt(i*2+1));
    }
    return ret;
}

public int hexToInt(char a, char b){
    int x = a < 65 ? a-48 : a-55;
    int y = b < 65 ? b-48 : b-55;
    return x*16+y;
}
public int[]getRGB(字符串rgb){
int[]ret=新的int[3];

对于(int i=0;i实际上,有一种更简单(内置)的方法:

Color.decode("#FFCCEE");

对于Android开发,我使用:

int color = Color.parseColor("#123456");

要详细说明@xhh提供的答案,可以在返回之前附加红色、绿色和蓝色以将字符串格式化为“rgb(0,0,0)”

/**
* 
* @param colorStr e.g. "#FFFFFF"
* @return String - formatted "rgb(0,0,0)"
*/
public static String hex2Rgb(String colorStr) {
    Color c = new Color(
        Integer.valueOf(hexString.substring(1, 3), 16), 
        Integer.valueOf(hexString.substring(3, 5), 16), 
        Integer.valueOf(hexString.substring(5, 7), 16));

    StringBuffer sb = new StringBuffer();
    sb.append("rgb(");
    sb.append(c.getRed());
    sb.append(",");
    sb.append(c.getGreen());
    sb.append(",");
    sb.append(c.getBlue());
    sb.append(")");
    return sb.toString();
}

您只需按以下步骤进行操作:

 public static int[] getRGB(final String rgb)
{
    final int[] ret = new int[3];
    for (int i = 0; i < 3; i++)
    {
        ret[i] = Integer.parseInt(rgb.substring(i * 2, i * 2 + 2), 16);
    }
    return ret;
}

这些解决方案中有很多是可行的,但这是一种替代方案

String hex="#00FF00"; // green
long thisCol=Long.decode(hex)+4278190080L;
int useColour=(int)thisCol;

如果不添加4278190080(#FF000000),则颜色的Alpha为0,不会显示。

前几天我解决了类似的问题,发现将十六进制颜色字符串转换为int数组非常方便[Alpha,r,g,b]:

 /**
 * Hex color string to int[] array converter
 *
 * @param hexARGB should be color hex string: #AARRGGBB or #RRGGBB
 * @return int[] array: [alpha, r, g, b]
 * @throws IllegalArgumentException
 */

public static int[] hexStringToARGB(String hexARGB) throws IllegalArgumentException {

    if (!hexARGB.startsWith("#") || !(hexARGB.length() == 7 || hexARGB.length() == 9)) {

        throw new IllegalArgumentException("Hex color string is incorrect!");
    }

    int[] intARGB = new int[4];

    if (hexARGB.length() == 9) {
        intARGB[0] = Integer.valueOf(hexARGB.substring(1, 3), 16); // alpha
        intARGB[1] = Integer.valueOf(hexARGB.substring(3, 5), 16); // red
        intARGB[2] = Integer.valueOf(hexARGB.substring(5, 7), 16); // green
        intARGB[3] = Integer.valueOf(hexARGB.substring(7), 16); // blue
    } else hexStringToARGB("#FF" + hexARGB.substring(1));

    return intARGB;
}

以下是一个同时处理RGB和RGBA版本的版本:

/**
 * Converts a hex string to a color. If it can't be converted null is returned.
 * @param hex (i.e. #CCCCCCFF or CCCCCC)
 * @return Color
 */
public static Color HexToColor(String hex) 
{
    hex = hex.replace("#", "");
    switch (hex.length()) {
        case 6:
            return new Color(
            Integer.valueOf(hex.substring(0, 2), 16),
            Integer.valueOf(hex.substring(2, 4), 16),
            Integer.valueOf(hex.substring(4, 6), 16));
        case 8:
            return new Color(
            Integer.valueOf(hex.substring(0, 2), 16),
            Integer.valueOf(hex.substring(2, 4), 16),
            Integer.valueOf(hex.substring(4, 6), 16),
            Integer.valueOf(hex.substring(6, 8), 16));
    }
    return null;
}
public static int hexToIntColor(String hex){
    int Alpha = Integer.valueOf(hex.substring(0, 2), 16);
    int Red = Integer.valueOf(hex.substring(2, 4), 16);
    int Green = Integer.valueOf(hex.substring(4, 6), 16);
    int Blue = Integer.valueOf(hex.substring(6, 8), 16);
    Alpha = (Alpha << 24) & 0xFF000000;
    Red = (Red << 16) & 0x00FF0000;
    Green = (Green << 8) & 0x0000FF00;
    Blue = Blue & 0x000000FF;
    return Alpha | Red | Green | Blue;
}

如果不想使用AWT Color.decode,则只需复制该方法的内容:

int i = Integer.decode("#FFFFFF");
int[] rgb = new int[]{(i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF};

Integer.decode处理#或0x,具体取决于字符串的格式

这里是另一个处理RGBA版本的更快的版本:

/**
 * Converts a hex string to a color. If it can't be converted null is returned.
 * @param hex (i.e. #CCCCCCFF or CCCCCC)
 * @return Color
 */
public static Color HexToColor(String hex) 
{
    hex = hex.replace("#", "");
    switch (hex.length()) {
        case 6:
            return new Color(
            Integer.valueOf(hex.substring(0, 2), 16),
            Integer.valueOf(hex.substring(2, 4), 16),
            Integer.valueOf(hex.substring(4, 6), 16));
        case 8:
            return new Color(
            Integer.valueOf(hex.substring(0, 2), 16),
            Integer.valueOf(hex.substring(2, 4), 16),
            Integer.valueOf(hex.substring(4, 6), 16),
            Integer.valueOf(hex.substring(6, 8), 16));
    }
    return null;
}
public static int hexToIntColor(String hex){
    int Alpha = Integer.valueOf(hex.substring(0, 2), 16);
    int Red = Integer.valueOf(hex.substring(2, 4), 16);
    int Green = Integer.valueOf(hex.substring(4, 6), 16);
    int Blue = Integer.valueOf(hex.substring(6, 8), 16);
    Alpha = (Alpha << 24) & 0xFF000000;
    Red = (Red << 16) & 0x00FF0000;
    Green = (Green << 8) & 0x0000FF00;
    Blue = Blue & 0x000000FF;
    return Alpha | Red | Green | Blue;
}
公共静态int-hexToIntColor(字符串十六进制){
int Alpha=整数.valueOf(十六进制子字符串(0,2),16);
int Red=整数.valueOf(十六进制子字符串(2,4),16);
int Green=整数.valueOf(十六进制子字符串(4,6,16));
int Blue=整数.valueOf(十六进制子字符串(6,8,16));

Alpha=(Alpha表示JavaFX

import javafx.scene.paint.Color;

最简单的方法:

// 0000FF
public static Color hex2Rgb(String colorStr) {
    return new Color(Integer.valueOf(colorStr, 16));
}

对于AndroidKotlin用户:

"#FFF".longARGB()?.let{ Color.parceColor(it) }
"#FFFF".longARGB()?.let{ Color.parceColor(it) }
公共静态颜色hex2Rgb(字符串colorStr){
试一试{
//创建颜色
返回新颜色(
//使用基数为16的Integer.parseInt()
//在2个字符的字符串元素上。例如:“FF 05 E5”
整数.parseInt(colorStr.substring(0,2,16),
整数.parseInt(colorStr.substring(2,4,16),
parseInt(colorStr.substring(4,6,16));
}捕捉(StringIndexOutOfBoundsException e){
//如果输入长度小于6的字符串
返回新颜色(0,0,0);
}
}
公共静态字符串rgbToHex(彩色){
//如果
//。获取不同的RGB值并进行转换。输出将仅为一个字符。
返回Integer.toHexString(color.getRed()).toUpperCase()+(color.getRed()<16?0:)+//添加字符串
Integer.toHexString(color.getGreen()).toUpperCase()+(color.getGreen()<16?0:)+
Integer.toHexString(color.getBlue()).toUpperCase()+(color.getBlue()<16?0:);
}

我认为这是可行的。

你能举个例子说明你想转换什么,转换成什么吗?还不清楚你到底想做什么。000000将转换成黑色RGB,而不是#RGB、#RRRGGGBBB或#RRRRGGGGBBB。不幸的是,这是AWT:/@wuppi我认为这是个好消息,就像AWT我一样它是JDK中的。有什么不好呢?公认的解决方案也使用AWT。AWT对原始提问者来说不是问题。这应该是公认的解决方案。在android上:Color.parseColor()对于那些想要3个字符版本的人,请注意,在3个字符的情况下,每个值都必须是*255/16。我用“000”、“aaa”测试了这一点,和“fff”,它们现在都可以正常工作。只需将“#”替换为“0x”颜色即可。parseColor不支持使用以下三位数字的颜色:#fff可以在下面尝试使用#fff int red=colorString.charAt(1)='0'?0:255;int blue=colorString.charAt(2)='0'?0:255;int green=colorString.charAt(3)='0'?0:255;Color.rgb(红色、绿色、蓝色);那么#eee呢?这对我很有用,因为Integer.toHexString支持alpha通道,但Integer.decode或Color.decode似乎无法使用它。
// 0000FF
public static Color hex2Rgb(String colorStr) {
    return new Color(Integer.valueOf(colorStr, 16));
}
"#FFF".longARGB()?.let{ Color.parceColor(it) }
"#FFFF".longARGB()?.let{ Color.parceColor(it) }
fun String?.longARGB(): String? {
    if (this == null || !startsWith("#")) return null
    
//    #RRGGBB or #AARRGGBB
    if (length == 7 || length == 9) return this

//    #RGB or #ARGB
    if (length in 4..5) {
        val rgb = "#${this[1]}${this[1]}${this[2]}${this[2]}${this[3]}${this[3]}"
        if (length == 5) {
            return "$rgb${this[4]}${this[4]}"
        }
        return rgb
    }

    return null
}