Как я могу дать цвет для изображения? - PullRequest
7 голосов
/ 02 июня 2010

У меня есть переменная 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);

Не работает.Зачем?Я тоже пробую без bin2hex, тоже не получилось.Кто-нибудь может мне помочь с этим?

Ответы [ 3 ]

8 голосов
/ 22 апреля 2014

С 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 или как #ffffff

6 голосов
/ 02 июня 2010

Использование hexdec() (пример: hexdec("a0"))

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

1 голос
/ 19 января 2016
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
}
...