2010-11-09 5 views
63

Comment puis-je convertir la couleur hexadécimale en code RVB en Java? Surtout dans Google, des exemples sont sur la façon de convertir RGB en hexadécimal.Comment convertir hex en rgb en utilisant Java?

+0

Pouvez-vous donner un exemple de ce que vous essayez de convertir et à quoi vous essayez de convertir? Ce n'est pas clair exactement ce que vous essayez de faire. – kkress

+0

000000 va convertir en couleur noire rgb – user236501

Répondre

137

Je suppose que cela devrait le faire:

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

Pour ceux qui veulent une version à 3 caractères, notez que dans le cas de 3 caractères, chaque valeur doit être * 255/16. J'ai testé ceci avec "000", "aaa" et "fff", et ils fonctionnent tous correctement à présent. – Andrew

2

Convertissez-le en nombre entier, puis divisez-le deux fois par 16, 256, 4096 ou 65536 en fonction de la longueur de la chaîne hexadécimale d'origine (3, 6, 9 ou 12 respectivement).

1

Les codes de couleurs hexadécimaux sont déjà rgb. Le format est #RRGGBB

+3

Sauf s'il s'agit de #RGB, #RRRGGGBBB ou #RRRRGGGGBBBB. –

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

Un code couleur hexadécimal est #RRGGBB

RR, GG, BB sont des valeurs hexagonales allant 0-255

appel RR de XY Let où X et y sont des caractères hex 0-9A-F, A = 10, F = 15

La valeur décimale est X * 1 6 + Y

Si RR = B7, la décimale B est 11, donc la valeur est 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; 
} 
171

En fait, il y a un moyen plus facile (intégré) de faire ceci:

Color.decode("#FFCCEE"); 
+2

malheureusement c'est AWT:/ – wuppi

+2

@wuppi Je pensais que c'était en fait de bonnes nouvelles, comme AWT est en JDK. Qu'y a-t-il de si malheureux? –

+0

Eclipse RCP est SWT, avec lequel je travaillais. – wuppi

19

Pour développement Android, j'utilise:

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

Il suffit de remplacer le «#» par «0x» –

1

Expliciter e e réponse @xhh fournie, vous pouvez ajouter le rouge, le vert et le bleu pour formater votre chaîne en "rgb (0,0,0)" avant de la renvoyer.

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

vous pouvez le faire simplement comme ci-dessous:

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

Par exemple

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

Beaucoup de ces solutions fonctionnent, mais c'est une alternative.

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

Si vous ne pas ajouter 4278190080 (# FF000000) la couleur a une valeur alpha de 0 et ne sera pas affiché.

0

L'autre jour, j'avais résoudre le problème similaire et trouvé pratique pour convertir la chaîne de couleur hexadécimal int tableau [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; 
} 
3

Voici une version qui gère à la fois versions RGB et 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; 
} 
0

Si vous ne souhaitez pas utiliser l'AWT Color.decode, alors il suffit de copier le contenu de la méthode:

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

Entier.Le décodage gère le # ou le 0x, en fonction de la façon dont votre chaîne est formatée.