Page 1 of 1

[SOLVED] newbie imagecolorat question

Posted: Fri Feb 25, 2005 4:09 am
by rubberjohn
Im using the following code from php.net:

Code: Select all

$rgb = imagecolorat($im, $x, $y);
$r = ($rgb >> 16);
$g = ($rgb >>  & 255;
$b = $rgb & 255;
while i have got it to work I dont fully understand what is going on here. What does the '>>16', '>>8)&255' and '&255' sections of the code mean and what do they do?

Thanks

Posted: Fri Feb 25, 2005 4:26 am
by n00b Saibot
>> is the right shift operator which shifts the bits rightwards
& is the AND operator which which performs AND operation on the operand number's bits.
See Bitwise Operators for more details. ;)

Posted: Fri Feb 25, 2005 4:37 am
by rubberjohn
ah ok so why are they needed in this function?

Sorry if these are obvious questions.

Posted: Fri Feb 25, 2005 6:27 am
by onion2k
rubberjohn wrote:ah ok so why are they needed in this function?

Sorry if these are obvious questions.
Basically, imagecolorat returns a really big number.. what these operators do is get parts of that number..

Imagine your colour is bright red. Thats FF0000 in hex, or 111111110000000000000000 in binary, or 16711680 in decimal. Using $r = ($rgb >> 16) & 255; means you 'discard' the last 16 bits, and only use the first 8 bits. Using $g = ($rgb >> 8) & 255; means you discard the last 8 bits, and only use the next 8. $b = $rgb & 255; means you only use the first 8 bits.

Note, if you're using PNG files instead of JPG files, you can also use $a = ($rgb >> 24); to get the alpha channel information.

Posted: Fri Feb 25, 2005 7:14 am
by rubberjohn
Thanks a lot thats really cleared that up for me