Compares the given color to the 12 main colors and returns the name (e.g. - Java 2D Graphics

Java examples for 2D Graphics:Color

Description

Compares the given color to the 12 main colors and returns the name (e.g.

Demo Code

/**//from  w w  w.j a  v a  2s .  com
 * Copyright 1998-2008, CHISEL Group, University of Victoria, Victoria, BC, Canada.
 * All rights reserved.
 */
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.geom.Rectangle2D;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter;
import java.util.HashMap;
import java.util.Iterator;
import javax.swing.GrayFilter;

public class Main{
    private static final HashMap COLORS = new HashMap(13);
    /**
     * Compares the given color to the 12 main colors and returns
     * the name (e.g. "red") if it is one of them.  Otherwise the hex value
     * like #FF0000 is returned.
     * @param color
     * @return String "red" or "#ff0000"
     */
    public static String colorToString(Color color) {
        if (color != null) {
            // check the main colors
            for (Iterator iter = COLORS.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                Color c = (Color) COLORS.get(name);
                if (c.equals(color)) {
                    return name;
                }
            }
            // return the hex value
            return GraphicsUtils.colorToHexString(color);
        }
        return "";
    }
    /**
     * Converts a color into a String like #RRGGBB.
     * @param color   Color to convert into a String.
     * @return String color String.
     */
    public static String colorToHexString(Color color) {
        String colorStr = "";
        if (color != null) {
            colorStr = Integer.toHexString(color.getRGB());
            colorStr = "#" + colorStr.substring(2); // chop off the alpha value
        }
        return colorStr;
    }
}

Related Tutorials