php - finding nearest match RGB color from color palate array

时间:2016-07-11 19:04:42

标签: php rgb

I know I need to use a loop to look in the $palate Array, but I need help making the color comparison.

GOAL is find the nearest value of $rgbcolor to $palate and show the color that matches from $palate.

<?php
//input color
$rgbcolor = array(110,84,43); 
//listed color
$palate = array(
    array(238,216,152),
    array(252,216,113),
    array(253,217,0),
    array(255,208,62),
    array(255,182,20),
    array(206,137,0),
    array(235,169,0),
    array(170,137,0),
    array(173,132,28),
    array(183,131,0),
    array(139,120,37),
    array(108,86,26)
);
?>

1 个答案:

答案 0 :(得分:3)

There are many different ways to determine color "distance."

There's absolute distance, i.e. the sum of the differences between each channel value:

function absoluteColorDistance($color_a, $color_b) {
    return
        abs($color_a[0] - $color_b[0]) +
        abs($color_a[1] - $color_b[1]) +
        abs($color_a[2] - $color_b[2]);
}

There's also difference in luminosity, which will give more of a color-independent comparison:

function luminanceDistance($color_a, $color_b) {
    $luminance_f = function ($red, $green, $blue) {
        // source: https://en.wikipedia.org/wiki/Relative_luminance
        $luminance = (int) (0.2126*$red + 0.7152*$green + 0.0722*$blue);
        return $luminance;
    };

    return abs(
        $luminance_f($color_a[0], $color_a[1], $color_a[2]) -
        $luminance_f($color_b[0], $color_b[1], $color_b[2])
    );
}

Once you figure out how to compare colors, the next problem you need to solve is finding the color with the least distance from your target color:

$nearest_distance = null;
$nearest_color = null;
foreach ($palate as $test_color) {
    $test_distance = luminanceDistance($test_color, $rgbcolor);
    if (isset($nearest_distance)) {
        if ($nearest_distance > $test_distance) {
            // found a closer color
            $nearest_distance = $test_distance;
            $nearest_color = $test_color;
        }
    } else {
        $nearest_color = $test_color;
        $nearest_distance = $test_distance;
    }
}