Checks whether the two colors are similar for a given tolerance (in the sense of a distance between the RGB values). - Java 2D Graphics

Java examples for 2D Graphics:Color

Description

Checks whether the two colors are similar for a given tolerance (in the sense of a distance between the RGB values).

Demo Code


//package com.java2s;
import java.awt.Color;

public class Main {
    /**//from  w  ww .ja  va 2s .  c o m
     * Credits: http://www.java-gaming.org/index.php?topic=32741.0
     *
     * Checks whether the two colors are similar for a given tolerance (in the
     * sense of a distance between the RGB values).
     *
     * @param c1
     * @param c2
     * @param tolerance
     * @return Whether or not the two colors are similar for the given tolerance.
     */
    public static boolean colorsAreSimilar(final Color c1, final Color c2,
            final int tolerance) {
        int r1 = c1.getRed();
        int g1 = c1.getGreen();
        int b1 = c1.getBlue();
        int r2 = c2.getRed();
        int g2 = c2.getGreen();
        int b2 = c2.getBlue();

        return ((r2 - tolerance <= r1) && (r1 <= r2 + tolerance)
                && (g2 - tolerance <= g1) && (g1 <= g2 + tolerance)
                && (b2 - tolerance <= b1) && (b1 <= b2 + tolerance));
    }
}

Related Tutorials