Skip to content

Instantly share code, notes, and snippets.

@BrendonKoz
Created October 26, 2015 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrendonKoz/ed38c9964afe34065a69 to your computer and use it in GitHub Desktop.
Save BrendonKoz/ed38c9964afe34065a69 to your computer and use it in GitHub Desktop.
<?php
/**
* Convert RGB colors array into HSL array
*
* @param array $ RGB colors set
* @return array HSL set
*/
function rgb_to_hsl($color){
list($r, $g, $b) = is_array($color) ? $color : hex_to_rgb($color);
$round_to = 1;
$clrR = $r;
$clrG = $g;
$clrB = $b;
$clrMin = min($clrR, $clrG, $clrB);
$clrMax = max($clrR, $clrG, $clrB);
$deltaMax = $clrMax - $clrMin;
$L = ($clrMax + $clrMin) / 510;
if (0 == $deltaMax){
$H = 0;
$S = 0;
}
else{
if (0.5 > $L){
$S = $deltaMax / ($clrMax + $clrMin);
}
else{
$S = $deltaMax / (510 - $clrMax - $clrMin);
}
if ($clrMax == $clrR) {
$H = ($clrG - $clrB) / (6.0 * $deltaMax);
}
else if ($clrMax == $clrG) {
$H = 1/3 + ($clrB - $clrR) / (6.0 * $deltaMax);
}
else {
$H = 2 / 3 + ($clrR - $clrG) / (6.0 * $deltaMax);
}
if (0 > $H) $H += 1;
if (1 < $H) $H -= 1;
$H = round($H * 360, $round_to);
$S = round($S * 100 . '%', $round_to);
$L = round($L * 100 . '%', $round_to);
}
return array($H, $S, $L);
}
function hex_to_rgb($hex) {
$hex = str_replace('#', '', $hex);
$hex = (strlen($hex) == 3) ? $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2] : substr(str_pad($hex, 6, '0', STR_PAD_LEFT), 0, 6);
// bitwise conversion
$colorval = hexdec($hex);
$r = 0xFF & $colorval >> 0x10;
$g = 0xFF & $colorval >> 0x8;
$b = 0xFF & $colorval;
return array($r, $g, $b);
}
list($h, $s, $l) = rgb_to_hsl('#CC2801');
// Alpha transparency (0-1)
$a = .75;
echo "Hue: $h" . '<br />';
echo "Saturation: $s" . '<br />';
echo "Lightness: $l" . '<br />';
echo '<div style="width:40px; height:2em; border:1px solid #000; background-color:hsl('."{$h}, {$s}%, {$l}%".')"></div>';
$l += 10;
echo '<div style="width:40px; height:2em; border:1px solid #000; background-color:hsla('."{$h}, {$s}%, {$l}%, $a".')"></div>';
@BrendonKoz
Copy link
Author

Converts a string in to RGB color profiles.
No additional work has been done to verify contrast, brightness, hue, etc...

// 32-char options: md2, md4, md5, ripemd128,
// tiger128,3, tiger128,4, haval128,3, haval128,4, haval128,5
$fullhash = hash('ripemd128', $string);
$colors = str_split($fullhash, 8); // values for R, G, B, A
foreach ($colors as $i => $hash) {
    $colors[$i] = dechex(bcmod(hexdec($hash), 255));
}

list($r, $g, $b, $a) = $colors;
return array($r . $g . $b, $a);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment