KristofferC / Crayons.jl

Colored and styled strings for terminals.
Other
150 stars 14 forks source link

Downcasting to `256` colors #58

Closed t-bltg closed 2 years ago

t-bltg commented 2 years ago

According to https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit:

In the 6x6x6 cube, if I take #ff8700 = rgb(255, 135, 0) I should land on the ANSI color code 208.

julia> using Crayons
julia> Crayon(foreground = (255, 135, 0)).fg |> Crayons.to_256_colors |> Crayons.val |> Int
214  # NOK

If instead I use the following :

julia> using Crayons
julia> function cubecolor(c)  # see stackoverflow.com/a/27165165
    tc = [0, 95, 135, 175, 215, 255]
    argmin(abs.(c .- tc)) - 1
end
julia> function to_256_colors(color)
    r, g, b = color.r, color.g, color.b
    r24, g24, b24 = map(c->round(Int, c * 23 / 256), (r, g, b))
    if r24 == g24 == b24
        return Crayons.ANSIColor(UInt8(232 + r24), Crayons.COLORS_256, color.active)
    else
        # r6, g6, b6 = map(c->round(Int, c * 5  / 256), (r, g, b))
        r6, g6, b6 = map(c->cubecolor(c), (r, g, b))  # <== note the change
        return Crayons.ANSIColor(UInt8(16 + 36 * r6 + 6 * g6 + b6), Crayons.COLORS_256, color.active)
    end
end
julia> Crayon(foreground = (255, 135, 0)).fg |> to_256_colors |> Crayons.val |> Int
208  # OK, expected value

Is this a bug ?