Converting Hex to RGB value in Python

前端 未结 10 1059
一生所求
一生所求 2020-12-04 21:19

Working off Jeremy\'s response here: Converting hex color to RGB and vice-versa I was able to get a python program to convert preset colour hex codes (example #B4FBB8), howe

相关标签:
10条回答
  • 2020-12-04 21:38

    This function will return the RGB values in float from a Hex code.

    def hextofloats(h):
        '''Takes a hex rgb string (e.g. #ffffff) and returns an RGB tuple (float, float, float).'''
        return tuple(int(h[i:i + 2], 16) / 255. for i in (1, 3, 5)) # skip '#'
    

    This function will return Hex code from RGB value.

    def floatstohex(rgb):
        '''Takes an RGB tuple or list and returns a hex RGB string.'''
        return f'#{int(rgb[0]*255):02x}{int(rgb[1]*255):02x}{int(rgb[2]*255):02x}'
    
    0 讨论(0)
  • 2020-12-04 21:41

    As HEX codes can be like "#FFF", "#000", "#0F0" or even "#ABC" that only use three digits. These are just the shorthand version of writing a code, which are the three pairs of identical digits "#FFFFFF", "#000000", "#00FF00" or "#AABBCC".


    This function is made in such a way that it can work with both shorthands as well as the full length of HEX codes. Returns RGB values if the argument hsl = False else return HSL values.

    import re
    
    def hex_to_rgb(hx, hsl=False):
        """Converts a HEX code into RGB or HSL.
        Args:
            hx (str): Takes both short as well as long HEX codes.
            hsl (bool): Converts the given HEX code into HSL value if True.
        Return:
            Tuple of length 3 consisting of either int or float values."""
        if re.compile(r'#[a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?$').match(hx):
            div = 255.0 if hsl else 0
            if len(hx) <= 4:
                return tuple(int(hx[i]*2, 16) / div if div else
                             int(hx[i]*2, 16) for i in (1, 2, 3))
            else:
                return tuple(int(hx[i:i+2], 16) / div if div else
                             int(hx[i:i+2], 16) for i in (1, 3, 5))
        else:
            raise ValueError(f'"{hx}" is not a valid HEX code.')
    

    Here are some IDLE outputs.

    >>> hex_to_rgb('#FFB6C1')
    >>> (255, 182, 193)
    
    >>> hex_to_rgb('#ABC')
    >>> (170, 187, 204)
    
    >>> hex_to_rgb('#FFB6C1', hsl=True)
    >>> (1.0, 0.7137254901960784, 0.7568627450980392)
    
    >>> hex_to_rgb('#ABC', hsl=True)
    >>> (0.6666666666666666, 0.7333333333333333, 0.8)
    
    >>> hex_to_rgb('#00FFFF')
    >>> (0, 255, 255)
    
    >>> hex_to_rgb('#0FF')
    >>> (0, 255, 255)
    
    0 讨论(0)
  • 2020-12-04 21:44

    There are two small errors here!

    hex == input("")
    

    Should be:

    user_hex = input("")
    

    You want to assign the output of input() to hex, not check for comparison. Also, as mentioned in comments (@koukouviou) don't override hex, instead call it something like user_hex.

    Also:

    print(hex_to_rgb(hex()))
    

    Should be:

    print(hex_to_rgb(user_hex))
    

    You want to use the value of hex, not the type's callable method (__call__).

    0 讨论(0)
  • 2020-12-04 21:45

    Just another option: matplotlib.colors module.

    Quite simple:

    >>> import matplotlib.colors
    >>> matplotlib.colors.to_rgb('#B4FBB8')
    (0.7058823529411765, 0.984313725490196, 0.7215686274509804)
    

    Note that the input of to_rgb need not to be hexadecimal color format, it admits several color formats.

    You can also use the deprecated hex2color

    >>> matplotlib.colors.hex2color('#B4FBB8')
    (0.7058823529411765, 0.984313725490196, 0.7215686274509804)
    

    The bonus is that we have the inverse function, to_hex and few extra functions such as, rgb_to_hsv.

    0 讨论(0)
提交回复
热议问题