在java中将颜色名称转换为RGB值

时间:2017-02-07 11:19:36

标签: java

当颜色名称作为输入时,我想要RGB值。以下代码适用于某些颜色(我猜是原色如RED)而其他一些颜色则失败(如CYAN,MAUVE)

import java.awt.Color;
import javax.swing.text.html.StyleSheet;

public class ColourTest {
    public static void main(String[] args) {
        StyleSheet s = new StyleSheet();
        String colourName="RED";
        Color clr = s.stringToColor(colourName);
        int r=clr.getRed();
        int g=clr.getGreen();
        int b=clr.getBlue();
        System.out.println("red:" + r + " green :" + g + " blue:" + b);
    }
}

还有其他方法可以获取颜色名称的RGB值吗?

3 个答案:

答案 0 :(得分:1)

这是我在javax.swing.text.html.CSS班级

中找到的内容
/**
 * 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;
}

因此,如果您传递上述代码中不存在的任何颜色,您将很遗憾地获得NullPointerException

但是,我找到了解决问题的方法。使用此代码:

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

在上面的代码中,我创建了一个自定义stringToColorCustom方法,现在我可以在该方法中添加我想要的任何颜色。

希望它有所帮助!

答案 1 :(得分:0)

我建议通过HashMap使用一种翻译表:

    HashMap<NamedColor, RgbColor> 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 HashMap<Color, RgbColor> table;

    public static RgbColor convert(NamedColor color) {
        return table.get(color);
    }

根据您的需要调整此大纲。

答案 2 :(得分:0)

最简单的javafx:

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

对于java.awt.Color,可以在所有定义在那里的常量上使用(缓慢)反射:

private static Optional<java.awt.Color> 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();
}

这里使用下划线的名称存在一些问题(已在javafx中删除)。

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

由于带有颜色名称的Java HTML支持CSS,因此应该存在其他解决方案,但我从未寻求过。