Page 1 of 1

HSL to RGB converter

Posted: Sun Nov 14, 2010 8:47 am
by Taehl
I, personally, feel that HSL is simply the very best way to express colors. So, for us HSL lovers, here's a tense function that will make you happy.

Code: Select all

-- Converts HSL to RGB (input and output range: 0 - 255)
function HSL(h, s, l)
	if s == 0 then return l,l,l end
	h, s, l = h/256*6, s/255, l/255
	local c = (1-math.abs(2*l-1))*s
	local x = (1-math.abs(h%2-1))*c
	local m,r,g,b = (l-.5*c), 0,0,0
	if h < 1     then r,g,b = c,x,0
	elseif h < 2 then r,g,b = x,c,0
	elseif h < 3 then r,g,b = 0,c,x
	elseif h < 4 then r,g,b = 0,x,c
	elseif h < 5 then r,g,b = x,0,c
	else              r,g,b = c,0,x
	end
	return math.ceil((r+m)*256),math.ceil((g+m)*256),math.ceil((b+m)*256)
end
Quite lovely, at only 15 lines of code (versus the 50 or 100 I've seen other people take).

EDIT) Majorly improved.

Re: HSL to RGB converter

Posted: Sun Nov 14, 2010 10:47 pm
by Taehl
Worth double-posting to announce: I rewrote it, and now it's one line shorter and fully twice as fast... And square! :awesome:

Re: HSL to RGB converter

Posted: Sat Apr 30, 2016 9:01 pm
by rmcode
What's the license for this?

Re: HSL to RGB converter

Posted: Sat Apr 30, 2016 9:19 pm
by vrld
The code is a literally just the definition of HSL to RGB. You don't need a license for this.

Re: HSL to RGB converter

Posted: Mon May 02, 2016 3:48 am
by Inny
Just as a personal preference note, it might be worth making a few adjustments to this code before using it. The outputs, for instance, are 1-256 instead of 0-255. Maybe use math.floor.

Also, the line that reads h, s, l = h/256*6, s/255, l/255 I personally would change so that the inputs are 0-360, 0-1, and 0-1. The 0-255 for hue is weird, as that would make the 6 major colors be in 42.66667 increments, and with 0-359 it would be in increments of 60. And I prefer 0 for gray, 1 for saturated, 0 for black and 1 for white.

Here's that change:

Code: Select all

h, s, l = h/360*6, math.min(math.max(0, s), 1), math.min(math.max(0, l), 1)

Re: HSL to RGB converter

Posted: Mon May 02, 2016 4:03 pm
by HugoBDesigner
Butting in just to make a little bit of shameless self-promotion, but in my Pattern Generator program I wrote a really neat (yet really complex imo) color selection library. It has rgb to hsl convertion, hexadecimals, etc.

viewtopic.php?f=5&t=81186

Has a lot of issues, I'm sure, and could definitely use a lot of polishing, but overall it works well. Here's a preview of it:
https://twitter.com/HugoBDesigner/statu ... 3650212864


If anyone wants to use it, have fun. Crediting not required but appreciated. If someone wants to "pretty the code up", good luck xD