Posted by & filed under Coding.

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.

One Response to “Contrasting color function for PHP”

  1. Ryan

    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.

    Reply

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>