欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

RGB与HEX颜色代码的转换指南

最编程 2024-01-13 07:56:11
...
def convert(value):
"""
convert 2------>16
:param value: input int type
:return: str type(16)
"""
if value == 10:
return "A"
elif value == 11:
return "B"
elif value == 12:
return "C"
elif value == 13:
return "D"
elif value == 14:
return "E"
elif value == 15:
return "F"
return str(value)

def convert_hex(value):
"""
convert 16------2
:param value: input string type
:return: str type(2)
"""
if value == "A":
return str(10)
elif value == "B":
return str(11)
elif value == "C":
return str(12)
elif value == "D":
return str(13)
elif value == "E":
return str(14)
elif value == "F":
return str(15)
return str(value)

def rgb2hex(rgb):
"""
Convert RGB to HEX color
:param rgb: Rge value example(23,32,44)
:return: Hex value example #??????
"""
hex = []
for i in rgb:
if i == 0:
h = str(0) + str(0)
else:
h_left = i / 16
h_right = i % 16
h = convert(h_left) + convert(h_right)

hex.append(h)
hex_combine = "#" + ''.join(hex)
return hex_combine

def hex2rgb(hex_value):
"""
Convert hex to rgp
:param hex_value: string type example "#1722DF"
:return: a rgb color tuple example (23,34,223)
"""
hex = hex_value[1:]
hex_splite = [convert_hex(x) for x in hex if x]
hex_splite_rgb = splite_string(hex_splite, 2)
rgb = [int(line[0]) * 16 + int(line[1]) for line in hex_splite_rgb if line]
return tuple(rgb)

def splite_string(s, n):
return [s[i:i + n] for i in range(len(s)) if i % n == 0]

推荐阅读