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

时间:2021-03-25 00:32:50

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

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

11 个解决方案

#1


17  

You can use a look-up table with some slicing and shifts — all relatively fast operations — to create a couple of functions that will work unchanged in both Python 2 and 3:

您可以使用具有一些切片和移位的查找表 - 所有相对快速的操作 - 来创建一些在Python 2和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

#2


69  

>>> 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'

#3


25  

Trying to be pythonic:

试图成为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'

#4


14  

I found a simple way:

我找到了一个简单的方法:

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

#5


10  

with matplotlib

matplotlib uses RGB tuples with values between 0 and 1:

matplotlib使用RGB元组,其值介于0和1之间:

from matplotlib.colors import hex2color, rgb2hex

hex_color = '#00ff00'
rgb_color = hex2color(hex_color)
hex_color_again = rgb2hex(rgb_color)

both rgb_color and hex_color are in a format acceptable by matplotlib.

rgb_color和hex_color都采用matplotlib可接受的格式。

with webcolors

html uses RGB tuples with values between 0 and 255.

html使用RGB元组,其值介于0到255之间。

you can convert between them with the module webcolors, using the functions hex_to_rgb, rgb_to_hex

您可以使用模块webcolors在它们之间进行转换,使用函数hex_to_rgb,rgb_to_hex

#6


9  

A very simplistic approach to convert rgb to hex

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

>>> rgb = (255, 255, 255)
>>> r, g , b = rgb
>>> hex(r)
'0xff'
>>> hex(r) + hex(g)[2:] + hex(b)[2:]
'0xffffff'
>>>

A simplistic approach to convert Hex to rgb

将Hex转换为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)

Use a module which provides some these facility: webcolors

使用提供这些功能的模块:webcolors

>>> hex_to_rgb('#000080')
(0, 0, 128)
>>> rgb_to_hex((255, 255, 255))
'#ffffff'

Function doc:

hex_to_rgb(hex_value) Convert a hexadecimal color value to a 3-tuple of integers suitable for use in an rgb() triplet specifying that color.

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

rgb_to_hex(rgb_triplet) : Convert a 3-tuple of integers, suitable for use in an rgb() color triplet, to a normalized hexadecimal value for that color.

rgb_to_hex(rgb_triplet):将适合在rgb()颜色三元组中使用的3元组整数转换为该颜色的标准化十六进制值。

#7


5  

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

#8


1  

import re

def hex_to_int_color(v):
  return tuple(int(i,16) for i in re.match(
    r'^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$', v,
    flags=re.IGNORECASE).groups())

def int_to_hex_color(v):
  return '#%02x%02x%02x' % v

#9


1  

Here you go. I use it to convert color to graphviz color format in #RGBA format with prefix=#.

干得好。我使用它将颜色转换为#RGBA格式的graphviz颜色格式,前缀=#。

def rgba_hex( color, prefix = '0x' ):
    if len( color ) == 3:
       color = color + (255,)
    hexColor = prefix + ''.join( [ '%02x' % x for x in color ] )
    return hexColor

USAGE:

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'

#10


0  

See https://*.com/a/214657/3787376 for really simple functions to do these converting jobs without requiring any third party modules or long/fancy code. I checked them and they work.
Here is the code below if you don't want to follow the link. Thanks to user Jeremy Cantrell for it:

有关真正简单的功能,请参阅https://*.com/a/214657/3787376,无需任何第三方模块或长/花式代码即可完成这些转换作业。我检查过他们的工作。如果您不想关注此链接,请参阅下面的代码。感谢用户Jeremy Cantrell:

def hex_to_rgb(value):
    value = value.lstrip('#')
    lv = len(value)
    return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))

def rgb_to_hex(rgb):
    return '#%02x%02x%02x' % rgb

hex_to_rgb("#ffffff")             #==> (255, 255, 255)
hex_to_rgb("#ffffffffffff")       #==> (65535, 65535, 65535)
rgb_to_hex((255, 255, 255))       #==> '#ffffff'
rgb_to_hex((65535, 65535, 65535)) #==> '#ffffffffffff'

#11


0  

HEX to RGB tuple

HEX到RGB元组

>>> tuple(bytes.fromhex('61559a'))
(97, 85, 154)

RGB tuple to HEX

RGB元组到十六进制

>>> bytes((97, 85, 154)).hex()
'61559a'

No imports needed!

不需要进口!


What is this magic?!

这个魔法是什么?!

Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b, b[0] will be an integer, while b[0:1] will be a bytes object of length 1

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

...

The representation of bytes objects uses the literal format (b'...') since it is often more useful than e.g. bytes([46, 46, 46]). You can always convert a bytes object into a list of integers using list(b).

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

Source: https://docs.python.org/3/library/stdtypes.html#bytes-objects

#1


17  

You can use a look-up table with some slicing and shifts — all relatively fast operations — to create a couple of functions that will work unchanged in both Python 2 and 3:

您可以使用具有一些切片和移位的查找表 - 所有相对快速的操作 - 来创建一些在Python 2和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

#2


69  

>>> 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'

#3


25  

Trying to be pythonic:

试图成为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'

#4


14  

I found a simple way:

我找到了一个简单的方法:

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

#5


10  

with matplotlib

matplotlib uses RGB tuples with values between 0 and 1:

matplotlib使用RGB元组,其值介于0和1之间:

from matplotlib.colors import hex2color, rgb2hex

hex_color = '#00ff00'
rgb_color = hex2color(hex_color)
hex_color_again = rgb2hex(rgb_color)

both rgb_color and hex_color are in a format acceptable by matplotlib.

rgb_color和hex_color都采用matplotlib可接受的格式。

with webcolors

html uses RGB tuples with values between 0 and 255.

html使用RGB元组,其值介于0到255之间。

you can convert between them with the module webcolors, using the functions hex_to_rgb, rgb_to_hex

您可以使用模块webcolors在它们之间进行转换,使用函数hex_to_rgb,rgb_to_hex

#6


9  

A very simplistic approach to convert rgb to hex

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

>>> rgb = (255, 255, 255)
>>> r, g , b = rgb
>>> hex(r)
'0xff'
>>> hex(r) + hex(g)[2:] + hex(b)[2:]
'0xffffff'
>>>

A simplistic approach to convert Hex to rgb

将Hex转换为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)

Use a module which provides some these facility: webcolors

使用提供这些功能的模块:webcolors

>>> hex_to_rgb('#000080')
(0, 0, 128)
>>> rgb_to_hex((255, 255, 255))
'#ffffff'

Function doc:

hex_to_rgb(hex_value) Convert a hexadecimal color value to a 3-tuple of integers suitable for use in an rgb() triplet specifying that color.

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

rgb_to_hex(rgb_triplet) : Convert a 3-tuple of integers, suitable for use in an rgb() color triplet, to a normalized hexadecimal value for that color.

rgb_to_hex(rgb_triplet):将适合在rgb()颜色三元组中使用的3元组整数转换为该颜色的标准化十六进制值。

#7


5  

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

#8


1  

import re

def hex_to_int_color(v):
  return tuple(int(i,16) for i in re.match(
    r'^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$', v,
    flags=re.IGNORECASE).groups())

def int_to_hex_color(v):
  return '#%02x%02x%02x' % v

#9


1  

Here you go. I use it to convert color to graphviz color format in #RGBA format with prefix=#.

干得好。我使用它将颜色转换为#RGBA格式的graphviz颜色格式,前缀=#。

def rgba_hex( color, prefix = '0x' ):
    if len( color ) == 3:
       color = color + (255,)
    hexColor = prefix + ''.join( [ '%02x' % x for x in color ] )
    return hexColor

USAGE:

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'

#10


0  

See https://*.com/a/214657/3787376 for really simple functions to do these converting jobs without requiring any third party modules or long/fancy code. I checked them and they work.
Here is the code below if you don't want to follow the link. Thanks to user Jeremy Cantrell for it:

有关真正简单的功能,请参阅https://*.com/a/214657/3787376,无需任何第三方模块或长/花式代码即可完成这些转换作业。我检查过他们的工作。如果您不想关注此链接,请参阅下面的代码。感谢用户Jeremy Cantrell:

def hex_to_rgb(value):
    value = value.lstrip('#')
    lv = len(value)
    return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))

def rgb_to_hex(rgb):
    return '#%02x%02x%02x' % rgb

hex_to_rgb("#ffffff")             #==> (255, 255, 255)
hex_to_rgb("#ffffffffffff")       #==> (65535, 65535, 65535)
rgb_to_hex((255, 255, 255))       #==> '#ffffff'
rgb_to_hex((65535, 65535, 65535)) #==> '#ffffffffffff'

#11


0  

HEX to RGB tuple

HEX到RGB元组

>>> tuple(bytes.fromhex('61559a'))
(97, 85, 154)

RGB tuple to HEX

RGB元组到十六进制

>>> bytes((97, 85, 154)).hex()
'61559a'

No imports needed!

不需要进口!


What is this magic?!

这个魔法是什么?!

Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b, b[0] will be an integer, while b[0:1] will be a bytes object of length 1

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

...

The representation of bytes objects uses the literal format (b'...') since it is often more useful than e.g. bytes([46, 46, 46]). You can always convert a bytes object into a list of integers using list(b).

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

Source: https://docs.python.org/3/library/stdtypes.html#bytes-objects