简体   繁体   中英

How can I give a color to imagecolorallocate?

I have a PHP variable which contains information about color. For example $text_color = "ff90f3" . Now I want to give this color to imagecolorallocate . The imagecolorallocate works like that:

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

So, I am trying to do the following:

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

It does not work. Why? I try it also without bin2hex, it also did not work. Can anybody help me with that?

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

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

Usage

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

the color can be passed as hex ffffff or as #ffffff

Use hexdec() (exemple : hexdec("a0") )

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM