Tag Archives: converter

PHP: Convert Web Hex Color Code to RGB Array Programming 18 OCT 2010

green php elephants - elephpantsSometimes you need to RGB array that makes up a color when working in the wonderful world of PHP. Don’t ask me why or when, though that said, I have required it at least once before when setting text color whilst generating PDFs using the FPDF library – so I have at least established that you do sometimes want to do this.

So let’s scribble down a neat little function that will convert a plain old web hex color to its RGB components for us then, shall we?

function convertHexToRGB($hex) {
    $hex = ereg_replace("#", "", $hex);
    $color = array();
    if(strlen($hex) == 3) {
            $color['r'] = hexdec(substr($hex, 0, 1));
            $color['g'] = hexdec(substr($hex, 1, 1));
            $color['b'] = hexdec(substr($hex, 2, 1));
    }
    else if(strlen($hex) == 6) {
            $color['r'] = hexdec(substr($hex, 0, 2));
            $color['g'] = hexdec(substr($hex, 2, 2));
            $color['b'] = hexdec(substr($hex, 4, 2));
    }
    return $color;
}

As you can see, the function does little more than make use of the useful hexdec function, though it neatly deals with hex codes that may or may not come in with the standard # prefix, or in the shorthand three character length instead of the standard six characters.

So now you know.

PHP: Convert a RGB color Array into a Web Hex Code Programming 15 OCT 2010

green php elephants - elephpantsRGB, that annoying little way of expressing a color via values between 0 and 255 for each of the three components that makes up a color. Always in the form of an array consisting of three values, namely one for red, one for green and one for blue, wouldn’t it be nice if we had a simple function that automatically converted such an array to the more universal web hex code? (Well when I say universal I mean developing on the web).

So let’s do that then. The following little function accepts three inputs, namely the red, green and blue values, converts each to the hexadecimal equivalent with the correct padding (remember a correct hex code is six characters long), concatenates them all together and returns a nice # prefix hex code string for us.

function convertRGBToHex($r, $g, $b) {
    $hex = "#";
    $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);
    return $hex;
}

Simple, clean, and oh so useful (especially when dealing with firefox which seems to enjoy throwing color values as RGB arrays at you!).