RGB.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace fphammerle\helpers\colors;
  3. class RGB
  4. {
  5. use \fphammerle\helpers\PropertyAccessTrait;
  6. const comparison_precision = 0.00001;
  7. private $_red;
  8. private $_green;
  9. private $_blue;
  10. public function __construct($red = 0, $green = 0, $blue = 0)
  11. {
  12. $this->setRed($red);
  13. $this->setGreen($green);
  14. $this->setBlue($blue);
  15. }
  16. public function getRed()
  17. {
  18. return $this->_red;
  19. }
  20. public function setRed($red)
  21. {
  22. $red = (float)$red;
  23. if($red < 0 || $red > 1) {
  24. throw new \UnexpectedValueException('value must be within [0, 1]');
  25. }
  26. $this->_red = $red;
  27. }
  28. public function getGreen()
  29. {
  30. return $this->_green;
  31. }
  32. public function setGreen($green)
  33. {
  34. $green = (float)$green;
  35. if($green < 0 || $green > 1) {
  36. throw new \UnexpectedValueException('value must be within [0, 1]');
  37. }
  38. $this->_green = $green;
  39. }
  40. public function getBlue()
  41. {
  42. return $this->_blue;
  43. }
  44. public function setBlue($blue)
  45. {
  46. $blue = (float)$blue;
  47. if($blue < 0 || $blue > 1) {
  48. throw new \UnexpectedValueException('value must be within [0, 1]');
  49. }
  50. $this->_blue = $blue;
  51. }
  52. public function equals(RGB $other)
  53. {
  54. return abs($this->red - $other->red) < self::comparison_precision
  55. && abs($this->green - $other->green) < self::comparison_precision
  56. && abs($this->blue - $other->blue) < self::comparison_precision;
  57. }
  58. public function getTuple()
  59. {
  60. return [$this->red, $this->green, $this->blue];
  61. }
  62. public function getDigitalTuple($bits)
  63. {
  64. $bits = (int)$bits;
  65. $factor = (2 << ($bits - 1)) - 1;
  66. $tuple = $this->tuple;
  67. return array_map(function($v) use ($factor) { return (int)round($v * $factor); }, $tuple);
  68. }
  69. public function getDigitalHexTuple($bits)
  70. {
  71. return array_map(function($v) { return dechex($v); }, $this->getDigitalTuple($bits));
  72. }
  73. /**
  74. * @return string
  75. */
  76. public function getHexTriplet()
  77. {
  78. return implode('', array_map(
  79. function($s) { return str_pad($s, 2, '0', STR_PAD_LEFT); },
  80. $this->getDigitalHexTuple(8)
  81. ));
  82. }
  83. }