2010-08-01 192 views
39

我需要将(0,128,64)转换为像#008040这样的东西。我不确定怎么称呼后者,使搜索变得困难。在Python中将RGB颜色元组转换为六位代码

+0

之前看到这么回答http://stackoverflow.com/questions/214359/converting-hex-to-rgb-and-vice-versa --oF的三个答案中,一个得票最多的包括独立的python代码片段来做我认为你在做的事。 – doug 2010-08-01 04:28:51

+0

您正在寻找的术语是Hex Triplet。 http://en.wikipedia.org/wiki/Hex_color#Hex_triplet – 2010-08-01 04:34:11

回答

79

使用格式运算符%

>>> '#%02x%02x%02x' % (0, 128, 64) 
'#008040' 

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

>>> '#%02x%02x%02x' % (0, -1, 9999) 
'#00-1270f' 
33
def clamp(x): 
    return max(0, min(x, 255)) 

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

这使用字符串格式化的首选方法,因为described in PEP 3101。它还使用min()max来确保0 <= {r,g,b} <= 255

更新添加了钳位功能,如下所示。

更新从问题的标题和给出的上下文中,应该很明显,这需要[0,255]中的3个整数,并且在传递3个这样的整数时总是返回一个颜色。不过,从意见,这未必是有目共睹的,所以让我们来明确指出:

提供了三个int值,这将返回一个表示颜色的有效的十六进制三元组。如果这些值在[0,255]之间,那么它会将这些值视为RGB值并返回与这些值相对应的颜色。

+0

只有一个建议:'def clamp(x):return max(0,min(x,255))' – 2010-08-01 14:55:07

+0

好的建议。谢谢马克,我会更新解决方案。 – 2010-08-01 18:39:10

+0

@Jesse Dhillon:“夹紧”==“默默地失败”。尝试这样:'if not(0 <= x <= 255):raise ValueError('rgb(%r)not in range(256)'%x)' – 2010-08-01 21:40:30

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

这是一个老问题,但对于信息,我开发了相关的颜色和色彩映射一些实用程序包并包含rgb2hex函数,您正在寻找将三元组转换为六元值(可以在很多地方找到它)其他包装,例如matplotlib)。这是PyPI上

pip install colormap 

然后的输入

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

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

6

我已经为它创建了一个完整的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'))) 

你可以看到在下面的链接完整的代码和教程:RGB to Hex and Hex to RGB conversion using Python

0

Python 3中。6,您可以使用F-串使这种清洁:

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) 
0
def RGB(red,green,blue): return '#%02x%02x%02x' % (red,green,blue) 

background = RGB(0, 128, 64) 

我知道在Python单行不nece一丝不苟地看着。但有时候我无法抵抗利用Python解析器所允许的优势。这与Dietrich Epp的解决方案(最好的)的解决方案是一样的,但是包含在一个单行的功能中。所以,谢谢迪特里希!

我现在使用它与Tkinter的:-)

0

这里是在您可能在范围RGB值处理情况比较完善的功能[0,1]或范围[ 0,255]

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