rec*_*gle 65 python rgb colors
我需要将(0,128,64)转换为这样的#008040.我不知道该怎么称呼后者,使搜索变得困难.
Die*_*Epp 144
使用格式运算符%:
>>> '#%02x%02x%02x' % (0, 128, 64)
'#008040'
Run Code Online (Sandbox Code Playgroud)
请注意,它不会检查边界...
>>> '#%02x%02x%02x' % (0, -1, 9999)
'#00-1270f'
Run Code Online (Sandbox Code Playgroud)
Jes*_*lon 46
def clamp(x):
return max(0, min(x, 255))
"#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))
Run Code Online (Sandbox Code Playgroud)
这使用了首选的字符串格式化方法,如PEP 3101中所述.它还使用min()并max确保这一点0 <= {r,g,b} <= 255.
更新添加了钳位功能,如下所示.
更新从问题的标题和给定的上下文来看,显然这需要[0,255]中的3个整数,并且在传递3个这样的整数时将始终返回颜色.但是,根据评论,这对每个人来说可能并不明显,因此请明确说明:
提供三个
int值,这将返回表示颜色的有效十六进制三元组.如果这些值介于[0,255]之间,那么它会将这些值视为RGB值并返回与这些值对应的颜色.
小智 17
这是一个老问题但是为了获取信息,我开发了一个包含一些与颜色和颜色映射相关的实用程序的包,并包含你想要将三元组转换为hexa值的rgb2hex函数(可以在许多其他包中找到,例如matplotlib).这是在pypi上
pip install colormap
Run Code Online (Sandbox Code Playgroud)
然后
>>> from colormap import rgb2hex
>>> rgb2hex(0, 128, 64)
'##008040'
Run Code Online (Sandbox Code Playgroud)
检查输入的有效性(值必须在0到255之间).
Mes*_*ion 14
我真的很惊讶没有人建议这种方法:
对于 Python 2 和 3:
'#' + ''.join('{:02X}'.format(i) for i in colortuple)
Run Code Online (Sandbox Code Playgroud)
Python 3.6+:
'#' + ''.join(f'{i:02X}' for i in colortuple)
Run Code Online (Sandbox Code Playgroud)
作为一个函数:
def hextriplet(colortuple):
return '#' + ''.join(f'{i:02X}' for i in colortuple)
color = (0, 128, 64)
print(hextriplet(color))
Run Code Online (Sandbox Code Playgroud)
'#' + ''.join('{:02X}'.format(i) for i in colortuple)
Run Code Online (Sandbox Code Playgroud)
我为它创建了一个完整的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')))
Run Code Online (Sandbox Code Playgroud)
您可以在以下链接中查看完整的代码和教程:RGB到Hex和使用Python的Hex到RGB转换
小智 8
您可以使用 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))
Run Code Online (Sandbox Code Playgroud)
用法
rgb2hex(r,g,b) #output = #hexcolor
hex2rgb("#hex") #output = (r,g,b) hexcolor must be in #hex format
triplet = (0, 128, 64)
print '#'+''.join(map(chr, triplet)).encode('hex')
Run Code Online (Sandbox Code Playgroud)
要么
from struct import pack
print '#'+pack("BBB",*triplet).encode('hex')
Run Code Online (Sandbox Code Playgroud)
python3略有不同
from base64 import b16encode
print(b'#'+b16encode(bytes(triplet)))
Run Code Online (Sandbox Code Playgroud)
在Python 3.6中,您可以使用f 字符串来使其更清晰:
rgb = (0,128, 64)
f'#{rgb[0]:02x}{rgb[1]:02x}{rgb[2]:02x}'
Run Code Online (Sandbox Code Playgroud)
当然,您可以将其放入function中,并且作为奖励,值会四舍五入并转换为 int:
def rgb2hex(r,g,b):
return f'#{int(round(r)):02x}{int(round(g)):02x}{int(round(b)):02x}'
rgb2hex(*rgb)
Run Code Online (Sandbox Code Playgroud)
这是一个更完整的函数,用于处理 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))
Run Code Online (Sandbox Code Playgroud)