Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a hex triplet to an RGB tuple and back?

Tags:

python

colors

I'd like to convert a hex triplet to an RGB tuple and then convert a tuple to a hex triplet.

like image 393
rectangletangle Avatar asked Nov 28 '10 09:11

rectangletangle


People also ask

What is hex in RGB?

A HEX color is expressed as a six-digit combination of numbers and letters defined by its mix of red, green and blue (RGB). Basically, a HEX color code is shorthand for its RGB values with a little conversion gymnastics in between. No need to sweat the conversion.

How do I use hex codes in Python?

Python hex() function is used to convert an integer to a lowercase hexadecimal string prefixed with “0x”. We can also pass an object to hex() function, in that case the object must have __index__() function defined that returns integer. The input integer argument can be in any base such as binary, octal etc.


2 Answers

>>> import struct >>> rgbstr='aabbcc' >>> struct.unpack('BBB',rgbstr.decode('hex')) (170, 187, 204) 

and

>>> rgb = (50,100,150) >>> struct.pack('BBB',*rgb).encode('hex') '326496' 
like image 58
adamk Avatar answered Sep 21 '22 01:09

adamk


Trying to be pythonic:

>>> rgbstr='aabbcc' >>> tuple(ord(c) for c in rgbstr.decode('hex')) (170, 187, 204) >>> tuple(map(ord, rgbstr.decode('hex')) (170, 187, 204) 

and

>>> rgb=(12,50,100) >>> "".join(map(chr, rgb)).encode('hex') '0c3264' 
like image 26
ecik Avatar answered Sep 23 '22 01:09

ecik