Perl-Sensitive Sunglasses PerlMonks

### Re: Contrasting Colours

by tall_man (Parson)
 on May 29, 2003 at 15:21 UTC ( #261566=note: print w/replies, xml ) Need Help??

Inverting the RGB value (i.e. subtracting each color value from the maximum value) would give a quick-and-dirty contrasting color.

There is also a module Color::Calc that supplies contrast, mix and blend functions.

Replies are listed 'Best First'.
Re: Re: Contrasting Colours
by Rhose (Priest) on May 29, 2003 at 15:33 UTC
Subtracting from the max starts breaking down the closer your color is to "the middle" -- 80 80 80.
Re: Re: Contrasting Colours
by msemtd (Scribe) on May 29, 2003 at 15:48 UTC
Hi, thanks, I took a look at Color::Calc and some old code by Ho-Sheng Hsiao dated 1998-07-07 and came up with the following which seems to work pretty well...
```# given a colour in the form "#ff00ff" i.e. hex rrggbb, return a contr
+asting colour
sub contrast_colour {
my \$col = shift;
# Need rgb values for colour...
if ( not \$col =~ /^#(..)(..)(..)\$/ ) {
warn "failed to convert colour '\$col' to rgb components\n";
return;
}
my ( \$r, \$g, \$b ) = ( hex(\$1), hex(\$2), hex(\$3) );
#~ print "RGB= \$r, \$g, \$b\n";
# here's an idea! simple contrast solution...
my %oppcolors = (
"00" => "FF",
"33" => "FF",
"66" => "FF",
"99" => "FF",
"CC" => "00",
"FF" => "00",
);
\$r = int( \$r / 51 ) * 51;
\$g = int( \$g / 51 ) * 51;
\$b = int( \$b / 51 ) * 51;
#~ print "RGB rounded = \$r, \$g, \$b\n";
\$r = \$oppcolors{ sprintf( "%02X", \$r ) };
\$g = \$oppcolors{ sprintf( "%02X", \$g ) };
\$b = \$oppcolors{ sprintf( "%02X", \$b ) };
#~ print "RGB inverted = \$r, \$g, \$b\n";
return "#\$r\$g\$b";
}

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://261566]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2023-06-09 00:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
How often do you go to conferences?

Results (35 votes). Check out past polls.

Notices?