Skip to content

Instantly share code, notes, and snippets.

@chaoswey
Last active July 22, 2019 01:48
Show Gist options
  • Save chaoswey/fa3ee016d02d17a7352dc1ce12416f75 to your computer and use it in GitHub Desktop.
Save chaoswey/fa3ee016d02d17a7352dc1ce12416f75 to your computer and use it in GitHub Desktop.
php 判斷 hex color 然後回傳 白色 or 黑色
/**
* @param $hexColor
* @return string
*/
function getContrastColor($hexColor)
{
$R1 = hexdec(substr($hexColor, 1, 2));
$G1 = hexdec(substr($hexColor, 3, 2));
$B1 = hexdec(substr($hexColor, 5, 2));
$blackColor = "#000000";
$R2BlackColor = hexdec(substr($blackColor, 1, 2));
$G2BlackColor = hexdec(substr($blackColor, 3, 2));
$B2BlackColor = hexdec(substr($blackColor, 5, 2));
$L1 = 0.2126 * pow($R1 / 255, 2.2) +
0.7152 * pow($G1 / 255, 2.2) +
0.0722 * pow($B1 / 255, 2.2);
$L2 = 0.2126 * pow($R2BlackColor / 255, 2.2) +
0.7152 * pow($G2BlackColor / 255, 2.2) +
0.0722 * pow($B2BlackColor / 255, 2.2);
$contrastRatio = ($L1 > $L2)
? (int)(($L1 + 0.05) / ($L2 + 0.05))
: (int)(($L2 + 0.05) / ($L1 + 0.05));
return ($contrastRatio > 5)
? '#000000'
: '#FFFFFF';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment