Jump to content

Why isn't imageColorAllocateAlpha required here?


doug

Recommended Posts

In this example from the book I'm reading:

<?$im = ImageCreateTrueColor(256,60); for($x=0; $x<256; $x++) {     ImageLine($im, $x, 0, $x, 19, $x);     ImageLine($im, 255-$x, 20, 255-$x, 39, $x<<8);     ImageLine($im, $x, 40, $x, 59, $x<<16); } header('Content-Type: image/png'); ImagePNG($im); ?>

three color bars are drawn.I understand the calculations in the last parameters of ImageLine. They look like the 32 bit r,g,b,alpha (with anti-aliasing flag) values that would be returned from imageColorResolveAlpha.But why wasn't it necessary to call imageColorAllocateAlpha to begin with to establish the colors for the image? Are calls to imageColorAllocateAlpha only needed if overriding some automatic default table?If so, does that hold true for imageColorAllocate and imageColorResolve as well?This book (the O'Reilly book "Programming PHP 2nd Ed" is sure skimpy on details in a lot of places!doug

Link to comment
Share on other sites

The color is just an int, it's a 24-bit number that corresponds to 8 bits for each of red, green, and blue. The << operator is the left shift operator, it ######s the left operand however many bits to the left as the right operand. So $x<<8 shifts $x eight bits to the left. So if $x in binary was 10011011 then after shifting it 8 bits to the left it will be 1001101100000000. Each position to the left is the same as multiplying by 2. So 100 (4) is twice as much as 10 (2), 1000 (8) is twice as much as 100 (4), etc.So since that is in a loop, it will run 256 times to draw 3 lines each time. The first time when $x = 0, the last value for all 3 calls will be 0, you can shift 0 as much as you want and it will still be 0. The next time when $x = 1, the first call uses the value 1 for the color, or basically black (#000001), the next call shifts to the left 8 so it uses 100000000 (#000100), and the last one shifts to the left 16 bits and uses #010000. The last time it runs, when $x = 255 = #FF, the first one uses #0000FF, the second uses #00FF00, and the last uses #FF0000, for blue, green, and red.If you run this:

$im = ImageCreateTrueColor(256,60);$cBlue=ImageColorAllocate($im,0,0,255);var_dump($cBlue);

You'll notice that $cBlue is just an integer, so all imageline needs is a number for the color. Allocating the color does some additional things for images that are palette-based, for example the first time it sets the background color, but for images that don't use a palette you shouldn't need to use it.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...