Java hex color codes

How to convert hex to rgb using Java?

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

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.

21 Answers 21

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

The accepted solution also uses AWT. AWT is not a problem for the original question asker. This should be the accepted solution.

I guess this should do it:

/** * * @param colorStr e.g. "#FFFFFF" * @return */ public static Color hex2Rgb(String colorStr)

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.

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

For Android development, I use:

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

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

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

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.

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; > 
getRGB("444444") = 68,68,68 getRGB("FFFFFF") = 255,255,255 

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; ireturn ret; > public int hexToInt(char a, char b)

For JavaFX

import javafx.scene.paint.Color; 
Color whiteColor = Color.valueOf("#ffffff"); 

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).

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.

For Android Kotlin developers:

"#FFF".longARGB()?.let < Color.parceColor(it) >"#FFFF".longARGB()?.let
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 = "#$$$$$$" if (length == 5) < return "$rgb$$" > return rgb > return null > 

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)

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

// 0000FF public static Color hex2Rgb(String colorStr)
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()

I think that this wil work.

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

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 return builder.toString(); > 

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

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

Источник

Example of converting colors from Java to hexadecimal RGB code

To resolve the issue, one can use an example that returns the name of the color using Reflection to access the name of java.awt.Color. It should be noted that the defined colors include Java rgb to color, kotlin convert color hex to rgba, and java hex to rgb. Instead of manually defining the color constants, one can use reflection on all the constants defined there. However, it is worth noting that there may be issues with names that use underscores, as they have been removed in JavaFX.

Convert colour names to RGB values in Java

In the javax.swing.text.html.CSS class, this is what I discovered:

/** * Convert a color string such as "RED" or "#NNNNNN" or "rgb(r, g, b)" * to a Color. */ static Color stringToColor(String str) < Color color; if (str == null) < return null; >if (str.length() == 0) color = Color.black; else if (str.startsWith("rgb(")) < color = parseRGB(str); >else if (str.charAt(0) == '#') color = hexToColor(str); else if (str.equalsIgnoreCase("Black")) color = hexToColor("#000000"); else if(str.equalsIgnoreCase("Silver")) color = hexToColor("#C0C0C0"); else if(str.equalsIgnoreCase("Gray")) color = hexToColor("#808080"); else if(str.equalsIgnoreCase("White")) color = hexToColor("#FFFFFF"); else if(str.equalsIgnoreCase("Maroon")) color = hexToColor("#800000"); else if(str.equalsIgnoreCase("Red")) color = hexToColor("#FF0000"); else if(str.equalsIgnoreCase("Purple")) color = hexToColor("#800080"); else if(str.equalsIgnoreCase("Fuchsia")) color = hexToColor("#FF00FF"); else if(str.equalsIgnoreCase("Green")) color = hexToColor("#008000"); else if(str.equalsIgnoreCase("Lime")) color = hexToColor("#00FF00"); else if(str.equalsIgnoreCase("Olive")) color = hexToColor("#808000"); else if(str.equalsIgnoreCase("Yellow")) color = hexToColor("#FFFF00"); else if(str.equalsIgnoreCase("Navy")) color = hexToColor("#000080"); else if(str.equalsIgnoreCase("Blue")) color = hexToColor("#0000FF"); else if(str.equalsIgnoreCase("Teal")) color = hexToColor("#008080"); else if(str.equalsIgnoreCase("Aqua")) color = hexToColor("#00FFFF"); else if(str.equalsIgnoreCase("Orange")) color = hexToColor("#FF8000"); else color = hexToColor(str); // sometimes get specified without leading # return color; > 

In case you encounter a color that is not listed in the aforementioned code, you will regrettably receive the code NullPointerException .

I've discovered a workaround for your issue. Utilize this code:

public static void main(String[] args) < StyleSheet s = new StyleSheet(); String colourName = "Cyan"; Color clr = stringToColorCustom(colourName); int r = clr.getRed(); int g = clr.getGreen(); int b = clr.getBlue(); System.out.println("red:" + r + " green :" + g + " blue:" + b); >static Color stringToColorCustom(String str) < Color color; if (str == null) < return null; >if (str.length() == 0) color = Color.black; else if (str.charAt(0) == '#') color = hexToColor(str); else if (str.equalsIgnoreCase("Black")) color = hexToColor("#000000"); else if (str.equalsIgnoreCase("Silver")) color = hexToColor("#C0C0C0"); else if (str.equalsIgnoreCase("Gray")) color = hexToColor("#808080"); else if (str.equalsIgnoreCase("White")) color = hexToColor("#FFFFFF"); else if (str.equalsIgnoreCase("Maroon")) color = hexToColor("#800000"); else if (str.equalsIgnoreCase("Red")) color = hexToColor("#FF0000"); else if (str.equalsIgnoreCase("Purple")) color = hexToColor("#800080"); else if (str.equalsIgnoreCase("Fuchsia")) color = hexToColor("#FF00FF"); else if (str.equalsIgnoreCase("Green")) color = hexToColor("#008000"); else if (str.equalsIgnoreCase("Lime")) color = hexToColor("#00FF00"); else if (str.equalsIgnoreCase("Olive")) color = hexToColor("#808000"); else if (str.equalsIgnoreCase("Yellow")) color = hexToColor("#FFFF00"); else if (str.equalsIgnoreCase("Navy")) color = hexToColor("#000080"); else if (str.equalsIgnoreCase("Blue")) color = hexToColor("#0000FF"); else if (str.equalsIgnoreCase("Teal")) color = hexToColor("#008080"); else if (str.equalsIgnoreCase("Aqua")) color = hexToColor("#00FFFF"); else if (str.equalsIgnoreCase("Orange")) color = hexToColor("#FF8000"); else if (str.equalsIgnoreCase("Cyan")) // Add your color color = hexToColor("#00FFFF"); // Add the RGB else color = hexToColor(str); // Sometimes get specified // without a leading # return color; > static final Color hexToColor(String value) < String digits; int n = value.length(); if (value.startsWith("#")) < digits = value.substring(1, Math.min(value.length(), 7)); >else < digits = value; >String hstr = "0x" + digits; Color c; try < c = Color.decode(hstr); >catch (NumberFormatException nfe) < c = null; >return c; > 

I have written a personalized code, stringToColorCustom , which enables me to insert any desired hues into the method.

My recommendation is to utilize a translation table implemented with a HashMap.

 HashMap table = new HashMap<>(); table.put(new NamedColor("red"), new RgbColor("#ff0000")); table.put(new NamedColor("blue"), new RgbColor("#0000ff")); 
class ColorConverter < // If you need reverse color conversion you can use handy bidirectoinal // maps from http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/bidimap/DualHashBidiMap.html private HashMaptable; public static RgbColor convert(NamedColor color) 

Adjust this outline to your needs.

 import javafx.scene.paint.Color; Color color = Color.web("orange"); System.out.printf("Color: %s, RGBA #%x%n", color, color.hashCode()); 

One can utilize reflection on all the constants defined in java.awt.Color, albeit at a slower speed.

private static Optional color(String name) < try < Field field = java.awt.Color.class.getDeclaredField(name.toUpperCase()); int modifiers = field.getModifiers(); if (field.getType() == java.awt.Color.class && Modifier.isStatic(modifiers && Modifier.isPublic(modifiers))) < return Optional.of((java.awt.Color)field.get(null)); >> catch (NoSuchFieldException e) < >return Optional.empty(); > 

There exist issues with names that contain underscores, which have been eliminated in JavaFX.

 System.out.println("RGBA " + color("orange") .map(c -> String.format("#%x", c.getRGB())) .orElse("(unknown)")); 

Despite the availability of an alternative solution for CSS support in Java's HTML with color names, I have not actively searched for it.

Java int rgb to hex Code Example, Follow. GREPPER; SEARCH ; WRITEUPS; FAQ; DOCS ; INSTALL GREPPER; Log In; Signup

Java - Decimal color to RGB color

As you mentioned earlier, RGB values are represented by bytes in a int . The red color is assigned to byte 2, green is assigned to byte 1 and blue is assigned to byte 0, making it a 24-bit color depth. The representation may vary depending on the endianess.

00000000 00000000 00000000 00000000  

It is possible to obtain the RGB values by performing bit shifting and masking.

int red = (color >> 16) & 0xff; int green = (color >> 8) & 0xff; int blue = color & 0xff; 
Color color = new Color(16777215); int red = color.getRed(); int green = color.getGreen(); int blue = color.getBlue(); 

It is possible to extract the channels using basic bitwise operations.

int r = (color >> 16) & 0xff; int g = (color >> 8) & 0xff; int b = color & 0xff; 

Once you have obtained the color information, manipulating it to your liking should be a straightforward task.

Java - Converting RGB values into color, I have a java code that returns decimal values as shown below [1.0, 0.0, 0.0] for Red [0.0, 1.0, 0.0] for Green the first value denotes the color code for Red, the second value denotes color code for Green and the third value denotes Color code for Blue. Is there any way we can convert these RGB values into …

Converting RGB values into color

An illustration is provided wherein the color name is retrieved based on the utilization of Reflection to obtain the name of the color (java.awt.Color).

public static String getNameReflection(Color colorParam) < try < //first read all fields in array Field[] field = Class.forName("java.awt.Color").getDeclaredFields(); for (Field f : field) < String colorName = f.getName(); Class t = f.getType(); if (t == java.awt.Color.class) < Color defined = (Color) f.get(null); if (defined.equals(colorParam)) < System.out.println(colorName); return colorName.toUpperCase(); >> > > catch (Exception e) < System.out.println("Error. " + e.toString()); >return "NO_MATCH"; > 
 Color colr = new Color(1.0f, 0.0f, 0.0f); Main m = new Main(); m.getNameReflection(colr); > 

It's important to note that the colors were defined by "java.awt.Color" .

white WHITE lightGray LIGHT_GRAY gray GRAY darkGray DARK_GRAY black BLACK red RED pink PINK orange ORANGE yellow YELLOW green GREEN magenta MAGENTA cyan CYAN blue BLUE 

Java - Decimal color to RGB color, I have a decimal (not hexadecimal) color code and, using Java, I need to convert it to the three RGB colors. So for example, 16777215 (pure white) needs to get converted to Red: 255 Green: 255 Blue: 255. 65280 (pure green) needs to get converted to Red: 0 Green 255: Blue: 0. Here is a converter for more examples.

Hex to color java

Java rgb to color

public int getIntFromColor(int Red, int Green, int Blue)< Red = (Red 

Источник

Читайте также:  Сортировка шелла алгоритм java
Оцените статью