Last active
September 28, 2024 14:50
-
-
Save sebdesign/a65cc39e3bcd81201609e6a8087a83b3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<?php | |
class Color | |
{ | |
/** | |
* Convert a hex color to RGB. | |
* | |
* @param string $hex #BADA55 | |
* @return array{int,int,int} [186, 218, 85] | |
*/ | |
public static function rgb(string $hex): array | |
{ | |
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(int $r, int $g, int $b): float | |
{ | |
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(string $C1, string $C2): float | |
{ | |
$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); | |
} | |
} | |
} |
Author
sebdesign
commented
Jul 11, 2016
Hi, I think there is an issue, a contrast ratio between #ffffff
and #bada55
is 1.58:1 https://webaim.org/resources/contrastchecker/?fcolor=ffffff&bcolor=BADA55
This is correct:
return Color::relativeLuminance('#000000', '#bada55') >= 4.5; // Return true
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment