Come convertire hex in rgb usando Java?


96

Come posso convertire il colore esadecimale in codice RGB in Java? Soprattutto in Google, gli esempi riguardano come convertire da RGB a esadecimale.


Puoi fare un esempio di cosa stai cercando di convertire e in cosa stai cercando di convertire? Non è chiaro esattamente cosa stai cercando di fare.
kkress

000000 convertirà in colore nero rgb
user236501

Risposte:


161

Immagino che questo dovrebbe farlo:

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

Per coloro che vogliono anche una versione a 3 caratteri, nota che nel caso di 3 caratteri ogni valore deve essere * 255 / 16. L'ho provato con "000", "aaa" e "fff" e ora funzionano tutti correttamente .
Andrew

283

In realtà, c'è un modo più semplice (integrato) per farlo:

Color.decode("#FFCCEE");

3
purtroppo quello è AWT: /
wuppi

6
@wuppi Ho pensato che fosse davvero una buona notizia, dato che AWT è in JDK. Cosa c'è di così sfortunato?
Dmitry Avtonomov

19
La soluzione accettata utilizza anche AWT. AWT non è un problema per il richiedente della domanda originale. Questa dovrebbe essere la soluzione accettata.
jewbix.cube

6
Su Android: Color.parseColor ()
Dawid Drozd

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

Per lo sviluppo Android , utilizzo:

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

Basta sostituire la "#" con "0x"
Julian Os

1
Color.parseColor non supporta i colori con tre cifre come questo: #fff
neoexpert

Puoi provare sotto di #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 (rosso, verde, blu);
GTID

9

Ecco una versione che gestisce sia le versioni RGB che 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;
}

Questo è stato utile per me poiché Integer.toHexString supporta il canale alfa, ma Integer.decode o Color.decode non sembra funzionare con esso.
Ted

4

Un codice colore esadecimale è #RRGGBB

RR, GG, BB sono valori esadecimali compresi tra 0 e 255

Chiamiamo RR XY dove X e Y sono caratteri esadecimali 0-9A-F, A = 10, F = 15

Il valore decimale è X * 16 + Y

Se RR = B7, il decimale per B è 11, quindi il valore è 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

puoi farlo semplicemente come di seguito:

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

Per esempio

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

2

Per JavaFX

import javafx.scene.paint.Color;

.

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

1

Convertirlo in un numero intero, quindi divmod due volte di 16, 256, 4096 o 65536 a seconda della lunghezza della stringa esadecimale originale (3, 6, 9 o 12 rispettivamente).


1

Molte di queste soluzioni funzionano, ma questa è un'alternativa.

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

Se non aggiungi 4278190080 (# FF000000) il colore ha un alfa 0 e non verrà visualizzato.


0

Per elaborare la risposta @xhh fornita, puoi aggiungere il rosso, il verde e il blu per formattare la stringa come "rgb (0,0,0)" prima di restituirla.

/**
* 
* @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 non desideri utilizzare AWT Color.decode, copia semplicemente il contenuto del metodo:

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

Integer.decode gestisce # o 0x, a seconda di come è formattata la stringa


0

Ecco un'altra versione più veloce che gestisce le versioni 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

La via più facile:

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


-1

L'altro giorno stavo risolvendo il problema simile e ho trovato conveniente convertire la stringa di colori esadecimali in array 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);

che mi dici di #eee?
Boni2k
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.