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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4296249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:08:01  来源:igfitidea点击:

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

pythoncolors

提问by rectangletangle

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

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

采纳答案by martineau

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

回答by dan_waterworth

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

回答by adamk

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

回答by pyfunc

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

将十六进制转换为 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.

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.

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

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

回答by spacedentist

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

回答by ecik

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'

回答by tsvikas

with matplotlib

使用matplotlib

matplotlib uses RGB tuples with values between 0 and 1:

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

from matplotlib.colors import hex2color, rgb2hex

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

both rgb_colorand hex_colorare in a format acceptable by matplotlib.

二者rgb_colorhex_color处于由格式可接受matplotlib。

with webcolors

webcolors

html uses RGB tuples with values between 0 and 255.

html 使用值在 0 到 255 之间的 RGB 元组。

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

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

回答by Elias Zamaria

I found a simple way:

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

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

回答by Dilawar

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

干得好。我用它的颜色转换成graphviz的色彩格式#RGBA与格式prefix=#

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'

回答by Inti

HEX to RGB tuple

HEX 到 RGB 元组

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

RGB tuple to HEX

RGB 元组到 HEX

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

...

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,b[0] 将是一个整数,而 b[0:1] 将是一个长度为 1 的字节对象

...

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

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

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