Tuesday, July 31, 2007

Messing around with code and colors

Inspired by this article I put together an erlang function to convert colors form HSL to RGB model. I will use it with the erlycairo imaging library and dynamic CSS generation as supported in erlyweb to get the colors right, hopefully !

Update:

How do erlang code snippets look like, just copy-pasted into google blogger and converted to courier font ? They get screwed up, because some special characters need proper escaping. Fortunately aquamacs, my preferred editor on the mac, has the htmlize mode, which turns anything into HTML. And also had to add some CSS from the generated emacs HTML output to the blogger template to make the snippet look more readable .

hsl_to_rgb(_H, S, L) when S == 0.0 ->
[L, L, L];

hsl_to_rgb(H, S, L) ->
Q = q(H,
S, L),
P = 2.0 * L - Q,
H1 = H / 360.0,
TList = [ t(T) || T <- [H1 + 1.0 / 3.0, H1, H1 - 1.0 / 3.0]],
[ c(P, Q, T) || T <- TList ].


q(_H, S, L) when (L < 0.5) ->
L * (1.0 + S);
q(_H, S, L) ->
L + S - L * S.

t(T) when (T < 0) ->
T + 1.0;
t(T) when (T > 1.0) ->
T - 1.0;
t(T) ->
T.

c(P, Q, T) when T < 1.0 / 6.0 ->
P + ((Q - P) * 6.0 * T);
c(P, Q, T) when 1.0 / 6.0 =< T, T < 0.5 ->
Q;
c(P, Q, T) when 0.5 =< T, T < 2.0 / 3.0 ->
P + ((Q - P) * (2.0 / 3.0 - T) * 6.0);
c(P, Q, T) ->
P.

No comments: