2010-06-02 9 views
5

J'ai une variable PHP qui contient des informations sur la couleur. Par exemple $text_color = "ff90f3". Maintenant, je veux donner cette couleur à imagecolorallocate. Les imagecolorallocate œuvres comme ça:Comment puis-je donner une couleur à imagecolorallocate?

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

Alors, je suis en train de faire ce qui suit:

$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); 

Il ne fonctionne pas. Pourquoi? Je l'essaie aussi sans bin2hex, ça n'a pas marché non plus. Quelqu'un peut-il m'aider avec ça?

+0

Que fait la fonction bin2hex? –

+0

Je mets bin2hex là pour transformer les chaînes en nombre hexadécimal qui devrait être donné à imagecolorallocate. – Roman

+0

quelle est la différence entre "chaîne" et "nombre hexadécimal"? Et je demandais ce que cette fonction fait, pas pourquoi l'avez-vous utilisé. Que retourne-t-il au moins? Dans ce cas, je veux dire –

Répondre

5

De 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); 
} 

Utilisation

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

la couleur peut être passé comme hex ffffff ou

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 
}