Converting a RGB color tuple to a six digit code
Solution 1
Use the format operator %
:
>>> '#%02x%02x%02x' % (0, 128, 64)
'#008040'
Note that it won't check bounds...
>>> '#%02x%02x%02x' % (0, -1, 9999)
'#00-1270f'
Solution 2
def clamp(x):
return max(0, min(x, 255))
"#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))
This uses the preferred method of string formatting, as described in PEP 3101. It also uses min()
and max
to ensure that 0 <= {r,g,b} <= 255
.
Update added the clamp function as suggested below.
Update From the title of the question and the context given, it should be obvious that this expects 3 ints in [0,255] and will always return a color when passed 3 such ints. However, from the comments, this may not be obvious to everyone, so let it be explicitly stated:
Provided three
int
values, this will return a valid hex triplet representing a color. If those values are between [0,255], then it will treat those as RGB values and return the color corresponding to those values.
Solution 3
This is an old question but for information, I developed a package with some utilities related to colors and colormaps and contains the rgb2hex function you were looking to convert triplet into hexa value (which can be found in many other packages, e.g. matplotlib). It's on pypi
pip install colormap
and then
>>> from colormap import rgb2hex
>>> rgb2hex(0, 128, 64)
'##008040'
Validity of the inputs is checked (values must be between 0 and 255).
Solution 4
I have created a full python program for it the following functions can convert rgb to hex and vice versa.
def rgb2hex(r,g,b):
return "#{:02x}{:02x}{:02x}".format(r,g,b)
def hex2rgb(hexcode):
return tuple(map(ord,hexcode[1:].decode('hex')))
You can see the full code and tutorial at the following link : RGB to Hex and Hex to RGB conversion using Python
Solution 5
I'm truly surprised no one suggested this approach:
For Python 2 and 3:
'#' + ''.join('{:02X}'.format(i) for i in colortuple)
Python 3.6+:
'#' + ''.join(f'{i:02X}' for i in colortuple)
As a function:
def hextriplet(colortuple):
return '#' + ''.join(f'{i:02X}' for i in colortuple)
color = (0, 128, 64)
print(hextriplet(color))
#008040
rectangletangle
Updated on May 18, 2021Comments
-
rectangletangle almost 3 years
I need to convert
(0, 128, 64)
to something like this"#008040"
. I'm not sure what to call the latter, making searching difficult. -
Lars Ericson almost 6 yearsThis function rgb2hex, applied to (13,13,12), gives 0xDDC, but the website RGB to HEX gives it as 0x0D0D0C, and this also concurs with the idea tha tthe number should be 13*65536+13*256+12, and 0xDDC is read by Python as 3548.
-
Brian Bruggeman almost 6 yearsCSS Colors are inconsistent. There are 6-digit hex colors, 3-digit hex colors, rgb notation with decimals and percentages, hsl, etc. I've tweaked the formula to always provide 6 digits hex colors, and though I think it may be more consistent, I'm not sure it's more correct.
-
Abhils about 5 yearsI tried to use rgb2hex but got an error "ImportError: No module named easydev.tools". Can you suggest any solution to it ?
-
Abhils about 5 yearsIt does not work for decimal value of rgb. Can you suggest me any solution to it ?
-
Mike from PSG almost 5 yearsCalling lambda's directly is not recommended for a host of reasons. I used them like this on a project that was reviewed and everyone said the same thing, not to call directly.
-
wordsforthewise about 4 yearsIs the 2-digit limit really necessary though? As long as the RGB values are in the proper bounds of 0-255, you shouldn't need it. So you could just do
'#%x%x%x' % (r, g, b)
-
wordsforthewise about 4 yearsActually now I see that if you have a value of 0, it needs to be padded with another 0. Thus the 02 to make it two digits.
-
Shounak Ray over 3 yearsTry reinstalling easydev. Then 'pip3 install easydev'.
-
Shounak Ray over 3 yearsRound. There shouldn't be a huge difference in the final color.
-
Sunghee Yun over 3 yearsThis is awesome! Truly generic function. Thx, Richard!
-
Sylvester Kruin about 2 yearsWhy does it output two
#
s? -
S3DEV about 2 yearsThis is great, for the exception it does not work if the R or G channels are 0, as the
hex()
function drops leading zero bits.