Converting Hex to RGB value in Python

前端 未结 10 1081
一生所求
一生所求 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:37

    All the answers I've seen involve manipulation of a hex string. In my view, I'd prefer to work with encoded integers and RGB triples themselves, not just strings. This has the benefit of not requiring that a color be represented in hexadecimal-- it could be in octal, binary, decimal, what have you.

    Converting an RGB triple to an integer is easy.

    rgb = (0xc4, 0xfb, 0xa1) # (196, 251, 161)
    
    def rgb2int(r,g,b):
        return (256**2)*r + 256*g + b
    
    c = rgb2int(*rgb) # 12909473
    print(hex(c))     # '0xc4fba1'
    

    We need a little more math for the opposite direction. I've lifted the following from my answer to a similar Math exchange question.

    c = 0xc4fba1
    
    def int2rgb(n):
        b = n % 256
        g = int( ((n-b)/256) % 256 )      # always an integer
        r = int( ((n-b)/256**2) - g/256 ) # ditto
        return (r,g,b)
    
    print(tuple(map(hex, int2rgb(c)))) # ('0xc4', '0xfb', '0xa1')
    

    With this approach, you can convert to and from strings with ease.

提交回复
热议问题