Skip to content

Instantly share code, notes, and snippets.

@cheeaun
Created October 2, 2009 08:30
Show Gist options
  • Save cheeaun/199557 to your computer and use it in GitHub Desktop.
Save cheeaun/199557 to your computer and use it in GitHub Desktop.
Color class for Kohana
<?php defined('SYSPATH') or die('No direct script access.');
class Color {
public static function hex_to_rgb($hex){
$pattern = '/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/';
preg_match($pattern, $hex, $matches);
$matches = array_slice($matches, 1);
if (!function_exists('map')){
function map($value){
if (strlen($value) == 1) $value += $value;
return base_convert($value, 16, 10);
}
}
$rgb = array_map('map', $matches);
return $rgb;
}
public static function hsb_to_rgb($hsb){
$br = round($hsb[2] / 100 * 255);
if ($hsb[1] == 0){
return array($br, $br, $br);
} else {
$hue = $hsb[0] % 360;
$f = $hue % 60;
$p = round(($hsb[2] * (100 - $hsb[1])) / 10000 * 255);
$q = round(($hsb[2] * (6000 - $hsb[1] * $f)) / 600000 * 255);
$t = round(($hsb[2] * (6000 - $hsb[1] * (60 - $f))) / 600000 * 255);
switch (floor($hue / 60)){
case 0: return array($br, $t, $p);
case 1: return array($q, $br, $p);
case 2: return array($p, $br, $t);
case 3: return array($p, $q, $br);
case 4: return array($t, $p, $br);
case 5: return array($br, $p, $q);
}
}
return false;
}
public static function rgb_to_hsb($rgb){
$red = $rgb[0];
$green = $rgb[1];
$blue = $rgb[2];
$hue = 0;
$max = max($red, $green, $blue);
$min = min($red, $green, $blue);
$delta = $max - $min;
$brightness = $max / 255;
$saturation = ($max != 0) ? $delta/$max : 0;
if ($saturation != 0){
$rr = ($max - $red) / $delta;
$gr = ($max - $green) / $delta;
$br = ($max - $blue) / $delta;
if ($red == $max) $hue = $br - $gr;
else if ($green == $max) $hue = 2 + $rr - $br;
else $hue = 4 + $gr - $rr;
$hue /= 6;
if ($hue < 0) $hue++;
}
return array(round($hue * 260), round($saturation * 100), round($brightness * 100));
}
public static function hsb_to_hex($hsb){
$rgb = Color::hsb_to_rgb($hsb);
return ($rgb) ? Color::rgb_to_hex($rgb) : false;
}
public static function rgb_to_hex($rgb){
$r = dechex($rgb[0]);
$g = dechex($rgb[1]);
$b = dechex($rgb[2]);
return '#' . strtoupper($r . $g . $b);
}
public static function text_to_hex($text, $brightness=100){
$hex = substr(md5($text), 0, 6);
$rgb = color::hex_to_rgb($hex);
$hsb = color::rgb_to_hsb($rgb);
if ($hsb[1] > 50){
$hsb[0] -= 10;
$hsb[1] -= 30;
} else {
$hsb[0] += 10;
$hsb[1] += 10;
}
$hsb[2] = $brightness;
$hex = color::hsb_to_hex($hsb);
return $hex;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment