如何将六角形三元组转换为RGB元组并返回? [英] How do I convert a hex triplet to an RGB tuple and back?
本文介绍了如何将六角形三元组转换为RGB元组并返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将一个十六进制三元组转换为一个RGB元组,然后将一个元组转换为十六进制三元组。
I'd like to convert a hex triplet to an RGB tuple and then convert a tuple to a hex triplet.
推荐答案
您可以使用包含一些切片和位移的查找表所有相对较快的操作创建几个在Python 2和3中都不会改变的函数:
You can use a look-up table with some slicing and shifts — all relatively fast operations — to create a couple of functions that will work unchanged in both Python 2 and 3:
_NUMERALS = '0123456789abcdefABCDEF'
_HEXDEC = {v: int(v, 16) for v in (x+y for x in _NUMERALS for y in _NUMERALS)}
LOWERCASE, UPPERCASE = 'x', 'X'
def rgb(triplet):
return _HEXDEC[triplet[0:2]], _HEXDEC[triplet[2:4]], _HEXDEC[triplet[4:6]]
def triplet(rgb, lettercase=LOWERCASE):
return format(rgb[0]<<16 | rgb[1]<<8 | rgb[2], '06'+lettercase)
if __name__ == '__main__':
print('{}, {}'.format(rgb('aabbcc'), rgb('AABBCC')))
# -> (170, 187, 204), (170, 187, 204)
print('{}, {}'.format(triplet((170, 187, 204)),
triplet((170, 187, 204), UPPERCASE)))
# -> aabbcc, AABBCC
print('{}, {}'.format(rgb('aa0200'), rgb('AA0200')))
# -> (170, 2, 0), (170, 2, 0)
print('{}, {}'.format(triplet((170, 2, 0)),
triplet((170, 2, 0), UPPERCASE)))
# -> aa0200, AA0200
这篇关于如何将六角形三元组转换为RGB元组并返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文