Skip to content

Instantly share code, notes, and snippets.

@sweeney
Created April 7, 2010 22:48
Show Gist options
  • Save sweeney/359549 to your computer and use it in GitHub Desktop.
Save sweeney/359549 to your computer and use it in GitHub Desktop.
Use the function 'TagColour' to create a 6 character hex code for a colour that isn't too bright (ie, shows up against white) for any input string. Or, supply an existing colour name (red, blue, green etc) and get it back as a usable code.
<?php
function TagColour($name){
$colours = array('red', 'blue', 'green', 'black', 'brown', 'cyan', 'gold', 'yellow', 'grey', 'gray', 'indigo', 'lime', 'navy', 'yellow', 'orange');
if(in_array(strtolower($name), $colours)){
return strtolower($name);
}
$hex = substr(md5($name), 1, 6);
$intensity = (HexIntensity($hex) / 255) * 100;
$i=0;
while(($intensity > 70) && ($i<10)){
$hex = IntensifyHex($hex);
$intensity = (HexIntensity($hex) / 255) * 100;
$i++;
}
return $hex;
}
function HexIntensity($hex){ //strlen = 6
$colours = HexToRGB($hex);
$brightness = (($colours['r'] * 299) + ($colours['g'] * 587) + ($colours['b'] * 114)) / 1000;
return $brightness;
}
function IntensifyHex($hex){
$c = HexToRGB($hex);
$r = $c['r'];
$g = $c['g'];
$b = $c['b'];
$min = min($r, $g, $b);
$max = max($r, $g, $b);
if($r == $max){
$r = $r * 0.6;
} elseif($g == $max){
$g = $r * 0.6;
} elseif($b == $max){
$b = $b * 0.6;
}
return RGBToHex($r, $g, $b);
}
function HexToRGB($hex){
$hex = str_replace("#", '', $hex);
$colour = array();
$colour['r'] = hexdec(substr($hex, 0, 2));
$colour['g'] = hexdec(substr($hex, 2, 2));
$colour['b'] = hexdec(substr($hex, 4, 2));
return $colour;
}
function RGBToHex($r, $g, $b){
$hex = '';
$rh = dechex($r);
$hex .= (strlen($rh)==1) ? $rh.$rh : $rh;
$rg = dechex($g);
$hex.= (strlen($rg)==1) ? $rg.$rg : $rg;
$rb = dechex($b);
$hex.= (strlen($rb)==1) ? $rb.$rb : $rb;
return substr($hex, 0, 6);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment