Skip to content

Instantly share code, notes, and snippets.

@AntonioCS
Created March 10, 2013 18:47
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 AntonioCS/5129826 to your computer and use it in GitHub Desktop.
Save AntonioCS/5129826 to your computer and use it in GitHub Desktop.
A simple hex to RGB converterd. Based on code from http://bavotasan.com/2011/convert-hex-color-to-rgb-using-php/
<?php
//Based on http://bavotasan.com/2011/convert-hex-color-to-rgb-using-php/
class hex2rgb {
private static $_cache = array();
private function __construct() {
}
/**
*
* @param string $hex
* @param bool $returnArray Return array and not as string
* @param bool $arrayIndex If specified return the given index
* @return string|array
*/
public static function convert($hex, $returnArray = false, $arrayIndex = null) {
if ($hex[0] == '#') {
$hex = substr($hex, 1);
}
$cKey = '_' . $hex;
$rgb = array();
if (!isset(self::$_cache[$cKey])) {
if (strlen($hex) == 3) {
$r = $hex[0] . $hex[0];
$g = $hex[1] . $hex[1];
$b = $hex[2] . $hex[2];
} else {
$r = substr($hex, 0, 2);
$g = substr($hex, 2, 2);
$b = substr($hex, 4);
}
$rgb = array(
hexdec($r),
hexdec($g),
hexdec($b)
);
self::$_cache[$cKey] = $rgb;
}
else {
$rgb = self::$_cache[$cKey];
}
if ($returnArray) {
if ($arrayIndex !== null && isset($rgb[$arrayIndex])) {
return $rgb[$arrayIndex];
}
return $rgb;
}
return implode(',', $rgb);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment