PHP: Convert Hex Color to RGB, RGB to Hex Color


<?php

define('HEX2RBG_ARRAY', 1);
define('HEX2RBG_STRING', 2);

function hex2rgb($hex, $return = HEX2RBG_ARRAY)
{
    $hex = str_replace("#", "", $hex);

    if (strlen($hex) == 3) {
        $r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
        $g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
        $b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
    } else {
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));
    }
    $rgb = array('red' => $r, 'green' => $g, 'blue' => $b);

    if ($return == HEX2RBG_ARRAY)
        return $rgb; // returns an array with the rgb values
    else
        return implode(",", $rgb); // returns the rgb values separated by commas
}

function rgb2hex($rgb)
{
    $hex = "#";
    $hex .= str_pad(dechex($rgb[0]), 2, "0", STR_PAD_LEFT);
    $hex .= str_pad(dechex($rgb[1]), 2, "0", STR_PAD_LEFT);
    $hex .= str_pad(dechex($rgb[2]), 2, "0", STR_PAD_LEFT);

    return $hex; // returns the hex value including the number sign (#)
}

?>

Example 1:

<? print_r(hex2rgb('00ff67')); ?>

result:

Array
(
[red] => 0
[green] => 255
[blue] => 103
)

Example 2:

<?php echo hex2rgb('#00ff67', HEX2RBG_STRING); ?>

result:

0,255,103

Example 3:

<?php echo hex2rgb('#2f6', HEX2RBG_STRING); ?>

result:

34,255,102

Example 4:

<?php print_r(hex2rgb('##22ff66')); ?>

result:

Array
(
[red] => 34
[green] => 255
[blue] => 102
)

Other function hex2rgb

function hex2rgb($color, $return = HEX2RBG_ARRAY)
{
    if (strlen($color) > 1)
        if ($color[0] == '#')
            $color = substr($color, 1);

    if (strlen($color) == 6)
        list($r, $g, $b) = array($color[0] . $color[1], $color[2] . $color[3], $color[4] .
            $color[5]);
    elseif (strlen($color) == 3)
        list($r, $g, $b) = array($color[0] . $color[0], $color[1] . $color[1], $color[2] .
            $color[2]);
    else
        return false;

    $rgb = array('red' => hexdec($r), 'green' => hexdec($g), 'blue' => hexdec($b));
    if ($return == HEX2RBG_ARRAY)
        return $rgb;
    else
        return implode(",", $rgb);
}

Leave a Reply