1<?php 2/** 3 * BaconQrCode 4 * 5 * @link http://github.com/Bacon/BaconQrCode For the canonical source repository 6 * @copyright 2013 Ben 'DASPRiD' Scholzen 7 * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License 8 */ 9 10namespace BaconQrCode\Renderer\Color; 11 12use BaconQrCode\Exception; 13 14/** 15 * RGB color. 16 */ 17class Rgb implements ColorInterface 18{ 19 /** 20 * Red value. 21 * 22 * @var integer 23 */ 24 protected $red; 25 26 /** 27 * Green value. 28 * 29 * @var integer 30 */ 31 protected $green; 32 33 /** 34 * Blue value. 35 * 36 * @var integer 37 */ 38 protected $blue; 39 40 /** 41 * Creates a new RGB color. 42 * 43 * @param integer $red 44 * @param integer $green 45 * @param integer $blue 46 */ 47 public function __construct($red, $green, $blue) 48 { 49 if ($red < 0 || $red > 255) { 50 throw new Exception\InvalidArgumentException('Red must be between 0 and 255'); 51 } 52 53 if ($green < 0 || $green > 255) { 54 throw new Exception\InvalidArgumentException('Green must be between 0 and 255'); 55 } 56 57 if ($blue < 0 || $blue > 255) { 58 throw new Exception\InvalidArgumentException('Blue must be between 0 and 255'); 59 } 60 61 $this->red = (int) $red; 62 $this->green = (int) $green; 63 $this->blue = (int) $blue; 64 } 65 66 /** 67 * Returns the red value. 68 * 69 * @return integer 70 */ 71 public function getRed() 72 { 73 return $this->red; 74 } 75 76 /** 77 * Returns the green value. 78 * 79 * @return integer 80 */ 81 public function getGreen() 82 { 83 return $this->green; 84 } 85 86 /** 87 * Returns the blue value. 88 * 89 * @return integer 90 */ 91 public function getBlue() 92 { 93 return $this->blue; 94 } 95 96 /** 97 * Returns a hexadecimal string representation of the RGB value. 98 * 99 * @return string 100 */ 101 public function __toString() 102 { 103 return sprintf('%02x%02x%02x', $this->red, $this->green, $this->blue); 104 } 105 106 /** 107 * toRgb(): defined by ColorInterface. 108 * 109 * @see ColorInterface::toRgb() 110 * @return Rgb 111 */ 112 public function toRgb() 113 { 114 return $this; 115 } 116 117 /** 118 * toCmyk(): defined by ColorInterface. 119 * 120 * @see ColorInterface::toCmyk() 121 * @return Cmyk 122 */ 123 public function toCmyk() 124 { 125 $c = 1 - ($this->red / 255); 126 $m = 1 - ($this->green / 255); 127 $y = 1 - ($this->blue / 255); 128 $k = min($c, $m, $y); 129 130 return new Cmyk( 131 100 * ($c - $k) / (1 - $k), 132 100 * ($m - $k) / (1 - $k), 133 100 * ($y - $k) / (1 - $k), 134 100 * $k 135 ); 136 } 137 138 /** 139 * toGray(): defined by ColorInterface. 140 * 141 * @see ColorInterface::toGray() 142 * @return Gray 143 */ 144 public function toGray() 145 { 146 return new Gray(($this->red * 0.21 + $this->green * 0.71 + $this->blue * 0.07) / 2.55); 147 } 148}