Skip to content

Contrasting color function for PHP

For another site of mine I needed a way to determine whether black or white was a better choice for text on a randomly colored background.

function contrast_color($col) {
	$d = 0;
	$a = 1 - (0.299 * $col['r'] + 0.587 * $col['g'] + 0.114 * $col['b']) / 255;
	if ($a < 0.5) {
		$d = 0;
	}
	else {
		$d = 255;
	}
	return array('r' => $d, 'g' => $d, 'b' => $d); 
}

The function takes a color as an array with elements r, g, and b and returns an array with the same 3 elements. Although in the returned array all 3 elements will either be 0 or 255 so you’ll always get either white or black.

The original function came from a post on Stack Overflow. I just took it and ported from C# to PHP.

Published inCoding

One Comment

  1. Looking at this it would probably make more sense to return either 0 or 255 instead of an array with r, g, and b elements that are all the same anyway.

Leave a Reply

Your email address will not be published. Required fields are marked *