我需要将(0, 128, 64)
转换成类似于"#008040"
的格式。我不确定后者应该被称为什么,这使得搜索变得困难。
我需要将(0, 128, 64)
转换成类似于"#008040"
的格式。我不确定后者应该被称为什么,这使得搜索变得困难。
%
:>>> '#%02x%02x%02x' % (0, 128, 64)
'#008040'
请注意它不会检查边界...
>>> '#%02x%02x%02x' % (0, -1, 9999)
'#00-1270f'
'#%x%x%x' % (r, g, b)
。 - wordsforthewisedef clamp(x):
return max(0, min(x, 255))
"#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))
这里使用了Python的首选字符串格式化方法,具体可参考PEP 3101。同时,min()
和max()
函数保证了0 <= {r,g,b} <= 255
。
更新: 根据下面提出的建议,添加了clamp函数。
更新: 根据问题的标题和上下文,很明显这个函数需要传入三个值,且这些值在[0,255]的范围内,才能返回一个颜色。然而,从评论中可以看出,这并不是对每个人都很明显,因此要明确声明:
给定三个
int
值,它将返回一个有效的十六进制表示的颜色。如果这些值在[0,255]之间,则将其视为RGB值,并返回对应的颜色。
我已经创建了一个完整的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')))
您可以在以下链接中查看完整的代码和教程:使用Python进行RGB到十六进制和十六进制到RGB转换
这是一个老问题,但为了提供信息,我开发了一个与颜色和调色板相关的工具包,其中包含您正在寻找的将三元组转换为十六进制值的rgb2hex函数(该函数可以在许多其他软件包中找到,例如matplotlib)。它在pypi上。
pip install colormap
然后
>>> from colormap import rgb2hex
>>> rgb2hex(0, 128, 64)
'##008040'
检查输入的有效性(值必须在0和255之间)。
#
符号? - Sylvester Kruin我真的很惊讶没有人提出这种方法:
适用于Python 2和3:
'#' + ''.join('{:02X}'.format(i) for i in colortuple)
Python 3.6+:
'#' + ''.join(f'{i:02X}' for i in colortuple)
作为一个函数:
def hextriplet(colortuple):
return '#' + ''.join(f'{i:02X}' for i in colortuple)
color = (0, 128, 64)
print(hextriplet(color))
#008040
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)))
你可以使用lambda和f-strings(在Python 3.6+中可用)
rgb2hex = lambda r,g,b: f"#{r:02x}{g:02x}{b:02x}"
hex2rgb = lambda hx: (int(hx[0:2],16),int(hx[2:4],16),int(hx[4:6],16))
使用方法
rgb2hex(r,g,b) #输出 = #十六进制颜色
hex2rgb("#hex") #输出 = (r,g,b) hex颜色必须是#hex格式
这里是一个更完整的函数,用于处理可能在范围[0,1]或[0,255]内具有RGB值的情况。
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))
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)
def rgb2hex(color):
"""Converts a list or tuple of color to an RGB string
Args:
color (list|tuple): the list or tuple of integers (e.g. (127, 127, 127))
Returns:
str: the rgb string
"""
return f"#{''.join(f'{hex(c)[2:].upper():0>2}' for c in color)}"
def rgb2hex(color):
string = '#'
for value in color:
hex_string = hex(value) # e.g. 0x7f
reduced_hex_string = hex_string[2:] # e.g. 7f
capitalized_hex_string = reduced_hex_string.upper() # e.g. 7F
string += capitalized_hex_string # e.g. #7F7F7F
return string