2010-08-01 56 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))