Convert hex color to RGB values in PHP
Solution 1:
If you want to convert hex to rgb you can use sscanf:
<?php
$hex = "#ff9900";
list($r, $g, $b) = sscanf($hex, "#%02x%02x%02x");
echo "$hex -> $r $g $b";
?>
Output:
#ff9900 -> 255 153 0
Solution 2:
Check out PHP's hexdec()
and dechex()
functions:
http://php.net/manual/en/function.hexdec.php
Example:
$value = hexdec('ff'); // $value = 255
Solution 3:
I made a function which also returns alpha if alpha is provided as a second parameter the code is below.
The function
function hexToRgb($hex, $alpha = false) {
$hex = str_replace('#', '', $hex);
$length = strlen($hex);
$rgb['r'] = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0));
$rgb['g'] = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0));
$rgb['b'] = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0));
if ( $alpha ) {
$rgb['a'] = $alpha;
}
return $rgb;
}
Example of function responses
print_r(hexToRgb('#19b698'));
Array (
[r] => 25
[g] => 182
[b] => 152
)
print_r(hexToRgb('19b698'));
Array (
[r] => 25
[g] => 182
[b] => 152
)
print_r(hexToRgb('#19b698', 1));
Array (
[r] => 25
[g] => 182
[b] => 152
[a] => 1
)
print_r(hexToRgb('#fff'));
Array (
[r] => 255
[g] => 255
[b] => 255
)
If you'd like to return the rgb(a) in CSS format just replace the return $rgb;
line in the function with return implode(array_keys($rgb)) . '(' . implode(', ', $rgb) . ')';
Solution 4:
For anyone that is interested this is another very simple way of doing it. This example assumes there is exactly 6 characters and no preceding pound sign.
list($r, $g, $b) = array_map('hexdec', str_split($colorName, 2));
Here is an example the supports 4 different inputs (abc, aabbcc, #abc, #aabbcc):
list($r, $g, $b) = array_map(
function ($c) {
return hexdec(str_pad($c, 2, $c));
},
str_split(ltrim($colorName, '#'), strlen($colorName) > 4 ? 2 : 1)
);