Skip to content

Instantly share code, notes, and snippets.

@SammyK
Created October 5, 2017 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SammyK/2c0cad8900dd52b35c1e6952e894d0e6 to your computer and use it in GitHub Desktop.
Save SammyK/2c0cad8900dd52b35c1e6952e894d0e6 to your computer and use it in GitHub Desktop.
Color RGB matcher
<?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