将十六进制颜色转换为 RGB,反之亦然我能够得到一个 python 程序来转换预设颜色十六进制代码(例如#B4FBB8),但是从最终用户的角度来看,我们不能问人们编辑代码并从那里运行。如何提示用户输入一个十六进制值,然后让它从那里吐出一个 RGB 值?
这是我到目前为止的代码:
def hex_to_rgb(value):
value = value.lstrip('#')
lv = len(value)
return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
def rgb_to_hex(rgb):
return '#%02x%02x%02x' % rgb
hex_to_rgb("#ffffff") # ==> (255, 255, 255)
hex_to_rgb("#ffffffffffff") # ==> (65535, 65535, 65535)
rgb_to_hex((255, 255, 255)) # ==> '#ffffff'
rgb_to_hex((65535, 65535, 65535)) # ==> '#ffffffffffff'
print('Please enter your colour hex')
hex == input("")
print('Calculating...')
print(hex_to_rgb(hex()))
使用线
print(hex_to_rgb('#B4FBB8'))
我能够让它吐出正确的 RGB 值,即 (180, 251, 184)它可能超级简单——我对 Python 还是很粗略。
h = input('Enter hex: ').lstrip('#')
print('RGB =', tuple(int(h[i:i+2], 16) for i in (0, 2, 4)))
(以上是为 Python 3 编写的)
样品运行:
Enter hex: #B4FBB8
RGB = (180, 251, 184)
写入文件
fhandle
的文件:
fhandle.write('RGB = {}'.format( tuple(int(h[i:i+2], 16) for i in (0, 2, 4)) ))
ImageColor
。
>>> from PIL import ImageColor
>>> ImageColor.getcolor("#23a9dd", "RGB")
(35, 169, 221)
matplotlib.colors 模块。
很简单:
>>> import matplotlib.colors
>>> matplotlib.colors.to_rgb('#B4FBB8')
(0.7058823529411765, 0.984313725490196, 0.7215686274509804)
注意to_rgb
的输入不需要是十六进制颜色格式,它承认几种颜色格式。您还可以使用已弃用的
hex2color
>>> matplotlib.colors.hex2color('#B4FBB8')
(0.7058823529411765, 0.984313725490196, 0.7215686274509804)
奖金是我们有反函数,to_hex
和一些额外的功能,如
rgb_to_hsv
.
webcolors 包具有 hex_to_rgb
功能。
from PIL import ImageColor
ImageColor.getrgb("#9b9b9b")
如果你想要从 0 到 1 的数字
[i/256 for i in ImageColor.getrgb("#9b9b9b")]
def rgb_to_hex(rgb):
return '%02x%02x%02x' % rgb
用法:
>>> rgb_to_hex((255, 255, 195))
'ffffc3'
def hex_to_rgb(hexa):
return tuple(int(hexa[i:i+2], 16) for i in (0, 2, 4))
用法:
>>> hex_to_rgb('ffffc3')
(255, 255, 195)
Hex 代码返回浮点形式的 RGB 值。
def hextofloats(h):
'''Takes a hex rgb string (e.g. #ffffff) and returns an RGB tuple (float, float, float).'''
return tuple(int(h[i:i + 2], 16) / 255. for i in (1, 3, 5)) # skip '#'
RGB值返回Hex代码。
def floatstohex(rgb):
'''Takes an RGB tuple or list and returns a hex RGB string.'''
return f'#{int(rgb[0]*255):02x}{int(rgb[1]*255):02x}{int(rgb[2]*255):02x}'
HEX 代码可以像 "#FFF"
、
"#000"
、
"#0F0"
甚至
"#ABC"
只使用三位数字。这些只是编写代码的简写版本,它们是三对相同的数字
"#FFFFFF"
,
"#000000"
,
"#00FF00"
or
"#AABBCC"
.
此功能的制作方式使其既可以使用简写形式,也可以使用全长的十六进制代码。如果参数 hsl = False
import re
def hex_to_rgb(hx, hsl=False):
"""Converts a HEX code into RGB or HSL.
Args:
hx (str): Takes both short as well as long HEX codes.
hsl (bool): Converts the given HEX code into HSL value if True.
Return:
Tuple of length 3 consisting of either int or float values.
Raise:
ValueError: If given value is not a valid HEX code."""
if re.compile(r'#[a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?$').match(hx):
div = 255.0 if hsl else 0
if len(hx) <= 4:
return tuple(int(hx[i]*2, 16) / div if div else
int(hx[i]*2, 16) for i in (1, 2, 3))
return tuple(int(hx[i:i+2], 16) / div if div else
int(hx[i:i+2], 16) for i in (1, 3, 5))
raise ValueError(f'"{hx}" is not a valid HEX code.')
这里有一些空闲输出。
>>> hex_to_rgb('#FFB6C1')
(255, 182, 193)
>>> hex_to_rgb('#ABC')
(170, 187, 204)
>>> hex_to_rgb('#FFB6C1', hsl=True)
(1.0, 0.7137254901960784, 0.7568627450980392)
>>> hex_to_rgb('#ABC', hsl=True)
(0.6666666666666666, 0.7333333333333333, 0.8)
>>> hex_to_rgb('#00FFFF')
(0, 255, 255)
>>> hex_to_rgb('#0FF')
(0, 255, 255)
>>> hex_to_rgb('#0FFG') # When invalid hex is given.
ValueError: "#0FFG" is not a valid HEX code.
def hex_to_rgb(hex_string):
r_hex = hex_string[1:3]
g_hex = hex_string[3:5]
b_hex = hex_string[5:7]
return int(r_hex, 16), int(g_hex, 16), int(b_hex, 16)
这会将 hexadecimal_string 转换为十进制数
int(hex_string, 16)
例如:
int('ff', 16) # Gives 255 in integer data type
hex == input("")
应该是:
user_hex = input("")
您想将
input()
的输出分配给
hex
,而不是检查比较。此外,如评论中所述 (@koukouviou) 不要覆盖
hex
,而是将其称为
user_hex
.还有:
print(hex_to_rgb(hex()))
应该是:
print(hex_to_rgb(user_hex))
你想使用十六进制的值,而不是类型的可调用方法(
__call__
)。
将 RGB 三元组转换为整数很容易。
rgb = (0xc4, 0xfb, 0xa1) # (196, 251, 161)
def rgb2int(r,g,b):
return (256**2)*r + 256*g + b
c = rgb2int(*rgb) # 12909473
print(hex(c)) # '0xc4fba1'
相反的方向我们需要更多的数学知识。我从我对类似
Math exchange question的回答中提取了以下内容。
c = 0xc4fba1
def int2rgb(n):
b = n % 256
g = int( ((n-b)/256) % 256 ) # always an integer
r = int( ((n-b)/256**2) - g/256 ) # ditto
return (r,g,b)
print(tuple(map(hex, int2rgb(c)))) # ('0xc4', '0xfb', '0xa1')
使用这种方法,您可以轻松地与字符串相互转换。
colorir 可用于格式化和颜色系统之间的转换:
from colorir import HexRGB, sRGB
user_input = input("Enter the hex code:")
rgb = HexRGB(user_input).rgb() # This is safe for pretty much any hex format
#fff
)。这很丑陋,但它确实有效。
def parse_hex(h):
if h[0]=="#":
h=h[1:]
try:
col=int(h,16)
except ValueError:
raise ValueError("Invalid HEX string") from None
l=len(h)
if l== 6: #long form , no alpha
return (col&0xff0000)>>16,(col&0xff00)>>8,(col&0xff),1
elif l== 8: #long form, alpha
scol = col >> 8
return (scol&0xff0000)>>16,(scol&0xff00)>>8,(scol&0xff),(col&0xff)/255
elif l == 3: #short form, no alpha
return 17*((col&0xf00)>>8),17*((col&0xf0)>>4),17*(col&0xf),1
elif l == 4: #short form, alpha
print(hex(col))
return 17*((col&0xf000)>>12),17*((col&0xf00)>>8),17*((col&0xf0)>>4),17*(col&0xf)/255
else:
raise ValueError("Invalid HEX string")
def hex_to_rgb(h, opacity=.8):
r = g = b = 0
if len(h) == 4:
r = int(("0x" + h[1] + h[1]), base=16)
g = int(("0x" + h[2] + h[2]), base=16)
b = int(("0x" + h[3] + h[3]), base=16)
elif len(h) == 7:
r = int(("0x" + h[1] + h[2]), base=16)
g = int(("0x" + h[3] + h[4]), base=16)
b = int(("0x" + h[5] + h[6]), base=16)
if opacity:
return f"rgb({r}, {g}, {b}, {opacity})"
return f"rgb({r}, {g}, {b})"
#fff, #000野外能遇到的
h = input('Enter hex: ').lstrip('#')
if len(h == 3):
h = ''.join([d + d for d in h])
print('RGB =', tuple(int(h[i:i+2], 16) for i in (0, 2, 4)))