How can I convert an RGB integer to the corresponding RGB tuple (R,G,B)
? Seems simple enough, but I can't find anything on google.
I know that for every RGB (r,g,b)
you have the integer n = r256^2 + g256 + b
, how can I solve the reverse in Python, IE given an n
, I need the r
,g
,b
values.
If only the
divmod(value, (divider1, divider2, divider3…))
suggestion was accepted, it would have simplified various time conversions too.Just a note for anyone using Google's Appengine Images Python API. I found I had a situation where I had to supply a method with a 32-bit RGB color value.
Specifically, if you're using the API to convert a PNG (or any image with transparent pixels), you'll need to supply the execute_transforms method with an argument called transparent_substitution_rgb which has to be a 32-bit RGB color value.
Borrowing from dbr's answer, I came up with a method similar to this:
This produces the following integer:
You can then unpack it either the long explicit way:
..or in a more compact manner:
Sample applies with any number of digits, e.g an RGBA colour:
If you are using NumPy and you have an array of RGBints, you can also just change its dtype to extract the red, green, blue and alpha components:
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.
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.
There's probably a shorter way of doing this:
EDIT: this is wrong - gives the answer in Hex, OP wanted int. EDIT2: refined to reduce misery and failure - needed '%06x' to ensure hex is always shown as six digits [thanks to Peter Hansen's comment].