How to convert hex to rgb using Java?
Asked Answered
D

21

122

How can I convert hex color to RGB code in Java? Mostly in Google, samples are on how to convert from RGB to hex.

Denaturalize answered 9/11, 2010 at 1:20 Comment(2)
Can you give an example of what you're trying to convert from and what you're trying to convert to? Its not clear exactly what you're trying to do.Progressionist
000000 will convert to black color rgbDenaturalize
C
178

I guess this should do it:

/**
 * 
 * @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 ) );
}
Cryptocrystalline answered 9/11, 2010 at 1:27 Comment(1)
For those who want a 3 character version as well, note that in the 3 character case each value must be * 255 / 16. I tested this with "000", "aaa", and "fff", and they all work properly now.Grapeshot
A
362

Actually, there's an easier (built in) way of doing this:

Color.decode("#FFCCEE");
Arbalest answered 19/9, 2011 at 12:48 Comment(4)
unfortunately that is AWT :/Freberg
@Freberg I thought that was actually good news, as AWT is in JDK. What's so unfortunate about it?Ranger
The accepted solution also uses AWT. AWT is not a problem for the original question asker. This should be the accepted solution.Titanium
On android: Color.parseColor()Embitter
C
178

I guess this should do it:

/**
 * 
 * @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 ) );
}
Cryptocrystalline answered 9/11, 2010 at 1:27 Comment(1)
For those who want a 3 character version as well, note that in the 3 character case each value must be * 255 / 16. I tested this with "000", "aaa", and "fff", and they all work properly now.Grapeshot
D
43
public static void main(String[] args) {
    int hex = 0x123456;
    int r = (hex & 0xFF0000) >> 16;
    int g = (hex & 0xFF00) >> 8;
    int b = (hex & 0xFF);
}
Diplo answered 9/11, 2010 at 1:41 Comment(0)
Q
29

For Android development, I use:

int color = Color.parseColor("#123456");
Quetzalcoatl answered 12/4, 2013 at 12:21 Comment(3)
Just replace the '#' with '0x'Transfigure
Color.parseColor does not support Colors with three digits like this one: #fffGatling
U can try below of #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(red, green,blue);Cowbane
L
13

Here is a version that handles both RGB and RGBA versions:

/**
 * 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;
}
Lardner answered 3/5, 2017 at 15:30 Comment(1)
This was useful for me since the Integer.toHexString supports the alpha channel, but the Integer.decode or Color.decode does not seem to work with it.Swizzle
R
5

you can do it simply as below:

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

For Example

getRGB("444444") = 68,68,68   
getRGB("FFFFFF") = 255,255,255
Rodrigorodrigue answered 15/4, 2014 at 12:17 Comment(1)
Beautiful! Xackly what I needed! Danke!Hedgehog
I
4

A hex color code is #RRGGBB

RR, GG, BB are hex values ranging from 0-255

Let's call RR XY where X and Y are hex character 0-9A-F, A=10, F=15

The decimal value is X*16+Y

If RR = B7, the decimal for B is 11, so value is 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;
}
Involuted answered 9/11, 2010 at 1:50 Comment(0)
P
4

For JavaFX

import javafx.scene.paint.Color;

.

Color whiteColor = Color.valueOf("#ffffff");
Pym answered 11/8, 2018 at 12:2 Comment(0)
C
1

Convert it to an integer, then divmod it twice by 16, 256, 4096, or 65536 depending on the length of the original hex string (3, 6, 9, or 12 respectively).

Crackpot answered 9/11, 2010 at 1:25 Comment(0)
S
1

Lots of these solutions work, but this is an alternative.

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

If you don't add 4278190080 (#FF000000) the colour has an Alpha of 0 and won't show.

Salvador answered 11/3, 2015 at 23:16 Comment(0)
L
1

For Android Kotlin developers:

"#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
}
Lenity answered 23/10, 2020 at 5:25 Comment(0)
M
1

Hex is base 16, so you can parse the string with parseLong using a radix of 16 :

Color newColor = new Color((int) Long.parseLong("FF7F0055", 16));
Methylal answered 22/2, 2022 at 15:35 Comment(0)
S
0

To elaborate on the answer @xhh provided, you can append the red, green, and blue to format your string as "rgb(0,0,0)" before returning it.

/**
* 
* @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();
}
Seltzer answered 21/8, 2013 at 19:39 Comment(0)
I
0

If you don't want to use the AWT Color.decode, then just copy the contents of the method:

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

Integer.decode handles the # or 0x, depending on how your string is formatted

Ill answered 10/1, 2018 at 13:33 Comment(0)
T
0

The easiest way:

// 0000FF
public static Color hex2Rgb(String colorStr) {
    return new Color(Integer.valueOf(colorStr, 16));
}
Tracietracing answered 18/6, 2020 at 10:39 Comment(1)
Rather call Integer.parseInt(String, int) instead of Integer.valueOf(String, int) in order to avoid useless conversions from int to Integer and from Integer to int, Integer.valueOf(String, int) returns an Integer and the constructor accepts an int whereas Integer.parseInt(String, int) returns an int. Moreover, java.awt.Color.decode(String) is more straightforward than your solution.Withal
A
0
public static Color hex2Rgb(String colorStr) {
    try {
        // Create the color
        return new Color(
                // Using Integer.parseInt() with a radix of 16
                // on string elements of 2 characters. Example: "FF 05 E5"
                Integer.parseInt(colorStr.substring(0, 2), 16),
                Integer.parseInt(colorStr.substring(2, 4), 16),
                Integer.parseInt(colorStr.substring(4, 6), 16));
    } catch (StringIndexOutOfBoundsException e){
        // If a string with a length smaller than 6 is inputted
        return new Color(0,0,0);
    }
}

public static String rgbToHex(Color color) {
    //      Integer.toHexString(), built in Java method        Use this to add a second 0 if the
    //     .Get the different RGB values and convert them.     output will only be one character.
    return Integer.toHexString(color.getRed()).toUpperCase() + (color.getRed() < 16 ? 0 : "") + // Add String
            Integer.toHexString(color.getGreen()).toUpperCase() + (color.getGreen() < 16 ? 0 : "") +
            Integer.toHexString(color.getBlue()).toUpperCase() + (color.getBlue() < 16 ? 0 : "");
}

I think that this wil work.

Adalbert answered 13/11, 2020 at 8:30 Comment(0)
Z
0

If you need to decode a HEXA string in following format #RRGGBBAA, you can use the following:

private static Color convert(String hexa) {
  var value = Long.decode(hexa);
  return new Color(
    (int) (value >> 24) & 0xFF,
    (int) (value >> 16) & 0xFF,
    (int) (value >> 8) & 0xFF,
    (int) (value & 0xFF)
  );
}

Furthermore, if you want to ensure correct format, you can use this method to get a uniform result:

private static String format(String raw) {
  var builder = new StringBuilder(raw);
  if (builder.charAt(0) != '#') {
    builder.insert(0, '#');
  }
  if (builder.length() == 9) {
    return builder.toString();
  } else if (builder.length() == 7) {
    return builder.append("ff").toString();
  } else if (builder.length() == 4) {
    builder.insert(builder.length(), 'f');
  } else if (builder.length() != 5) {
    throw new IllegalStateException("unsupported format");
  }
  for (int index = 1; index <= 7; index += 2) {
    builder.insert(index, builder.charAt(index));
  }
  return builder.toString();
}

This method will turn every accepted format (#RGB, #RGBA, #RRGGBB, RGB, RGBA, RRGGBB) into #RRGGBBAA

Zigrang answered 23/8, 2022 at 17:21 Comment(0)
G
-1

The other day I'd been solving the similar issue and found convenient to convert hex color string to int array [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;
}
Grapeshot answered 24/3, 2015 at 23:3 Comment(0)
N
-1

Here is another faster version that handles RGBA versions:

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;
}
Nakasuji answered 27/3, 2018 at 10:44 Comment(1)
All that string manipulation doesn't look like it would be faster to me.Myall
C
-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);
Cowbane answered 24/1, 2019 at 3:54 Comment(1)
what about #eee?Voluntarism
S
-3

Hexidecimal color codes are already rgb. The format is #RRGGBB

Sculpsit answered 9/11, 2010 at 1:25 Comment(1)
Unless it's #RGB, #RRRGGGBBB, or #RRRRGGGGBBBB.Crackpot

© 2022 - 2024 — McMap. All rights reserved.