2010-06-02 22 views
5

Tôi có một biến PHP chứa thông tin về màu sắc. Ví dụ: $text_color = "ff90f3". Bây giờ tôi muốn đưa màu này cho imagecolorallocate. Các imagecolorallocate công trình như thế:Làm thế nào tôi có thể cho một màu sắc để imagecolorallocate?

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

Vì vậy, tôi đang cố gắng để làm như sau:

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

Nó không làm việc. Tại sao? Tôi thử nó cũng không có bin2hex, nó cũng không hoạt động. Ai có thể giúp tôi với điều đó không?

+0

chức năng bin2hex hoạt động như thế nào? –

+0

Tôi đặt bin2hex ở đó để biến đổi chuỗi thành số thập lục phân cần được đưa vào imagecolorallocate. – Roman

+0

sự khác nhau giữa "chuỗi" và "số thập lục phân" là gì? Và tôi đã hỏi những gì chức năng này làm, không phải lý do tại sao bạn sử dụng nó. Nó trở lại ít nhất là gì? Trong trường hợp này, tôi có nghĩa là –

Trả lời

5

Từ 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); 
} 

Cách sử dụng

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

màu sắc có thể được thông qua như hex ffffff hoặc dưới dạng #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 
} 
Các vấn đề liên quan