如何为imagecolorallocate提供颜色?

Rom*_*man 7 php string hex colors

我有一个PHP变量,其中包含有关颜色的信息.例如$text_color = "ff90f3".现在我想给这个颜色imagecolorallocate.这样的imagecolorallocate作品:

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);
Run Code Online (Sandbox Code Playgroud)

这是行不通的.为什么?我也尝试了没有bin2hex,它也没有用.任何人都可以帮助我吗?

Tim*_*nen 11

来自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); 
}
Run Code Online (Sandbox Code Playgroud)

用法

$img = imagecreatetruecolor(300, 100);
$color = hexColorAllocate($img, 'ffff00');
imagefill($img, 0, 0, $color); 
Run Code Online (Sandbox Code Playgroud)

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