Last active
April 26, 2017 06:13
-
-
Save CyberStrike/35c8e947233756d0b3a385acf91564e6 to your computer and use it in GitHub Desktop.
PHP Color Functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function rgbToHsl(int $r,int $g, int $b ) { | |
$oldR = $r; | |
$oldG = $g; | |
$oldB = $b; | |
$r /= 255; | |
$g /= 255; | |
$b /= 255; | |
$max = max( $r, $g, $b ); | |
$min = min( $r, $g, $b ); | |
$h; | |
$s; | |
$l = ( $max + $min ) / 2; | |
$d = $max - $min; | |
if( $d == 0 ){ | |
$h = $s = 0; // achromatic | |
} else { | |
$s = $d / ( 1 - abs( 2 * $l - 1 ) ); | |
switch( $max ){ | |
case $r: | |
$h = 60 * fmod( ( ( $g - $b ) / $d ), 6 ); | |
if ($b > $g) { | |
$h += 360; | |
} | |
break; | |
case $g: | |
$h = 60 * ( ( $b - $r ) / $d + 2 ); | |
break; | |
case $b: | |
$h = 60 * ( ( $r - $g ) / $d + 4 ); | |
break; | |
} | |
} | |
return array(max(ceil($h), 0), max(round($s, 2), 0), max(round($l, 2), 0)); | |
} | |
function hslToRgb( int $h, int $s, int $l ){ | |
$r; | |
$g; | |
$b; | |
$c = ( 1 - abs( 2 * $l - 1 ) ) * $s; | |
$x = $c * ( 1 - abs( fmod( ( $h / 60 ), 2 ) - 1 ) ); | |
$m = $l - ( $c / 2 ); | |
if ( $h < 60 ) { | |
$r = $c; | |
$g = $x; | |
$b = 0; | |
} else if ( $h < 120 ) { | |
$r = $x; | |
$g = $c; | |
$b = 0; | |
} else if ( $h < 180 ) { | |
$r = 0; | |
$g = $c; | |
$b = $x; | |
} else if ( $h < 240 ) { | |
$r = 0; | |
$g = $x; | |
$b = $c; | |
} else if ( $h < 300 ) { | |
$r = $x; | |
$g = 0; | |
$b = $c; | |
} else { $r = $c; $g = 0; $b = $x; } | |
$r = ( $r + $m ) * 255; | |
$g = ( $g + $m ) * 255; | |
$b = ( $b + $m ) * 255; | |
return array( max(ceil($r), 0), max(ceil($g), 0), max(ceil($b), 0) ); | |
} | |
function adjustRGB(string $type, string $rgbString, int $amount){ | |
// covert string to array | |
$rgb = explode(',', $rgbString); | |
// convert to HSL | |
$hsl = rgbToHsl($rgb[0], $rgb[1], $rgb[2]); | |
// Extract to named variables | |
$hue = $hsl[0]; | |
$saturation = $hsl[1]; | |
switch ($type): | |
case 'darken': | |
$lightness = ($hsl[2] - $amount); // Convert to decimal; | |
break; | |
case 'brighten': | |
$lighteness = ($hsl[2] + $amount); // Convert to decimal; | |
break | |
endswitch; | |
// Convert Back to RGB | |
return $darkenedRGB = hslToRgb($hue, $saturation, $lightness); | |
}; | |
function darkenRGB(string $rgbString, int $amount){ | |
return adjustRGB('darken', $rgbString, $amount); | |
}; | |
function brightenRGB(string $rgbString, int $amount){ | |
return adjustRGB('brighten', $rgbString, $amount); | |
}; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment