将 RGB 颜色元组转换为十六进制字符串
- 2025-03-13 08:58:00
- admin 原创
- 70
问题描述:
我需要将其转换(0, 128, 64)
为类似这样的内容"#008040"
。我不确定后者该怎么称呼,这使得搜索变得困难。
解决方案 1:
使用格式运算符%
:
>>> '#%02x%02x%02x' % (0, 128, 64)
'#008040'
请注意,它不会检查边界......
>>> '#%02x%02x%02x' % (0, -1, 9999)
'#00-1270f'
解决方案 2:
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 个这样的整数时将始终返回颜色。但是,从评论来看,这可能并不是每个人都清楚的,所以让我们明确说明:
提供三个
int
值,这将返回表示颜色的有效十六进制三元组。如果这些值介于 [0,255] 之间,则它会将它们视为 RGB 值并返回与这些值相对应的颜色。
解决方案 3:
我已经为其创建了一个完整的 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 到 Hex 和 Hex 到 RGB 的转换
解决方案 4:
这是一个老问题,但为了便于参考,我开发了一个包,其中包含一些与颜色和颜色图相关的实用程序,并包含您正在寻找的将三元组转换为六元组的 rgb2hex 函数(可以在许多其他包中找到,例如 matplotlib)。它在 pypi 上
pip install colormap
进而
>>> from colormap import rgb2hex
>>> rgb2hex(0, 128, 64)
'##008040'
检查输入的有效性(值必须介于 0 到 255 之间)。
解决方案 5:
我真的很惊讶没有人建议这种方法:
对于 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
解决方案 6:
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)))
解决方案 7:
在Python 3.6中,你可以使用f 字符串来使其更简洁:
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)
解决方案 8:
您可以使用 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`
解决方案 9:
下面是一个更完整的函数,用于处理 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))
解决方案 10:
请注意,这仅适用于 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
解决方案 11:
对于所有简单的颜色转换,matplotlib 提供了一个具有大量函数的模块,其中包括:
转RGB
RGB 到 HSV 格式
到十六进制
到RGB
到_rgba
您只需将您的值标准化为 0 到 1 之间。就您而言:
from matplotlib.colors import to_hex
t = (0, 128, 64)
to_hex(tuple(v/255. for v in t)) # returns '#008040'
解决方案 12:
您还可以使用非常高效的按位运算符,尽管我怀疑您会担心这种操作的效率。它也相对干净。请注意,它不会限制或检查边界。至少从Python 2.7.17开始,此功能就已受支持。
hex(r << 16 | g << 8 | b)
要将其更改为以 # 开头,您可以执行以下操作:
"#" + hex(243 << 16 | 103 << 8 | 67)[2:]
解决方案 13:
def RGB(red,green,blue): return '#%02x%02x%02x' % (red,green,blue)
background = RGB(0, 128, 64)
我知道 Python 中的单行代码不一定受欢迎。但有时我还是忍不住要利用 Python 解析器允许的功能。它与 Dietrich Epp 的解决方案(最佳)相同,但包含在一行函数中。所以,谢谢 Dietrich!
我现在正在 tkinter 中使用它 :-)
解决方案 14:
有一个名为 webcolors 的包。https ://github.com/ubernostrum/webcolors
它有一个方法webcolors.rgb_to_hex
>>> import webcolors
>>> webcolors.rgb_to_hex((12,232,23))
'#0ce817'
解决方案 15:
如果输入三次格式字符串似乎有点冗长......
位移位和 f 字符串的组合可以很好地完成这项工作:
# Example setup.
>>> r, g, b = 0, 0, 195
# Create the hex string.
>>> f'#{r << 16 | g << 8 | b:06x}'
'#0000c3'
这也说明了如果红色或绿色通道为零,则不会丢失“前导”零位的方法。
解决方案 16:
''.join('%02x'%i for i in input)
可用于从 int 数字转换为十六进制
解决方案 17:
我的课程任务要求在不使用 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))
扫码咨询,免费领取项目管理大礼包!