
procedure RGB_to_HLS (r,g,b: real; var h,l,s:real):
{Given: rgb each in [0,1].
Desired: h in [0,360] and s in [0,1], except if s=0, then h=UNDEFINED.}
begin
max := Maximum (r,g,b);
min := Minimum (r,g,b);
l := (max+min)/2 {This is the lightness}
{Next calculate saturation}
if max=min then
begin
s := 0;
h := UNDEFINED
end {Acrhomatic case}
else
begin {Chromatic case}
{First calculate the saturation.}
if l <= 0.5 then
s := (max-min)/(max+min);
else s := (max-min)/(2-max-min);
{Next calculate the hue.}
delta := max-min
if r = max then
h := (g-b)/delta {Resulting color is between yellow and magenta}
else if g = max then
h := 2 + (b-r)/delta {Resulting color is between cyan and yellow}
else if b = max then
h := 4 + (r-g)/delta; {Resulting color is between magenta and cyan{
h := h*60 {Convert to degrees}
if h < 0.0 then
h := h + 360 {Make degrees be nonnegative}
end {Chromatic Case}
end {RGB_to_HLS}