Last active
          February 1, 2025 06:47 
        
      - 
      
- 
        Save devhammed/7de59f89bf09ed514b00e89242f57bce to your computer and use it in GitHub Desktop. 
    Calculating Color Contrast using YIQ
  
        
  
    
      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
    
  
  
    
  | 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'; | |
| } | 
  
    
      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
    
  
  
    
  | 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