color code: RGB number to hex

Posted by Zimmy on Sat 28 Dec 2019 05:00 PM — 2 posts, 13,458 views.

#0
I would like to be able to convert RGB color codes into hex format.
I've tried this:

--works for black and white
print("#"..string.format("%06x", ColourNameToRGB("white"))) --> "#ffffff"
print("#"..string.format("%06x", ColourNameToRGB("black"))) --> "#000000"

--but for red, I get blue!
print("#"..string.format("%06x", ColourNameToRGB("red"))) --> "#0000ff"

Thanks!

[EDIT] okay so I figured out rgb color codes are actually bgr [/edit]


--this works :)
local function rgb_to_hex(col)
    local b, g, r = string.match(string.format("%06x", col), "([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])")
    return "#"..r..g..b
end
print(rgb_to_hex(ColourNameToRGB("yellow"))) -- > "#ffff00"
Amended on Sat 28 Dec 2019 05:18 PM by Zimmy
Australia Forum Administrator #1
Yes, see http://www.gammon.com.au/forum/?id=14479 for some discussion about this.