Reputation: 115
I am using colors.jl package and have RGB values that I need to convert to hex string triplet value. What's the best way to do this? couldn't find a conversion function in colors.jl
thanks
Upvotes: 2
Views: 788
Reputation: 652
As suggested by Bogumil, Colors.jl provides the hex
function:
julia> using Colors
julia> hex(RGB(1,0.5,0))
"FF8000"
Upvotes: 3
Reputation: 1301
You can define a custom struct
which is constructible from AbstractRGB
and which has the appropriate show
overload as in
import Base: show
using ColorTypes
struct RGBPacked
r::UInt8
g::UInt8
b::UInt8
function (::Type{RGBPacked})(c::AbstractRGB)
colvec = (red(c), green(c), blue(c))
temp = map(UInt8, map(x->floor(255*x), colvec))
new(temp[1], temp[2], temp[3])
end
end
function show(io::IO, r::RGBPacked)
print(io, "#$(hex(r.r))$(hex(r.g))$(hex(r.b))")
end
Then, you can use your custom datatype as in
c1 = RGB(1.,0.5,0.7)
c2 = RGBPacked(c1)
which prints
Main> c1 = RGB(1.,0.5,0.7)
RGB{Float64}(1.0,0.5,0.7)
Main> c2 = RGBPacked(c1)
#ff7fb2
Upvotes: 3