Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
class Color
{
/**
* Convert a hex color to RGB.
*
* @param string $hex #BADA55
* @return array [186, 218, 85]
*/
public static function rgb ($hex)
{
return sscanf($hex, "#%02x%02x%02x");
}
/**
* Calculate the relative luminance of an RGB color.
*
* @param int $r
* @param int $g
* @param int $b
* @return float
*/
public static function luminance ($r, $g, $b) {
return 0.2126 * pow($r/255, 2.2) +
0.7152 * pow($g/255, 2.2) +
0.0722 * pow($b/255, 2.2);
}
/**
* Calculate the relative luminance of two colors.
*
* @param string $C1 hex color
* @param string $C2 hex color
* @return float
*/
public static function relativeLuminance ($C1, $C2) {
$L1 = self::luminance(...self::rgb($C1));
$L2 = self::luminance(...self::rgb($C2));
if ($L1 > $L2) {
return ($L1 + 0.05) / ($L2 + 0.05);
} else {
return ($L2 + 0.05) / ($L1 + 0.05);
}
}
}
@sebdesign

This comment has been minimized.

Copy link
Owner Author

@sebdesign sebdesign commented Jul 11, 2016

// Check if white text against #bada55 background passes G18.
// https://www.w3.org/TR/2016/NOTE-WCAG20-TECHS-20160317/G18
return Color::relativeLuminance('#ffffff', '#bada55') >= 4.5;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment