Skip to content

Instantly share code, notes, and snippets.

@devhammed
Last active February 1, 2025 06:47
Show Gist options
  • Save devhammed/7de59f89bf09ed514b00e89242f57bce to your computer and use it in GitHub Desktop.
Save devhammed/7de59f89bf09ed514b00e89242f57bce to your computer and use it in GitHub Desktop.
Calculating Color Contrast using YIQ
function getContrastYIQ(string $hexColor): string
{
$hex = str_replace('#', '', $hexColor);
$r = hexdec(substr($hex, 0, 2));
$g = hexdec(substr($hex, 2, 2));
$b = hexdec(substr($hex, 4, 2));
$yiq = (($r * 299) + ($g * 587) + ($b * 114)) / 1000;
return ($yiq >= 128) ? '#000000' : '#ffffff';
}
function getContrastYIQ(hexColor: string): string {
const hex = hexColor.replace('#', '');
const r = parseInt(hex.substr(0, 2), 16);
const g = parseInt(hex.substr(2, 2), 16);
const b = parseInt(hex.substr(4, 2), 16);
const yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
return (yiq >= 128) ? '#000000' : '#ffffff';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment