Skip to content

Commit

Permalink
Merge pull request #2 from willemstuursma/closest-color
Browse files Browse the repository at this point in the history
Improve mechanism that picks the closest color
  • Loading branch information
ricardofiorani authored Oct 11, 2018
2 parents 787e18e + d7adb4c commit 7a91c1a
Showing 1 changed file with 14 additions and 12 deletions.
26 changes: 14 additions & 12 deletions src/Pallete/ColorPalette.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

class ColorPalette implements LegoPaletteInterface
{
private $palette = [
private const PALETTE = [
'024' => [
254,
196,
Expand Down Expand Up @@ -264,28 +264,30 @@ class ColorPalette implements LegoPaletteInterface
],
];

/**
* @link https://stackoverflow.com/questions/4485229/rgb-to-closest-predefined-color
*/
public function pickClosestColor(AbstractColor $color): AbstractColor
{
$distances = [];

$colorArray = $color->getArray();

foreach ($this->palette as $colorIdentifier => $colorSchema) {
$distance =
abs($colorSchema[0] - $colorArray[0]) +
abs($colorSchema[1] - $colorArray[1]) +
abs($colorSchema[2] - $colorArray[2]);
foreach (self::PALETTE as $colorIdentifier => $colorSchema) {
$rDistance = $colorSchema[0] - $colorArray[0];
$gDistance = $colorSchema[1] - $colorArray[1];
$bDistance = $colorSchema[2] - $colorArray[2];

$distances[$distance] = [$colorSchema[0], $colorSchema[1], $colorSchema[2]];
}
$distance = ($rDistance * .299) ** 2 + ($gDistance * .587) ** 2 + ($bDistance * .114) ** 2;

ksort($distances);
$distances[$colorIdentifier] = $distance;
}

$colorFound = reset($distances);
asort($distances);

list($r, $g, $b) = $colorFound;
$colorIdentifier = array_keys($distances)[0];

$color->initFromRgb($r, $g, $b);
$color->initFromRgb(...self::PALETTE[$colorIdentifier]);

return $color;
}
Expand Down

0 comments on commit 7a91c1a

Please sign in to comment.