Function to Calculate the Best Font Color for a Background Color

This PHP function tables a hexadecimal color code like “ff0000” and figures out what’s more color font text would be more readable, black or white.

public static function bestTextColor($hexCode){
	$redHex = substr($hexCode,0,2);
	$greenHex = substr($hexCode,2,2);
	$blueHex = substr($hexCode,4,2);

	$r = (hexdec($redHex)) / 255;
	$g = (hexdec($greenHex)) / 255;
	$b = (hexdec($blueHex)) / 255;

	$brightness = (($r * 299) + ($g * 587) + ($b * 114)) / 1000;
	// human eye sees 60% easier
	if($brightness > .6){
		return '000000';
	}else{
		return 'ffffff';
	}
}

Leave a Reply

Your email address will not be published.