如何将十六进制三元组转换为 RGB 元组并返回? [英] How do I convert a hex triplet to an RGB tuple and back?

查看:36
本文介绍了如何将十六进制三元组转换为 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆