Convert HEX to closest X11 Color Number

后端 未结 5 1721
醉梦人生
醉梦人生 2021-02-01 08:43

I\'m looking for a Algorithm/Way to convert given HEX (e.g. #111111 R:0x11, G:0x11, B:0x11) to the closest X11 color number (Terminal is either 88 or 256 colors) using either Py

5条回答
  •  滥情空心
    2021-02-01 09:25

    Here is python implementation that is constant time:

    N = []
    for i, n in enumerate([47, 68, 40, 40, 40, 21]):
        N.extend([i]*n)
    
    def rgb_to_xterm(r, g, b):
        mx = max(r, g, b)    
        mn = min(r, g, b)
    
        if (mx-mn)*(mx+mn) <= 6250:
            c = 24 - (252 - ((r+g+b) // 3)) // 10
            if 0 <= c <= 23:
                return 232 + c
    
        return 16 + 36*N[r] + 6*N[g] + N[b]
    

提交回复
热议问题