Monday 14 November 2011

RGB Hex and Int Conversions in PHP

Convert Hex to an Integer
hexdec("FFDDAA"); // returns 16768426

Convert an Integer to Hex
sprintf("%06X", 65280); // returns 00FF00
Can be used as a random color generator:
// get a random color (between 000000 and ffffff)
function randomColor() {
    return sprintf("%06X", rand(0, 16777215));
}

Get RGB Decimal values from Hex
$color = "34BB21";
$r = hexdec(substr($color, 0, 2)); // 52
$g = hexdec(substr($color, 2, 2)); // 187
$b = hexdec(substr($color, 4, 2)); // 33

And as a bonus.... RGB Hex validation
preg_match('/^[[:xdigit:]]{6}$/', $color);
For example:
function validate($color) {
    return (bool)preg_match('/^[[:xdigit:]]{6}$/', $color);
}

$tests = array(
    'asdfee',
    '123455',
    'DEAD12',
    'fde888',
    'gde888',
    'ffee',
    'blaarg'
);

foreach ($tests as $test) {
    print $test . "\t" . (validate($test) ? 'valid' : 'invalid') . "\n";
}

/*
Outputs

asdfee  invalid
123455  valid
DEAD12  valid
fde888  valid
gde888  invalid
ffee    invalid
blaarg  invalid
*/

No comments:

Post a Comment