Using Mark Ransom's formula to determine the contrast.
Using arosolino's code to convert the hexadecimal value to Red, Green, Blue values.
Using Mark Ransom's formula to determine the contrast.
Using arosolino's code to convert the hexadecimal value to Red, Green, Blue values.
<?php | |
$hex = "#A0DAA9"; // accepts abc, aabbcc, #abc and #aabbcc. | |
// Split HEX value into Red Green and Blue values | |
list( $r, $g, $b ) = array_map( | |
function ( $c ) { | |
return hexdec( str_pad( $c, 2, $c ) ); | |
}, | |
str_split( | |
ltrim( $hex, '#' ), | |
strlen( $hex ) > 4 ? 2 : 1 ) | |
); | |
// Multiply with industry standards for contrast values | |
$red = ( $r * 0.299 ); | |
$green = ( $g * 0.587 ); | |
$blue = ( $b * 0.114 ); | |
// Combine RGB values | |
$rgb = ( $r * 0.299 ) + ( $g * 0.587 ) + ( $b * 0.114 ); | |
// advised contrast limit for displays | |
$limit = 186; | |
if( $rgb >= $limit ) { | |
// $hex is bright, text should be dark | |
$text = "#000"; | |
} else { | |
// $hex is dark, text should be bright | |
$text = "#fff"; | |
} | |
// Oneliner version | |
$text = ( ( $r * 0.299 ) + ( $g * 0.587 ) + ( $b * 0.114 ) >= 186 ) ? "#000" : "#fff" ; | |
// $text (color) is now a hexadecimal value that is readable on $hex (color). |