3 namespace Drupal\Component\Utility;
6 * Performs color conversions.
11 * Validates whether a hexadecimal color value is syntactically correct.
14 * The hexadecimal string to validate. May contain a leading '#'. May use
15 * the shorthand notation (e.g., '123' for '112233').
18 * TRUE if $hex is valid or FALSE if it is not.
20 public static function validateHex($hex) {
22 $valid = is_string($hex);
23 // Hash prefix is optional.
24 $hex = ltrim($hex, '#');
25 // Must be either RGB or RRGGBB.
26 $length = Unicode::strlen($hex);
27 $valid = $valid && ($length === 3 || $length === 6);
28 // Must be a valid hex value.
29 $valid = $valid && ctype_xdigit($hex);
34 * Parses a hexadecimal color string like '#abc' or '#aabbcc'.
37 * The hexadecimal color string to parse.
40 * An array containing the values for 'red', 'green', 'blue'.
42 * @throws \InvalidArgumentException
44 public static function hexToRgb($hex) {
45 if (!self::validateHex($hex)) {
46 throw new \InvalidArgumentException("'$hex' is not a valid hex value.");
49 // Ignore '#' prefixes.
50 $hex = ltrim($hex, '#');
52 // Convert shorthands like '#abc' to '#aabbcc'.
53 if (strlen($hex) == 3) {
54 $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
60 'red' => $c >> 16 & 0xFF,
61 'green' => $c >> 8 & 0xFF,
67 * Converts RGB color arrays and RGB strings in CSS notation to lowercase
68 * simple colors like '#aabbcc'.
70 * @param array|string $input
71 * The value to convert. If the value is an array the first three elements
72 * will be used as the red, green and blue components. String values in CSS
73 * notation like '10, 20, 30' are also supported.
76 * The lowercase simple color representation of the given color.
78 public static function rgbToHex($input) {
79 // Remove named array keys if input comes from Color::hex2rgb().
80 if (is_array($input)) {
81 $rgb = array_values($input);
83 // Parse string input in CSS notation ('10, 20, 30').
84 elseif (is_string($input)) {
85 preg_match('/(\d+), ?(\d+), ?(\d+)/', $input, $rgb);
90 foreach ($rgb as $k => $v) {
91 $out |= $v << (16 - $k * 8);
94 return '#' . str_pad(dechex($out), 6, 0, STR_PAD_LEFT);