Como converter hex para rgb usando Java?


96

Como posso converter cores hexadecimais em código RGB em Java? Principalmente no Google, os exemplos são sobre como converter de RGB para hexadecimal.


Você pode dar um exemplo do que você está tentando converter e para o que está tentando se converter? Não está claro exatamente o que você está tentando fazer.
kkress

000000 será convertido para a cor preta rgb
user236501

Respostas:


161

Eu acho que isso deve bastar:

/**
 * 
 * @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 ) );
}

Para aqueles que querem uma versão de 3 caracteres também, observe que no caso de 3 caracteres cada valor deve ser * 255 / 16. Eu testei isso com "000", "aaa" e "fff", e todos eles funcionam corretamente agora .
Andrew

283

Na verdade, existe uma maneira mais fácil (integrada) de fazer isso:

Color.decode("#FFCCEE");

3
infelizmente é AWT: /
wuppi

6
@wuppi Achei que eram boas notícias, já que AWT está em JDK. O que há de tão infeliz nisso?
Dmitry Avtonomov

19
A solução aceita também usa AWT. AWT não é um problema para o autor da pergunta original. Esta deve ser a solução aceita.
jewbix.cube

6
No Android: Color.parseColor ()
Dawid Drozd de

37
public static void main(String[] args) {
    int hex = 0x123456;
    int r = (hex & 0xFF0000) >> 16;
    int g = (hex & 0xFF00) >> 8;
    int b = (hex & 0xFF);
}

26

Para desenvolvimento Android , eu uso:

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

Basta substituir o '#' por '0x'
Julian Os

1
Color.parseColor não oferece suporte a cores com três dígitos como este: #fff
neoexpert

Você pode tentar abaixo de #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 (vermelho, verde, azul);
GTID

9

Aqui está uma versão que lida com as versões RGB e 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;
}

Isso foi útil para mim, pois Integer.toHexString oferece suporte ao canal alfa, mas Integer.decode ou Color.decode não parece funcionar com ele.
Ted de

4

Um código de cor hexadecimal é #RRGGBB

RR, GG, BB são valores hexadecimais variando de 0-255

Vamos chamar RR XY onde X e Y são caracteres hexadecimais 0-9A-F, A = 10, F = 15

O valor decimal é X * 16 + Y

Se RR = B7, o decimal para B é 11, então o valor é 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;
}

4

você pode fazer isso simplesmente como abaixo:

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

Por exemplo

getRGB("444444") = 68,68,68   
getRGB("FFFFFF") = 255,255,255

2

Para JavaFX

import javafx.scene.paint.Color;

.

Color whiteColor = Color.valueOf("#ffffff");

1

Converta-o para um número inteiro e divmod-o duas vezes por 16, 256, 4096 ou 65536, dependendo do comprimento da string hexadecimal original (3, 6, 9 ou 12, respectivamente).


1

Muitas dessas soluções funcionam, mas esta é uma alternativa.

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

Se você não adicionar 4278190080 (# FF000000), a cor terá um Alpha de 0 e não será exibida.


0

Para elaborar a resposta @xhh fornecida, você pode adicionar vermelho, verde e azul para formatar sua string como "rgb (0,0,0)" antes de retorná-la.

/**
* 
* @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();
}

0

Se você não quiser usar o AWT Color.decode, basta copiar o conteúdo do método:

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

Integer.decode lida com # ou 0x, dependendo de como sua string está formatada


0

Aqui está outra versão mais rápida que lida com versões RGBA:

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

0

A maneira mais fácil:

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


-1

Outro dia, eu estava resolvendo um problema semelhante e achei conveniente converter string de cores hexadecimais em matriz 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;
}

-1
For shortened hex code like #fff or #000

int red = "colorString".charAt(1) == '0' ? 0 : 
     "colorString".charAt(1) == 'f' ? 255 : 228;  
int green =
     "colorString".charAt(2) == '0' ? 0 :  "colorString".charAt(2) == 'f' ?
     255 : 228;  
int blue = "colorString".charAt(3) == '0' ? 0 : 
     "colorString".charAt(3) == 'f' ? 255 : 228;

Color.rgb(red, green,blue);

e #eee?
Boni2k
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.