在这里处理杰里米的回应:将十六进制颜色转换为RGB,反之亦然。 i能够获得一个python程序来转换预设的彩色十六进制代码(例如#B4FB8),但是从最终用户的角度来看,我们不能要求人们编辑代码并从那里运行。如何提示用户输入一个十六进制值,然后让它从那里吐出一个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仍然很粗糙。
发布于 2015-04-15 07:03:37
我相信这做了你想要的:
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)) ))
发布于 2020-03-11 06:07:55
您可以使用ImageColor
从枕头。
>>> from PIL import ImageColor
>>> ImageColor.getcolor("#23a9dd", "RGB")
(35, 169, 221)
发布于 2020-09-17 15:31:25
只是另一个选择: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
。
https://stackoverflow.com/questions/29643352
复制相似问题