Return to Snippet

Revision: 8223
at September 9, 2008 15:15 by Jacolyte


Updated Code
function img_colorallocate($img, $color) {
        // strip away any non hex characters, to allow flexibility with the function
        $color = ereg_replace('[^A-Fa-f0-9]|(0x)|(0X)', '', $color);
        if ( strlen($color) != 6 || !preg_match('/[0-9a-fA-F]{6}/', $color) ) {
                die("The value provided does not contain a valid 6 digit hex value.");
        }
        $color = imagecolorallocate(
                $img,
                hexdec($color[0] . $color[1]),
                hexdec($color[2] . $color[3]),
                hexdec($color[4] . $color[5])
        );
        return $color;
}

Revision: 8222
at September 9, 2008 13:55 by Jacolyte


Initial Code
function img_colorallocate($img, $color) {
        // strip away any non hex characters, to allow flexibility with the function
        $color = ereg_replace('[^A-Fa-f0-9]|(0x)|(0X)', '', $color);
        if ( strlen($color) != 6 && !preg_match('/[0-9a-fA-F]{6}/', $color) ) {
                die("The value provided does not contain a valid 6 digit hex value.");
        }
        $color = imagecolorallocate(
                $img,
                hexdec($color[0] . $color[1]),
                hexdec($color[2] . $color[3]),
                hexdec($color[4] . $color[5])
        );
        return $color;
}

Initial URL
http://jacolyte.com

Initial Description
This function will allow you to use '#ABCDEF' or '0xEEFF33' instead of the RGB values required for imagecolorallocate() by stripping away any non hex characters. It will also check and make sure that it's a valid 6 digit hex value after the stripping of non-hex characters takes place.

it simply uses the function hexdec() to convert each R, G, and B hex values to decimal, and then passes them to imagecolorallocate() individually.

See the page: http://us3.php.net/imagecolorallocate
to learn how to use this wrapper function.

Initial Title
imgcolorallocate wrapper that allows hex values instead of RGB

Initial Tags
php

Initial Language
PHP