Converting RGB values into color

2019-08-05 05:08发布

问题:

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 the respective color in java?

回答1:

There are an example to return the color name which depend on using Reflection to get 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";
    }

and in the main

        Color colr = new Color(1.0f, 0.0f, 0.0f);
        Main m = new Main();
        m.getNameReflection(colr);
    }

You have to know that :"java.awt.Color" defined this colors:

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 colors rgb