1
0

RGB.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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(
  37. sprintf('value must be within [0, 1], %f given', $green)
  38. );
  39. }
  40. $this->_green = $green;
  41. }
  42. public function getBlue()
  43. {
  44. return $this->_blue;
  45. }
  46. public function setBlue($blue)
  47. {
  48. $blue = (float)$blue;
  49. if($blue < 0 || $blue > 1) {
  50. throw new \UnexpectedValueException('value must be within [0, 1]');
  51. }
  52. $this->_blue = $blue;
  53. }
  54. public function equals(RGB $other)
  55. {
  56. return abs($this->red - $other->red) < self::comparison_precision
  57. && abs($this->green - $other->green) < self::comparison_precision
  58. && abs($this->blue - $other->blue) < self::comparison_precision;
  59. }
  60. public function getTuple()
  61. {
  62. return [$this->red, $this->green, $this->blue];
  63. }
  64. public function getDigitalTuple($bits)
  65. {
  66. $factor = (2 << ($bits - 1)) - 1;
  67. return array_map(
  68. function($v) use ($factor) { return (int)round($v * $factor); },
  69. $this->tuple
  70. );
  71. }
  72. public function getDigitalHexTuple($bits)
  73. {
  74. return array_map(function($v) { return dechex($v); }, $this->getDigitalTuple($bits));
  75. }
  76. /**
  77. * @return string
  78. */
  79. public function getHexTriplet()
  80. {
  81. return implode('', array_map(
  82. function($s) { return str_pad($s, 2, '0', STR_PAD_LEFT); },
  83. array_slice($this->getDigitalHexTuple(8), 0, 3)
  84. ));
  85. }
  86. }