Return the "distance" between two colors. - Java 2D Graphics

Java examples for 2D Graphics:Color

Description

Return the "distance" between two colors.

Demo Code

/*/*from   w w w. java2  s .  com*/
Storybook: Scene-based software for novelists and authors.
Copyright (C) 2008 - 2011 Martin Mustun

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import java.awt.Color;

public class Main{
    public static void main(String[] argv) throws Exception{
        double[] color1 = new double[]{34.45,35.45,36.67,37.78,37.0000,37.1234,67.2344,68.34534,69.87700};
        double[] color2 = new double[]{34.45,35.45,36.67,37.78,37.0000,37.1234,67.2344,68.34534,69.87700};
        System.out.println(colorDistance(color1,color2));
    }
    /**
     * Return the "distance" between two colors. The rgb entries are taken to be
     * coordinates in a 3D space [0.0-1.0], and this method returnes the
     * distance between the coordinates for the first and second color.
     *
     * @param r1
     *            , g1, b1 First color.
     * @param r2
     *            , g2, b2 Second color.
     * @return Distance bwetween colors.
     */
    public static double colorDistance(double r1, double g1, double b1,
            double r2, double g2, double b2) {
        double a = r2 - r1;
        double b = g2 - g1;
        double c = b2 - b1;
        return Math.sqrt(a * a + b * b + c * c);
    }
    /**
     * Return the "distance" between two colors.
     *
     * @param color1
     *            First color [r,g,b].
     * @param color2
     *            Second color [r,g,b].
     * @return Distance bwetween colors.
     */
    public static double colorDistance(double[] color1, double[] color2) {
        return ColorUtil.colorDistance(color1[0], color1[1], color1[2],
                color2[0], color2[1], color2[2]);
    }
    /**
     * Return the "distance" between two colors.
     *
     * @param color1
     *            First color.
     * @param color2
     *            Second color.
     * @return Distance between colors.
     */
    public static double colorDistance(Color color1, Color color2) {
        float rgb1[] = new float[3];
        float rgb2[] = new float[3];
        color1.getColorComponents(rgb1);
        color2.getColorComponents(rgb2);
        return ColorUtil.colorDistance(rgb1[0], rgb1[1], rgb1[2], rgb2[0],
                rgb2[1], rgb2[2]);
    }
}

Related Tutorials