我需要将
(0, 128, 64)
转换为这样的 "#008040"
。我不知道如何称呼后者,这使得搜索变得困难。
使用格式运算符
%
:
>>> '#%02x%02x%02x' % (0, 128, 64)
'#008040'
请注意,它不会检查边界...
>>> '#%02x%02x%02x' % (0, -1, 9999)
'#00-1270f'
def clamp(x):
return max(0, min(x, 255))
"#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))
这使用首选的字符串格式化方法,如 PEP 3101 中所述。它还使用
min()
和 max
来确保 0 <= {r,g,b} <= 255
。
更新添加了钳位功能,如下所示。
更新 从问题的标题和给出的上下文来看,很明显,这需要 [0,255] 中的 3 个整数,并且当传递 3 个这样的整数时,总是返回一个颜色。然而,从评论来看,这可能对每个人来说都不是显而易见的,所以明确说明一下:
提供了三个
值,这将返回一个表示颜色的有效十六进制三元组。如果这些值在 [0,255] 之间,那么它将把它们视为 RGB 值并返回与这些值相对应的颜色。int
我已经为它创建了一个完整的Python程序,以下函数可以将rgb转换为hex,反之亦然。
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 之间)。
我真的很惊讶没有人建议这种方法:
对于 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 字符串(在 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) #output = #hexcolor
hex2rgb("#hex") #output = (r,g,b) hexcolor must be in #hex format
在 Python 3.6 中,您可以使用 f-strings 使其更清晰:
rgb = (0,128, 64)
f'#{rgb[0]:02x}{rgb[1]:02x}{rgb[2]:02x}'
当然,您可以将其放入函数中,并且作为奖励,值会四舍五入并转换为int:
def rgb2hex(r,g,b):
return f'#{int(round(r)):02x}{int(round(g)):02x}{int(round(b)):02x}'
rgb2hex(*rgb)
这是一个更完整的函数,用于处理 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))
请注意,这只适用于 python3.6 及以上版本。
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
您还可以使用非常高效的按位运算符,尽管我怀疑您会担心这样的操作的效率。也比较干净。请注意,它不会限制或检查边界。至少从 Python 2.7.17 开始就支持此功能。
hex(r << 16 | g << 8 | b)
要更改它,使其以 # 开头,您可以这样做:
"#" + hex(243 << 16 | 103 << 8 | 67)[2:]
def RGB(red,green,blue): return '#%02x%02x%02x' % (red,green,blue)
background = RGB(0, 128, 64)
我知道 Python 中的俏皮话并不一定会受到友善的对待。但有时我会忍不住利用 Python 解析器所允许的功能。它与 Dietrich Epp 的解决方案(最好的)答案相同,但包含在单行函数中。所以,谢谢迪特里希!
我现在正在使用 tkinter :-)
有一个名为 webcolors 的包。 https://github.com/ubernostrum/webcolors
它有一个方法
webcolors.rgb_to_hex
>>> import webcolors
>>> webcolors.rgb_to_hex((12,232,23))
'#0ce817'
如果输入格式化字符串三次次似乎有点冗长......
位移位和 f 字符串的组合可以很好地完成这项工作:
# Example setup.
>>> r, g, b = 0, 0, 195
# Create the hex string.
>>> f'#{r << 16 | g << 8 | b:06x}'
'#0000c3'
这也说明了一种方法,如果红色或绿色通道为零,则不会丢弃“前导”零位。
''.join('%02x'%i for i in input)
可用于从 int 数字进行十六进制转换
我的课程任务需要在不使用 for 循环和其他东西的情况下完成此操作,这是我奇怪的解决方案,哈哈。
color1 = int(input())
color2 = int(input())
color3 = int(input())
color1 = hex(color1).upper()
color2 = hex(color2).upper()
color3 = hex(color3).upper()
print('#'+ color1[2:].zfill(2)+color2[2:].zfill(2)+color3[2:].zfill(2))
对于所有简单的颜色转换,matplotlib 提供了一个模块,其中有很多功能,其中:
你只需要正常化即可。对于你的情况:
from matplotlib.colors import to_hex
t = (0, 128, 64)
to_hex(tuple(v/255. for v in t)) # returns '#008040'