如何为imagecolorallocate提供颜色?

时间:2010-06-02 12:24:11

标签: php string colors hex

我有一个PHP变量,其中包含有关颜色的信息。例如$text_color = "ff90f3"。现在我想将此颜色赋予imagecolorallocateimagecolorallocate就是这样的:

imagecolorallocate($im, 0xFF, 0xFF, 0xFF);

所以,我正在努力做到以下几点:

$r_bg = bin2hex("0x".substr($text_color,0,2));
$g_bg = bin2hex("0x".substr($text_color,2,2));
$b_bg = bin2hex("0x".substr($text_color,4,2));
$bg_col = imagecolorallocate($image, $r_bg, $g_bg, $b_bg);

它不起作用。为什么?我也尝试了没有bin2hex,它也没有用。有人可以帮我吗?

3 个答案:

答案 0 :(得分:8)

来自http://forums.devshed.com/php-development-5/gd-hex-resource-imagecolorallocate-265852.html

function hexColorAllocate($im,$hex){
    $hex = ltrim($hex,'#');
    $a = hexdec(substr($hex,0,2));
    $b = hexdec(substr($hex,2,2));
    $c = hexdec(substr($hex,4,2));
    return imagecolorallocate($im, $a, $b, $c); 
}

用法

$img = imagecreatetruecolor(300, 100);
$color = hexColorAllocate($img, 'ffff00');
imagefill($img, 0, 0, $color); 

颜色可以作为十六进制ffffff#ffffff

传递

答案 1 :(得分:6)

使用hexdec()(例如:hexdec("a0")

http://fr2.php.net/manual/en/function.hexdec.php

答案 2 :(得分:1)

function hex2RGB($hexStr, $returnAsString = false, $seperator = ',') {
    $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
    $rgbArray = array();
    if (strlen($hexStr) == 6) { //If a proper hex code, convert using bitwise operation. No overhead... faster
        $colorVal = hexdec($hexStr);
        $rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
        $rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
        $rgbArray['blue'] = 0xFF & $colorVal;
    } elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations
        $rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
        $rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
        $rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
    } else {
        return false; //Invalid hex color code
    }
    return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array
}