views:

21

answers:

2

Can you allocate a color in PHP GD without an image resource? It should be possible because really an allocated color is a number, right?

$im = imagecreatetruecolor(100, 100);
$col = imagecolorallocate($im, 255, 0, 0);
print $col."<br/>";
$col2 = imagecolorallocate($im, 255, 0, 0);
print $col2."<br/>";
$im2 = imagecreatetruecolor(600, 100);
$col3 = imagecolorallocate($im, 255, 0, 0);
print $col3;

This prints out:

16711680

16711680

16711680

I guess what the real question is how 255, 0, and 0 are made into 16711680.

+1  A: 

It should be possible because really an allocated color is a number, right?

No, it's not. GD may also have to register that color in the palette of the image (think non true color images).

So you need an image resource.

Artefacto
I just found something on http://php.net/manual/en/function.imagecolorallocate.php. The fourth user comment has a way... is it valid?
Mark
See the edit also...
Mark
@Mark That only works for true color images.
Artefacto
I suggest correct because it's useful for truecolors
Mark
+1  A: 

16711680 (decimal) is 0x00FF0000 (hexadecimal)

00 - Alpha value (0 dec)

FF - Red (255 dec)

00 - Green (0 dec)

00 - Blue (0 dec)

See http://www.php.net/manual/en/function.imagecolorallocatealpha.php to set the alpha byte

Edit:

Also, to answer your first question -- yes, you can create a color without an image resource (and, consequently without a call to imagecolorallocate):

$col1 = 0x00FF0000; // Red

$col2 = 0x0000FF00; // Green

// etc...

vdeych
Only true color images...
Artefacto