KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: RGB to HSL colors, and Back!
PRODUCT: 4D | VERSION: 11 | PLATFORM: Mac & Win
Published On: November 19, 2009

RGB and HSL are two different color definitions. RGB uses Red, Green, and Blue color components to define colors. HSL uses Hue, Saturation, and Lightness. In RGB the three values are integers from 0 to 255. In HSL the Hue is a degree value (0 to 360), and Saturation and Lightness are real values from 0 to 1.

HSL is a different way to represent colors but can be computationally the same as RGB. Because HSL defines colors in a more intuitive fashion you can change the darkness of a given color or manipulate it in similar ways. The following code shows how to convert between HSL and RGB:

RGB to HSL method:
Input Parameters:
$1, $2, $3: R, G, B integer values 0 to 255
Return Parameters:
$4: Pointer to H integer value 0 to 360
$5, $6: Pointers to S, L real values 0 to 1

C_LONGINT($1;$2;$3)
C_POINTER($4;$5;$6)
C_LONGINT($r;$g;$b;$h)
C_REAL($r1;$g1;$b1;$s;$l;$max;$min)

$r:=$1
$g:=$2
$b:=$3
$r1:=$r/255
$g1:=$g/255
$b1:=$b/255

$max:=Choose($r1>$g1);Choose($b1>$r1;$b1;$r1);Choose($b1>$g1);$b1;$g1))
$min:=Choose($r1<$g1);Choose($b1<$r1;$b1;$r1);Choose($b1<$g1);$b1;$g1)))

Case of
 : ($max=$min)
  $h:=0
 : ($max=$r1)
  $h:=((60*(($g1-$b1)/($max-$min)))+360)%360
 : ($max=$g1)
  $h:=((60*(($b1-$r1)/($max-$min)))+120)%360
 : ($max=$b1)
  $h:=((60*(($r1-$g1)/($max-$min)))+240)%360
End case

$l:=0.5*($max+$min)

Case of
 : ($max=$min)
  $s:=0
 : ($l<=0.5)
  $s:=($max-$min)/($max+$min)
 : ($l>0.5)
  $s:=($max-$min)/(2-($max+$min))
End case

$4->:=$h
$5->:=$s
$6->:=$l


HSL to RGB method:
Input Parameters:
$1: H integer value 0 to 360
$2, $3: S, L real values 0 to 1
Return Parameters:
$4, $5, $6: Pointers to R, G, B integer values 0 to 255

C_LONGINT($1)
C_REAL($2;$3)
C_POINTER($4;$5;$6)
C_LONGINT($r;$g;$b;$h)
C_REAL($r1;$g1;$b1;$s;$l;$max;$min;$q;$p;$hk;$tr;$tg;$tb)

$h:=$1
$s:=$2
$l:=$3

If ($s=0)
 $r1:=$l
 $g1:=$l
 $b1:=$l
Else
 $q:=Choose($l<0.5;$l*(1+$s);$l+$s-($l*$s))
 $p:=(2*$l)-$q
 $hk:=$h/360
 $tr:=$hk+(1/3)
 $tg:=$hk
 $tb:=$hk-(1/3)
 $tr:=Choose($tr<0;$tr+1;Choose($tr>1;$tr-1;$tr))
 $tg:=Choose($tg<0;$tg+1;Choose($tg>1;$tg-1;$tg))
 $tb:=Choose($tb<0;$tb+1;Choose($tb>1;$tb-1;$tb))

 $r1:=util_getRGB ($tr;$p;$q)
 $g1:=util_getRGB ($tg;$p;$q)
 $b1:=util_getRGB ($tb;$p;$q)
End if

$r:=$r1*255
$g:=$g1*255
$b:=$b1*255

$4->:=$r
$5->:=$g
$6->:=$b


The following method "util_getRGB" is used as part of the calculation for the HSL to RGB method:

C_REAL($1;$2;$3;$0)
C_REAL($rgbval;$trgb;$p;$q)

$trgb:=$1
$p:=$2
$q:=$3

Case of
 : ($trgb<(1/6))
  $rgbval:=$p+(($q-$p)*6*$trgb)
 : ($trgb<0.5)
  $rgbval:=$q
 : ($trgb<(2/3))
  $rgbval:=$p+(($q-$p)*6*((2/3)-$trgb))
 Else
  $rgbval:=$p
End case

$0:=$rgbval