Jump to content

Compare 2 #xxxxxx colour values to ensure text on bacground would look ok


Recommended Posts

I need to check if 2 colours are not similar.

 

Colour 1 is the background.

Colour 2 is the text.

 

So if I have red text on white background, this is fine. However, yellow on white is not ideal etc.

 

I am sure there must be a script to compare the #FFFFFF values as I know somehow they mean something.

 

Any ideas?

Nothing yet.

 

Imagine just a form where a user chooses 2 colours. I then need php to check it to ensure they are suitable.

 

As these colours will then be used to display text as mentioned, 1 as background, 1 as text - it is important they are checked to ensure the text can be seen reasonably well.

I'm not really sure.  If the user input the colors then you can store them in PHP variables and find an algorithm on google to compare these hex colors but this is a bit complex to make sure what colors don't look good together because it's a matter of opinion.  Sorry, maybe someone else has a more promising answer for you .

Convert to decimal, and make a minimum difference. This will only work for light/dark though... as #FF0000 text and #0000FF background technically have a '0' difference. To get by this you may want to have a minimum difference per channel and combine that with an overall difference... though personally i think solid red text on a solid blue background is just ugly.

 

<?php

$text = '#FFFF00';
$bg = '#000000';

$minDeviation = 400;

$textRGB = hex2rgb( $text );
$bgRGB = hex2rgb( $bg );

if( abs(array_sum($textRGB)-array_sum($bgRGB)) < $minDeviation )
echo 'Colors are too similar';
else
echo 'Colors are different enough';

function hex2rgb ( $hex ) {
if ( substr($hex,0,1) === '#' )
	$hex = substr($hex,1);
if ( strlen($hex) !== 6 )
	return FALSE;
return array(
	'r' => hexdec( substr($hex,0,2) ),
	'g' => hexdec( substr($hex,2,2) ),
	'b' => hexdec( substr($hex,4,2) )
);
}
?>

PERFECT, thanks discomatt.

 

My concern is purely not being able to see the text.

 

Pink on green, red on blue, no problem - as long as it can be read.

 

I dropped the $minDeviation a little and it is exactly what I was looking for.

 

Thanks for all help.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.