Created
March 10, 2013 18:47
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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