Comment convertir hexadécimal en RVB en utilisant Java?


96

Comment puis-je convertir une couleur hexadécimale en code RVB en Java? Surtout dans Google, des exemples expliquent comment convertir RVB en hexadécimal.


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

000000 sera converti en couleur noire
— RVB

Réponses:


161

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

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

283

En fait, il existe un moyen plus simple (intégré) de le faire:

Color.decode("#FFCCEE");

3
malheureusement c'est AWT: /
— wuppi

6
@wuppi J'ai pensé que c'était en fait une bonne nouvelle, car AWT est dans JDK. Qu'y a-t-il de malheureux à ce sujet?
— Dmitry Avtonomov

19
La solution acceptée utilise également AWT. AWT n'est pas un problème pour le demandeur d'origine. Cela devrait être la solution acceptée.
— jewbix.cube

6
Sur 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

Pour développement Android , j'utilise:

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

Remplacez simplement le '#' par '0x'
— Julian Os

1
Color.parseColor ne prend pas en charge les couleurs à trois chiffres comme celle-ci: #fff
— neoexpert

Vous pouvez essayer ci-dessous #fff int red = colorString.charAt (1) == '0'? 0: 255; int blue = colorString.charAt (2) == '0'? 0: 255; int vert = colorString.charAt (3) == '0'? 0: 255; Color.rgb (rouge, vert, bleu);
— GTID

9

Voici une version qui gère à la fois les versions RVB et RVBA:

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

Cela m'a été utile car Integer.toHexString prend en charge le canal alpha, mais Integer.decode ou Color.decode ne semble pas fonctionner avec.
— Ted

4

Un code couleur hexadécimal est #RRGGBB

RR, GG, BB sont des valeurs hexadécimales comprises entre 0 et 255

Appelons RR XY où X et Y sont le caractère hexadécimal 0-9A-F, A = 10, F = 15

La valeur décimale est X * 16 + Y

Si RR = B7, la décimale pour 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;
}

4

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

2

Pour JavaFX

import javafx.scene.paint.Color;

.

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

1

Convertissez-le en entier, puis divmodez-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

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 n'ajoutez pas 4278190080 (# FF000000), la couleur a un alpha de 0 et ne s'affichera pas.


0

Pour élaborer sur la réponse @xhh fournie, vous pouvez ajouter le rouge, le vert et le bleu pour formater votre chaîne comme "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();
}

0

Si vous ne souhaitez pas utiliser le code AWT Color.decode, copiez simplement le contenu de la méthode:

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

Integer.decode gère le # ou 0x, selon la façon dont votre chaîne est formatée


0

Voici une autre version plus rapide qui gère les versions 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

Le moyen le plus simple:

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


-1

L'autre jour, j'avais résolu le problème similaire et trouvé pratique de convertir une chaîne de couleur hexadécimale en tableau 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);

et #eee?
— Boni2k
En utilisant notre site, vous reconnaissez avoir lu et compris notre politique liée aux cookies et notre politique de confidentialité.
Licensed under cc by-sa 3.0 with attribution required.