Convert RGB to HSL in PHP, and sort by color

May 16th, 2014 by Alex Leave a reply »

Here’s a simple way to convert an RGB color into an HSL (Hue/Saturation/Lightness). You might ask why we need that at all? Well, first, we might then use that to find the lightest color, or sort colors by Hue (that will give a rainbow effect when you output the colors sorted like that).

Anyway, a simple function is here:

function rgbToHsl($r, $g, $b) {
    $r /= 255; 
    $g /= 255; 
    $b /= 255;
    $max = max($r, $g, $b);
        $min = min($r, $g, $b);
    $h = 0;
    $s = 0;
    $l = ($max + $min) / 2;
 
    if($max == $min){
        $h = $s = 0; // achromatic
    }else{
        $d = $max - $min;
        $s = $l > 0.5 ? $d / (2 - $max - $min) : $d / ($max + $min);
        switch($max){
            case $r: $h = ($g - $b) / $d + ($g < $b ? 6 : 0); break;
            case $g: $h = ($b - $r) / $d + 2; break;
            case $b: $h = ($r - $g) / $d + 4; break;
        }
        $h /= 6;
    }
 
    return array('h'=>$h, 's'=>$s, 'l'=>$l);
}

Then if we have a hex color, we can call it like this:

$rgb = 'FF0000';
$r = hexdec(substr($rgb, 0, 2));
$g = hexdec(substr($rgb, 2, 2));
$b = hexdec(substr($rgb, 4, 2));
$hsl = rgbToHsl($r, $g, $b);
print_r($hsl); // should output Array ( [h] => 0 [s] => 1 [l] => 0.5 )

Now it is pretty easy to sort using the above data, say:

function sortColorsByColor($rgblist) {
	$sort = array();
	foreach($rgblist as $rgb) {
		$hsl = rgbToHsl(hexdec(substr($rgb, 0, 2)), hexdec(substr($rgb, 2, 2)), hexdec(substr($rgb, 4, 2)));
		$sort[] = $hsl['h'];
	}
	array_multisort($sort, SORT_ASC, $rgblist);
	return $rgblist;
}
 
$list = array('9DD3FA', '1F39A1', '6D7AAB', ..);
$sorted = sortColorsByColor($list); // will now contain a color-sorted list of hex colors

Leave a Reply