Search code examples
phpresourcescolorsgdrgb

PHP allocate color without image resource


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.


Solution

  • 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...