[SOLVED] newbie imagecolorat question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
rubberjohn
Forum Contributor
Posts: 193
Joined: Fri Feb 25, 2005 4:03 am

[SOLVED] newbie imagecolorat question

Post 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
User avatar
n00b Saibot
DevNet Resident
Posts: 1452
Joined: Fri Dec 24, 2004 2:59 am
Location: Lucknow, UP, India
Contact:

Post 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. ;)
rubberjohn
Forum Contributor
Posts: 193
Joined: Fri Feb 25, 2005 4:03 am

Post by rubberjohn »

ah ok so why are they needed in this function?

Sorry if these are obvious questions.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post 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.
rubberjohn
Forum Contributor
Posts: 193
Joined: Fri Feb 25, 2005 4:03 am

Post by rubberjohn »

Thanks a lot thats really cleared that up for me
Post Reply