Python 如何将十六进制三元组转换为RGB元组并返回?

Python 如何将十六进制三元组转换为RGB元组并返回?,python,colors,Python,Colors,我想将十六进制三元组转换为RGB元组,然后将元组转换为十六进制三元组 def hex_to_int_color(v): if v[0] == '#': v = v[1:] assert(len(v) == 6) return int(v[:2], 16), int(v[2:4], 16), int(v[4:6], 16) def int_to_hex_color(v): assert(len(v) == 3) return '#%02x%

我想将十六进制三元组转换为RGB元组,然后将元组转换为十六进制三元组

def hex_to_int_color(v):
    if v[0] == '#':
        v = v[1:]
    assert(len(v) == 6)
    return int(v[:2], 16), int(v[2:4], 16), int(v[4:6], 16)

def int_to_hex_color(v):
    assert(len(v) == 3)
    return '#%02x%02x%02x' % v


将rgb转换为十六进制的非常简单的方法

>>> rgb = (255, 255, 255)
>>> r, g , b = rgb
>>> hex(r)
'0xff'
>>> hex(r) + hex(g)[2:] + hex(b)[2:]
'0xffffff'
>>>
将十六进制转换为rgb的简化方法

>>> h  = '0xffffff'
>>> h1, h2, h3 = h[0:4], '0x' + h[4:6], '0x' + h[6:8]
>>> h1, h2, h3
('0xff', '0xff', '0xff')
>>> r, g , b = int(h1, 16), int(h2, 16), int(h3, 16)
>>> r, g, b
(255, 255, 255)
使用提供以下功能的模块:

功能文档:

十六进制至十六进制rgb(十六进制值) 将十六进制颜色值转换为适合在指定该颜色的rgb()三元组中使用的3元组整数

rgb_至_十六进制(rgb_三元组): 将适用于rgb()颜色三元组的3元组整数转换为该颜色的标准化十六进制值


您可以使用带有一些切片和移位(都是相对快速的操作)的查找表来创建两个在Python 2和Python 3中都能正常工作的函数:

_NUMERALS = '0123456789abcdefABCDEF'
_HEXDEC = {v: int(v, 16) for v in (x+y for x in _NUMERALS for y in _NUMERALS)}
LOWERCASE, UPPERCASE = 'x', 'X'

def rgb(triplet):
    return _HEXDEC[triplet[0:2]], _HEXDEC[triplet[2:4]], _HEXDEC[triplet[4:6]]

def triplet(rgb, lettercase=LOWERCASE):
    return format(rgb[0]<<16 | rgb[1]<<8 | rgb[2], '06'+lettercase)

if __name__ == '__main__':
    print('{}, {}'.format(rgb('aabbcc'), rgb('AABBCC')))
    # -> (170, 187, 204), (170, 187, 204)

    print('{}, {}'.format(triplet((170, 187, 204)),
                          triplet((170, 187, 204), UPPERCASE)))
    # -> aabbcc, AABBCC

    print('{}, {}'.format(rgb('aa0200'), rgb('AA0200')))
    # -> (170, 2, 0), (170, 2, 0)

    print('{}, {}'.format(triplet((170, 2, 0)),
                          triplet((170, 2, 0), UPPERCASE)))
    # -> aa0200, AA0200
\u数字='0123456789abcdefabcddef'
_HEXDEC={v:int(v,16)表示v in(x+y表示x in_数字表示y in_数字)}
小写,大写='x','x'
def rgb(三线组):
返回HEXDEC[triplet[0:2]]、HEXDEC[triplet[2:4]]、HEXDEC[triplet[4:6]]
def三元组(rgb,小写):
返回格式(rgb[0]aa0200,aa0200)
尝试成为pythonic:

具有 matplotlib使用值介于0和1之间的RGB元组:

from matplotlib.colors import hex2color, rgb2hex

hex_color = '#00ff00'
rgb_color = hex2color(hex_color)
hex_color_again = rgb2hex(rgb_color)
rgb_color
hex_color
均采用matplotlib可接受的格式

具有 html使用值介于0和255之间的RGB元组

您可以使用模块WebColor在它们之间进行转换,使用函数
hex\u to\u rgb
rgb\u to\u hex
我找到了一个简单的方法:

red, green, blue = bytes.fromhex("aabbcc")

给你。我用它将颜色转换为
\RGBA
格式的graphviz颜色格式,并带有
前缀=

用法:

In [3]: rgba_hex( (222, 100, 34) )
Out[3]: '0xde6422ff'

In [4]: rgba_hex( (0,255,255) )
Out[4]: '0x00ffffff'

In [5]: rgba_hex( (0,255,255,0) )
Out[5]: '0x00ffff00'
十六进制到RGB元组

>>> tuple(bytes.fromhex('61559a'))
(97, 85, 154)
RGB元组到十六进制

>>> bytes((97, 85, 154)).hex()
'61559a'
不需要进口


这是什么魔法

由于bytes对象是整数序列(类似于元组),因此 字节对象b,b[0]将是一个整数,而b[0:1]将是一个字节 长度为1的对象

字节对象的表示使用文字格式(b'…') 因为它通常比字节([46,46,46])更有用。您可以 始终使用列表(b)将字节对象转换为整数列表


来源:

可能的重复:请参阅Python 3,您希望@Inti-clean,fast,no-import,no-install获得基于
字节的答案。在Python 3.0中,将
str.decode('hex')
替换为
bytes.fromhex(str)
。对于另一个方向,使用
binascii.hexlify
在打包后转换回字符串。在Python 2.7中
str
是内置类型的名称。在许多早期版本中也是如此,我只是不记得它是在什么时候引入的。无论如何,关键是,给一个变量命名通常不是一个好的p因为它隐藏了类型。这仍然是一个很好的答案,IMHO。将其转换为Python 3.x有点棘手——特别是(令人惊讶的)在第二部分中转换为十六进制三元组。如果我没有弄错的话,
binascii.hexlify
生成一个bytes对象。您需要调用
.decode('utf-8'))
获取字符串,对吗?total命令是
binascii.hexlify(struct.pack('BBB',*rgb)).decode('utf-8')
。我认为
'#%02x%02x%02x'%rgb
简单得多,并且有处理浮点值和整数的好处。def int_to_hex_color(v):assert(len(v)==3)返回“#%02x%02x%02x”%v对不起,当某些颜色分量的值小于16时,您的int-to-hex颜色不会返回正确的结果。int-to-hex-color((30,20,10))->”#1e14a'尝试使用三元组(170,2,0)进行测试。请注意,如果任何输入值小于16,则rgb-to-hex将失败。例如,
rgb=(0,255,0)
将导致
“0x0ff0”
rgbstr.decode('hex')
python3的情况如何?这是最简单的解决方案,甚至不需要导入任何模块。
bytearray.fromhex()
对于python 2.7来说,这不仅简单,而且比使用struct更快。如果您返回tuple而不是list,则更是如此。
>>> rgb=(12,50,100)
>>> "".join(map(chr, rgb)).encode('hex')
'0c3264'
from matplotlib.colors import hex2color, rgb2hex

hex_color = '#00ff00'
rgb_color = hex2color(hex_color)
hex_color_again = rgb2hex(rgb_color)
red, green, blue = bytes.fromhex("aabbcc")
def rgba_hex( color, prefix = '0x' ):
    if len( color ) == 3:
       color = color + (255,)
    hexColor = prefix + ''.join( [ '%02x' % x for x in color ] )
    return hexColor
In [3]: rgba_hex( (222, 100, 34) )
Out[3]: '0xde6422ff'

In [4]: rgba_hex( (0,255,255) )
Out[4]: '0x00ffffff'

In [5]: rgba_hex( (0,255,255,0) )
Out[5]: '0x00ffff00'
>>> tuple(bytes.fromhex('61559a'))
(97, 85, 154)
>>> bytes((97, 85, 154)).hex()
'61559a'