将一个RGB颜色元组转换为十六进制字符串

154

我需要将(0, 128, 64)转换成类似于"#008040"的格式。我不确定后者应该被称为什么,这使得搜索变得困难。


1
请参考之前的SO回答https://dev59.com/dXVC5IYBdhLWcg3wsTRi -- 在三个答案中,投票最多的那个包含了一个独立的Python代码片段,可以完成我认为你想要的功能。 - doug
3
您要找的术语是“Hex Triplet”(十六进制三元组)。详细信息请参见http://en.wikipedia.org/wiki/Hex_color#Hex_triplet。 - Mark Ransom
对于一个更一般的问题,这里有比这个回答更好的答案:https://dev59.com/yW035IYBdhLWcg3wC7YR#57197866 - MestreLion
17个回答

267
使用格式运算符 %
>>> '#%02x%02x%02x' % (0, 128, 64)
'#008040'

请注意它不会检查边界...

>>> '#%02x%02x%02x' % (0, -1, 9999)
'#00-1270f'

然而,真的需要限制在两位数吗?只要RGB值在0-255的正确范围内,就不需要它。所以你可以只写'#%x%x%x' % (r, g, b) - wordsforthewise
9
现在我明白了,如果一个值为0,则需要用另一个0进行填充。因此需要加上02以使其成为两位数。 - wordsforthewise

69
def clamp(x): 
  return max(0, min(x, 255))

"#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))

这里使用了Python的首选字符串格式化方法,具体可参考PEP 3101。同时,min()max()函数保证了0 <= {r,g,b} <= 255

更新: 根据下面提出的建议,添加了clamp函数。

更新: 根据问题的标题和上下文,很明显这个函数需要传入三个值,且这些值在[0,255]的范围内,才能返回一个颜色。然而,从评论中可以看出,这并不是对每个人都很明显,因此要明确声明:

给定三个int值,它将返回一个有效的十六进制表示的颜色。如果这些值在[0,255]之间,则将其视为RGB值,并返回对应的颜色。


25

我已经创建了一个完整的Python程序,以下函数可以将RGB转换为十六进制,反之亦然。

def rgb2hex(r,g,b):
    return "#{:02x}{:02x}{:02x}".format(r,g,b)

def hex2rgb(hexcode):
    return tuple(map(ord,hexcode[1:].decode('hex')))

您可以在以下链接中查看完整的代码和教程:使用Python进行RGB到十六进制和十六进制到RGB转换


它不能处理RGB的十进制值。你能给我提供任何解决方案吗? - Abhils
2
圆形。最终颜色不应该有太大的差异。 - Shounak Ray

23

这是一个老问题,但为了提供信息,我开发了一个与颜色和调色板相关的工具包,其中包含您正在寻找的将三元组转换为十六进制值的rgb2hex函数(该函数可以在许多其他软件包中找到,例如matplotlib)。它在pypi上。

pip install colormap

然后

>>> from colormap import rgb2hex
>>> rgb2hex(0, 128, 64)
'##008040'

检查输入的有效性(值必须在0和255之间)。


4
我尝试使用rgb2hex,但出现了一个错误:“ImportError: No module named easydev.tools”。你有什么解决方法吗? - Abhils
尝试重新安装easydev。然后执行'pip3 install easydev'。 - Shounak Ray
为什么它会输出 两个 # 符号? - Sylvester Kruin

13

我真的很惊讶没有人提出这种方法:

适用于Python 2和3:

'#' + ''.join('{:02X}'.format(i) for i in colortuple)

Python 3.6+:

'#' + ''.join(f'{i:02X}' for i in colortuple)

作为一个函数:

def hextriplet(colortuple):
    return '#' + ''.join(f'{i:02X}' for i in colortuple)

color = (0, 128, 64)
print(hextriplet(color))
#008040

10
triplet = (0, 128, 64)
print '#'+''.join(map(chr, triplet)).encode('hex')
或者
from struct import pack
print '#'+pack("BBB",*triplet).encode('hex')

Python3 稍有不同。

from base64 import b16encode
print(b'#'+b16encode(bytes(triplet)))

7

你可以使用lambda和f-strings(在Python 3.6+中可用)

rgb2hex = lambda r,g,b: f"#{r:02x}{g:02x}{b:02x}"
hex2rgb = lambda hx: (int(hx[0:2],16),int(hx[2:4],16),int(hx[4:6],16))

使用方法

rgb2hex(r,g,b) #输出 = #十六进制颜色 hex2rgb("#hex") #输出 = (r,g,b) hex颜色必须是#hex格式


1
直接调用lambda表达式是不推荐的,有很多原因。我在一个项目中使用了它们,但被审查后大家都说不要直接调用。 - Mike from PSG

5

这里是一个更完整的函数,用于处理可能在范围[0,1][0,255]内具有RGB值的情况。

def RGBtoHex(vals, rgbtype=1):
  """Converts RGB values in a variety of formats to Hex values.

     @param  vals     An RGB/RGBA tuple
     @param  rgbtype  Valid valus are:
                          1 - Inputs are in the range 0 to 1
                        256 - Inputs are in the range 0 to 255

     @return A hex string in the form '#RRGGBB' or '#RRGGBBAA'
"""

  if len(vals)!=3 and len(vals)!=4:
    raise Exception("RGB or RGBA inputs to RGBtoHex must have three or four elements!")
  if rgbtype!=1 and rgbtype!=256:
    raise Exception("rgbtype must be 1 or 256!")

  #Convert from 0-1 RGB/RGBA to 0-255 RGB/RGBA
  if rgbtype==1:
    vals = [255*x for x in vals]

  #Ensure values are rounded integers, convert to hex, and concatenate
  return '#' + ''.join(['{:02X}'.format(int(round(x))) for x in vals])

print(RGBtoHex((0.1,0.3,  1)))
print(RGBtoHex((0.8,0.5,  0)))
print(RGBtoHex((  3, 20,147), rgbtype=256))
print(RGBtoHex((  3, 20,147,43), rgbtype=256))

太棒了!这个函数真的很通用。谢谢,Richard! - Sunghee Yun

5
在Python 3.6中,您可以使用f-strings使代码更加简洁:
rgb = (0,128, 64)
f'#{rgb[0]:02x}{rgb[1]:02x}{rgb[2]:02x}'

当然可以将这个内容放入一个函数中,并且作为奖励,值会被四舍五入并转换成整数
def rgb2hex(r,g,b):
    return f'#{int(round(r)):02x}{int(round(g)):02x}{int(round(b)):02x}'

rgb2hex(*rgb)

4
请注意,这仅适用于Python 3.6及以上版本。
def rgb2hex(color):
    """Converts a list or tuple of color to an RGB string

    Args:
        color (list|tuple): the list or tuple of integers (e.g. (127, 127, 127))

    Returns:
        str:  the rgb string
    """
    return f"#{''.join(f'{hex(c)[2:].upper():0>2}' for c in color)}"

以上代码的含义是:
def rgb2hex(color):
    string = '#'
    for value in color:
       hex_string = hex(value)  #  e.g. 0x7f
       reduced_hex_string = hex_string[2:]  # e.g. 7f
       capitalized_hex_string = reduced_hex_string.upper()  # e.g. 7F
       string += capitalized_hex_string  # e.g. #7F7F7F
    return string

函数rgb2hex应用于(13,13,12)的结果为0xDDC,但网站RGB to HEX将其作为0x0D0D0C给出,并且这也与数字应为13 * 65536 + 13 * 256 + 12的想法相符,而0xDDC被Python解释为3548。 - Lars Ericson
CSS颜色不一致。有6位十六进制颜色、3位十六进制颜色、带小数和百分比的RGB表示法、HSL等。我已经调整了公式,始终提供6位十六进制颜色,虽然我认为它可能更一致,但我不确定它是否更正确。 - Brian Bruggeman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接