Quick PHP Color Guessing Function

 

I was in a hurry and needed to guess the basic color of any hex value. Not precise and not the most elegant solution (color math is complicated!) but it is doing the job.

public function guess_color($hex = '') {
	$hex = strtolower(str_replace('#', '', $hex));
	$hex = str_replace(array('a','b','c','d','e','f'), '9', $hex);
	
	$r = $hex[0].$hex[1];
	$g = $hex[2].$hex[3];
	$b = $hex[4].$hex[5];
		
	if($r-$g > 30 && $r-$b > 30) return 'red';
	if($g-$r > 30 && $g-$b > 30) return 'green';
	if($b-$r > 30 && $b-$g > 30) return 'blue';
	if($r-$g < 20 && ($r+$g)-($b*2) > 40) return 'yellow';
	if($r-$b < 20 && ($r+$b)-($g*2) > 40) return 'purple';
	if($g-$b < 20 && ($g+$b)-($r*2) > 40) return 'teal';
		
	if($r-$g-$b < 20 && $r > 200) return 'white';
	if($r-$g-$b < 20 && $r < 50) return 'black';
	if($r-$g-$b < 20) return 'gray';
		
	return 'unk';
}

There are plenty of pitfalls in the above approach (orange?) but it is also a fast and effective enough approach to detect a few hues.

Last updated on