Converting Colours to HEX

Posted by Rene on Mon 01 Oct 2018 10:50 PM — 5 posts, 22,898 views.

#0
I am looking for a good way to convert a colour from it's name to the hex value, i.e. convert "red" to "#FF0000", etc.

Thanks!
USA Global Moderator #1
modified from http://www.gammon.com.au/forum/?id=1883


function ColourNameToRGBHex(color_name)
   color = ColourNameToRGB(color_name)
   low = math.floor(color/65536)
   color = color - low * 65536
   mid = math.floor(color/256) * 256
   color = color - mid
   high = color * 65536
   return string.format("#%06x", high + mid + low)
end
Amended on Tue 02 Oct 2018 11:16 PM by Fiendish
#2
Thanks, but it does not seem to be working fully.
For blue it returns #ff, for green #8000

I am looking at it to try understanding it and see if I can figure out the issue. I am unsure what the general number from ColourNameToRGB means, as standard RGB give 3 numbers for the red, green and blue value, yet this returns a single number, so I assume if I understood that it would make things simpler.

Thanks so far.
Australia Forum Administrator #3

Yes, but you asked for one number.

See https://en.wikipedia.org/wiki/Web_colors#HTML_color_names

The standard HTML colour codes are like this:

#rrggbb

Where “rr” is the red component (0 to 0xFF, that is, 0 to 255) and so on.

Full green is actually “lime” and not “green”. Lime would give you #FF00

USA Global Moderator #4
I've updated it to add zero-padding.