Skip to content

Instantly share code, notes, and snippets.

@ProjectCleverWeb
Created July 19, 2016 19:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ProjectCleverWeb/9df684226ac86fc22c7254a4bf7f238e to your computer and use it in GitHub Desktop.
Save ProjectCleverWeb/9df684226ac86fc22c7254a4bf7f238e to your computer and use it in GitHub Desktop.
Simple and very accurate function to check the contrast of 2 RGB colors. (uses YIQ weights)
/**
* Measures the visual contrast of 2 RGB colors.
*
* NOTE: most colors do not have a 100% contrasting opposite, but all colors
* do have a contrasting opposite that is at least 50%.
*
* @param array $rgb1 The first color, array where offsets 'r', 'g', & 'b' contain their respective values.
* @param array $rgb2 The second color, array where offsets 'r', 'g', & 'b' contain their respective values.
* @return float The visual contrast as a percentage (e.g. 12.345)
*/
function rgb_contrast($rgb1, $rgb2) {
$r = (max($rgb1['r'], $rgb2['r']) - min($rgb1['r'], $rgb2['r'])) * 299;
$g = (max($rgb1['g'], $rgb2['g']) - min($rgb1['g'], $rgb2['g'])) * 587;
$b = (max($rgb1['b'], $rgb2['b']) - min($rgb1['b'], $rgb2['b'])) * 114;
// Sum => Average => Convert to percentage
return ($r + $g + $b) / 1000 / 2.55;
}
@ProjectCleverWeb
Copy link
Author

Please note that the only good way to check 2 colors perceived contrast is with the RGB spectrum. This because human eyes work by using red, blue, and green sensory cones to distinguish colors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment