Created
October 5, 2017 21:48
-
-
Save SammyK/2c0cad8900dd52b35c1e6952e894d0e6 to your computer and use it in GitHub Desktop.
Color RGB matcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Color | |
{ | |
private $hex; | |
private $r; | |
private $g; | |
private $b; | |
public function __construct(string $hex) { | |
$this->hex = ltrim($hex, '#'); | |
[$this->r, $this->g, $this->b] = self::makeRGB($this->hex); | |
} | |
public function r(): int { | |
return $this->r; | |
} | |
public function g(): int { | |
return $this->g; | |
} | |
public function b(): int { | |
return $this->b; | |
} | |
private static function makeRGB(string $hex): array { | |
return [ | |
hexdec(substr($hex, 0, 2)), | |
hexdec(substr($hex, 2, 2)), | |
hexdec(substr($hex, 4, 2)), | |
]; | |
} | |
// @see https://stackoverflow.com/a/9085524/443479 | |
public function distanceFrom(Color $color): float { | |
$rMean = ($this->r + $color->r()) / 2; | |
$r = $this->r - $color->r(); | |
$g = $this->g - $color->g(); | |
$b = $this->b - $color->b(); | |
return sqrt((((512+$rMean)*$r*$r)>>8) + 4*$g*$g + (((767-$rMean)*$b*$b)>>8)); | |
} | |
public function __toString(): string { | |
return "#" . $this->hex; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment