Color conversion from terminal color to Colors.jl color

Hi,
how can I convert the “one integer” terminal color consumed by printstyled() to a Colors.jl color usable within Luxor e.g.?

Something like this might get you started

using Luxor
using Colors

low_ansi_colors = Dict(
    0 => RGB(0, 0, 0),    
    1 => RGB(0.5, 0, 0), 
    2 => RGB(0, 0.5, 0), 
    3 => RGB(0.5, 0.5, 0), 
    4 => RGB(0, 0, 0.5), 
    5 => RGB(0.5, 0, 0.5),
    6 => RGB(0, 0.5, 0.5),
    7 => RGB(0.75, 0.75, 0.75),
    8 => RGB(0.5, 0.5, 0.5),
    9 => RGB(1, 0, 0), 
    10 => RGB(0, 1, 0), 
    11 => RGB(1, 1, 0),
    12 => RGB(0, 0, 1), 
    13 => RGB(1, 0, 1),
    14 => RGB(0, 1, 1),
    15 => RGB(1, 1, 1)
)

function ansi_to_colorant(ansi_code)
    if ansi_code < 16
        return low_ansi_colors[ansi_code]
    elseif ansi_code < 232
        r = (ansi_code - 16) ÷ 36
        g = ((ansi_code - 16) ÷ 6) % 6
        b = (ansi_code - 16) % 6
        return RGB(r / 5, g / 5, b / 5)
    else
        grey = (ansi_code - 232) / 23
        return RGB(grey, grey, grey)
    end
end

@drawsvg begin
    background("black")
    table = Table(16, 16, 30, 30)
    for (pos, n) in table
        sethue(ansi_to_colorant(n))
        box(table, n, :fill)
        sethue("white")
        text(string(n), pos, halign=:center)
    end
end

4 Likes

How about making these two

  1. low_ansi_colors
  2. ansi_to_colorant

available inside the Luxor package by default?

If it has to go anywhere, it would probably be in Colors.jl. I see no use for it anywhere else.

When StyledStrings.jl is widely available, you might be able to access the information here.

1 Like

@cormullion Thanks again for your efforts!
I totally agree with you that this doesn’t belong to any drawing library at all which is why I tried not to bother you but rather to address this question more in the direction of the Colors.jl people.
Regarding the StyledStrings.jl about which I read in the Julia 1.11(?) announcement there obviously happened what I was afraid of which is that two competing color management infrastructures come to life that are not directly connected to each other.
I still don’t know enough about Julia syntax but I believe that the “Colors” way and the “StyledStrings” way are quite different in terms of identifying colors. One uses numbers the other one symbols. I have no idea how these can be translated into each other efficiently.

Anyway the legacy_color() function which is not exposed to the public as far as I understand would translate from 8 bit to 24 bit RGB. Would this be consumable by e.g. Luxor directly?

This won’t be a problem, StyledStrings defines a SimpleColor which can be an ordinary RGB triplet. The glue code to get this working with Colors.jl should be relatively straightforward.

1 Like