Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 229
Roman Avatar asked Jun 02 '10 12:06

Roman


People also ask

What is the Colour code for white Colour?

The hex code for white is #FFFFFF.

What is Imagecolorallocate PHP?

PHP Imagecolorallocate() Function. Imagecolorallocate( ) function is another inbuilt PHP function mainly used to implement a new color to an image. It returns the color of an image in an RGB format (RED GREEN BLUE)


1 Answers

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

like image 50
Timo Huovinen Avatar answered Oct 06 '22 00:10

Timo Huovinen