Created
July 19, 2016 19:28
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.