Fabian
Fabian

Reputation: 3495

Triple HEX code to RGB

I'm having toubles with converting triple HEX color codes in an RGB color code.

What I've got so far for HEX to RGB is:

if(strlen($hex) == 3) {
        $color['r'] = hexdec(substr($hex, 0, 1) . $r);
        $color['g'] = hexdec(substr($hex, 1, 1) . $g);
        $color['b'] = hexdec(substr($hex, 2, 1) . $b);
    }

When I convert the RGB code back to HEX it's a different one.

E.g.: #FFF becomes 15, 15, 15 but 15, 15, 15 is #0F0F0F

I'm also not sure about converting RGB back to triple HEX code. My code for RGB to HEX looks like this:

$hex = str_pad(dechex($r), 2, "0", STR_PAD_LEFT);
$hex.= str_pad(dechex($g), 2, "0", STR_PAD_LEFT);
$hex.= str_pad(dechex($b), 2, "0", STR_PAD_LEFT);

Any help is greatly appreciated! Thanks in advance!

Upvotes: 2

Views: 961

Answers (2)

Fleep
Fleep

Reputation: 429

function hex2rgb($hex)
{
    // Ensure we're working only with upper-case hex values,
    // toss out any extra characters.
    $hex = preg_replace('/[^A-F0-9]/', '', strtoupper($hex));

    // Convert 3-letter hex RGB codes into 6-letter hex RGB codes
    $hex_len = strlen($hex);
    if ($hex_len == 3) {
        $new_hex = '';
        for ($i = 0; $i < $hex_len; ++$i) {
            $new_hex .= $hex[$i].$hex[$i];
        }
        $hex = $new_hex;
    }

    // Calculate the RGB values
    $rgb['r'] = hexdec(substr($hex, 0, 2));
    $rgb['g'] = hexdec(substr($hex, 2, 2));
    $rgb['b'] = hexdec(substr($hex, 4, 2));

    return $rgb;
}

print_r(hex2rgb('#fff'));      // r: 255 g: 255 b: 255
print_r(hex2rgb('#AE9C00'));   // r: 174 g: 156 b: 0

Upvotes: 2

Adonais
Adonais

Reputation: 1292

It looks like you need to handle triplets in a different way: #XYZ = #XXYYZZ. #FFF should be, for example, the same as #FFFFFF, or well, (255, 255, 255), instead of (15, 15, 15).

So, a way to do this is with the following code:

if(strlen($hex) == 3) {
    $color['r'] = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
    $color['g'] = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
    $color['b'] = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
}

Note I'm not including $r, $g and $b, as I don't know why are you using them.

Upvotes: 2

Related Questions