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

后端 未结 10 1452
孤街浪徒
孤街浪徒 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 00:52

    A very simplistic approach to convert rgb to hex

    >>> rgb = (255, 255, 255)
    >>> r, g , b = rgb
    >>> hex(r)
    '0xff'
    >>> hex(r) + hex(g)[2:] + hex(b)[2:]
    '0xffffff'
    >>>
    

    A simplistic approach to convert Hex to rgb

    >>> h  = '0xffffff'
    >>> h1, h2, h3 = h[0:4], '0x' + h[4:6], '0x' + h[6:8]
    >>> h1, h2, h3
    ('0xff', '0xff', '0xff')
    >>> r, g , b = int(h1, 16), int(h2, 16), int(h3, 16)
    >>> r, g, b
    (255, 255, 255)
    

    Use a module which provides some these facility: webcolors

    >>> hex_to_rgb('#000080')
    (0, 0, 128)
    >>> rgb_to_hex((255, 255, 255))
    '#ffffff'
    

    Function doc:

    hex_to_rgb(hex_value) Convert a hexadecimal color value to a 3-tuple of integers suitable for use in an rgb() triplet specifying that color.

    rgb_to_hex(rgb_triplet) : Convert a 3-tuple of integers, suitable for use in an rgb() color triplet, to a normalized hexadecimal value for that color.

    0 讨论(0)
  • 2020-12-14 00:52

    HEX to RGB tuple

    >>> tuple(bytes.fromhex('61559a'))
    (97, 85, 154)
    

    RGB tuple to HEX

    >>> bytes((97, 85, 154)).hex()
    '61559a'
    

    No imports needed!


    What is this magic?!

    Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b, b[0] will be an integer, while b[0:1] will be a bytes object of length 1

    ...

    The representation of bytes objects uses the literal format (b'...') since it is often more useful than e.g. bytes([46, 46, 46]). You can always convert a bytes object into a list of integers using list(b).

    Source: https://docs.python.org/3/library/stdtypes.html#bytes-objects

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-14 01:03
    >>> import struct
    >>> rgbstr='aabbcc'
    >>> struct.unpack('BBB',rgbstr.decode('hex'))
    (170, 187, 204)
    

    and

    >>> rgb = (50,100,150)
    >>> struct.pack('BBB',*rgb).encode('hex')
    '326496'
    
    0 讨论(0)
  • 2020-12-14 01:05

    Trying to be pythonic:

    >>> rgbstr='aabbcc'
    >>> tuple(ord(c) for c in rgbstr.decode('hex'))
    (170, 187, 204)
    >>> tuple(map(ord, rgbstr.decode('hex'))
    (170, 187, 204)
    

    and

    >>> rgb=(12,50,100)
    >>> "".join(map(chr, rgb)).encode('hex')
    '0c3264'
    
    0 讨论(0)
  • 2020-12-14 01:05
    import re
    
    def hex_to_int_color(v):
      return tuple(int(i,16) for i in re.match(
        r'^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$', v,
        flags=re.IGNORECASE).groups())
    
    def int_to_hex_color(v):
      return '#%02x%02x%02x' % v
    
    0 讨论(0)
提交回复
热议问题