note 96780 deleted from function.hexdec by thiago
| From: | thiago@php.net | Date: | Tue, 16 Mar 2010 19:17:42 +0000 |
| Subject: | note 96780 deleted from function.hexdec by thiago | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-167112@lists.php.net to get a copy of this message | ||
Note Submitter: Adam
----
Someone might find this helpful.
/**
* Return an array of RGB color values from either a HEX string,
* an array (R,G,B) or a comma deliminiated string (255, 255, 255).
* @since 1.0.0
* @param string|array $value
* @return array
* @access public
*/
public function toRgb($value)
{
if (is_string($value))
{
$value = str_replace('#', '', $value);
$value = explode(',', $value);
if (sizeof($value) == 1)
{
$value = $value[0];
if (strlen($value) == 6)
{
list($r, $g, $b) = array($value[0].$value[1], $value[2].$value[3], $value[4].$value[5]);
}
else if (strlen($value) == 3)
{
list($r, $g, $b) = array($value[0].$value[0], $value[1].$value[1], $value[2].$value[2]);
}
else
{
list($r, $g, $b) = array('FF', 'FF', 'FF');
}
$value = array(hexdec($r), hexdec($g), hexdec($b));
}
else if (sizeof($value) == 3)
{
$value = $this->toRgb($value);
}
}
else if (is_array($value) && sizeof($value) == 3)
{
$colors = array();
foreach ($value as $color)
{
$color = intval($color);
if ($color < 0)
{
array_push($colors, 0);
}
else if ($color > 255)
{
array_push($colors, 255);
}
else
{
array_push($colors, $color);
}
}
$value = $colors;
}
else
{
$value = array(255, 255, 255);
}
return $value;
}
// Use-case:
list($r, $g, $b) = $this->toRgb('#FF9900');
echo 'R: '.$r."\n";
echo 'G: '.$g."\n";
echo 'B: '.$b."\n";
// Outputs
// R: 255
// G: 153
// B: 0
// Either combinations should work.
// $this->toRgb('#FF9900');
// $this->toRgb(array(255, 153, 0));
// $this->toRgb('255, 153, 0')