RGB Int to RGB - Python RGB Int to RGB - Python python python

RGB Int to RGB - Python


I'm not a Python expert by all means, but as far as I know it has the same operators as C.

If so this should work and it should also be a lot quicker than using modulo and division.

Blue =  RGBint & 255Green = (RGBint >> 8) & 255Red =   (RGBint >> 16) & 255

What it does it to mask out the lowest byte in each case (the binary and with 255.. Equals to a 8 one bits). For the green and red component it does the same, but shifts the color-channel into the lowest byte first.


From a RGB integer:

Blue =  RGBint mod 256Green = RGBint / 256 mod 256Red =   RGBint / 256 / 256 mod 256

This can be pretty simply implemented once you know how to get it. :)

Upd: Added python function. Not sure if there's a better way to do it, but this works on Python 3 and 2.4

def rgb_int2tuple(rgbint):    return (rgbint // 256 // 256 % 256, rgbint // 256 % 256, rgbint % 256)

There's also an excellent solution that uses bitshifting and masking that's no doubt much faster that Nils Pipenbrinck posted.


>>> import struct>>> str='aabbcc'>>> struct.unpack('BBB',str.decode('hex'))(170, 187, 204)for python3:>>> struct.unpack('BBB', bytes.fromhex(str))

and

>>> rgb = (50,100,150)>>> struct.pack('BBB',*rgb).encode('hex')'326496'for python3:>>> bytes.hex(struct.pack('BBB',*rgb))