Skip to content

Instantly share code, notes, and snippets.

@odil-io
Last active August 2, 2022 07:45
Show Gist options
  • Save odil-io/e4c89a8867948bfb679a8ff1323f96ed to your computer and use it in GitHub Desktop.
Save odil-io/e4c89a8867948bfb679a8ff1323f96ed to your computer and use it in GitHub Desktop.
PHP: determine legibility on different colors

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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment