There is no set function for this kind of behavior, but you could do something like this:
public static String getColorName(int r, int g, int b) {
String[] colorNames = new String[] {
"BLACK",
"BLUE",
"GREEN",
"CYAN",
"DARK_GRAY",
"GRAY",
"LIGHT_GRAY",
"MAGENTA",
"ORANGE",
"PINK",
"RED",
"WHITE",
"YELLOW"
};
Color userProvidedColor = new Color(r,g,b);
Color color;
Field field;
for (String colorName : colorNames) {
try {
field = Class.forName("java.awt.Color").getField(colorName);
color = (Color)field.get(null);
if (color.equals(userProvidedColor)) {
return colorName; // Or maybe return colorName.toLowerCase() for aesthetics
}
} catch (Exception e) {
}
}
Color someOtherCustomDefinedColorMaybePurple = new Color(128,0,128);
if (someOtherCustomDefinedColorMaybePurple.equals(userProvidedColor)) {
return "Purple";
}
return "Undefined";
}
There are a few options from here as well, maybe you want the nearest color? In which case you could try and resolve the distance somehow (here by distance from each r,g,b coordinate, admittedly not the best method but simple enough for this example, this wiki page has a good discussion on more rigorous methods)
// ...
String minColorName = "";
float minColorDistance = 10000000;
float thisColorDistance = -1;
for (String colorName : colorNames) {
try {
field = Class.forName("java.awt.Color").getField(colorName);
color = (Color)field.get(null);
thisColorDistance = ( Math.abs(color.red - userProvidedColor.red) + Math.abs(color.green - userProvidedColor.green) + Math.abs(color.blue - userProvidedColor.blue) );
if (thisColorDistance < minColorDistance) {
minColorName = colorName;
minColorDistance = thisColorDistance;
}
} catch (Exception e) {
// exception that should only be raised in the case color name is not defined, which shouldnt happen
}
}
if (minColorName.length > 0) {
return minColorName;
}
// Tests on other custom defined colors
This should outline how you would be able to compare to the built in colors from the Color
library. You could use a Map
to expand the functionality further to allow for you to define as many custom colors as you like (Something @TheGuywithTheHat suggests as well) which gives you more control over the return names of matched colors, and allows for you to go by more colors than just the predefined ones:
HashMap<String,Color> colorMap = new HashMap<String,Color>();
colorMap.put("Red",Color.RED);
colorMap.put("Purple",new Color(128,0,128));
colorMap.put("Some crazy name for a color", new Color(50,199,173));
// etc ...
String colorName;
Color color;
for (Map.Entry<String, Color> entry : colorMap.entrySet()) {
colorName = entry.getKey();
color= entry.getValue();
// Testing against users color
}