2010-06-02 92 views
5

我有一個PHP變量,其中包含有關顏色的信息。例如$text_color = "ff90f3"。現在我想給這個顏色imagecolorallocate。該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); 

它不工作。爲什麼?我嘗試它也沒有bin2hex,它也沒有工作。有人可以幫我嗎?

+0

bin2hex函數做什麼? – 2010-06-02 12:25:58

+0

我把bin2hex放在那裏把字符串轉換成應該給imagecolorallocate的十六進制數字。 – Roman 2010-06-02 12:29:49

+0

「string」和「hexadecimal number」有什麼區別?我問的是這個功能的作用,而不是你爲什麼使用它。它至少會返回什麼?在這種情況下,我的意思是 – 2010-06-02 12:34:32

回答

5

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

0
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 
}