How do I convert a hex triplet to an RGB tuple and back?

后端 未结 10 1474
孤街浪徒
孤街浪徒 2020-12-14 00:24

I\'d like to convert a hex triplet to an RGB tuple and then convert a tuple to a hex triplet.

10条回答
  •  感动是毒
    2020-12-14 01:01

    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
    

提交回复
热议问题