Last active
December 21, 2015 21:58
-
-
Save cointilt/6371830 to your computer and use it in GitHub Desktop.
Color Brightness
This file contains 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 color_brightness($hex, $percent) { | |
// Work out if hash given | |
$hash = ''; | |
if (stristr($hex,'#')) { | |
$hex = str_replace('#','',$hex); | |
$hash = '#'; | |
} | |
/// HEX TO RGB | |
$rgb = array(hexdec(substr($hex,0,2)), hexdec(substr($hex,2,2)), hexdec(substr($hex,4,2))); | |
//// CALCULATE | |
for ($i = 0; $i < 3; $i++) { | |
// See if brighter or darker | |
if ($percent > 0) { | |
// Lighter | |
$rgb[$i] = round($rgb[$i] * $percent) + round(255 * (1-$percent)); | |
} else { | |
// Darker | |
$positivePercent = $percent - ($percent*2); | |
$rgb[$i] = round($rgb[$i] * $positivePercent) + round(0 * (1-$positivePercent)); | |
} | |
// In case rounding up causes us to go to 256 | |
if ($rgb[$i] > 255) { | |
$rgb[$i] = 255; | |
} | |
} | |
//// RBG to Hex | |
$hex = ''; | |
for ($i=0; $i < 3; $i++) { | |
// Convert the decimal digit to hex | |
$hexDigit = dechex($rgb[$i]); | |
// Add a leading zero if necessary | |
if (strlen($hexDigit) == 1) { | |
$hexDigit = "0" . $hexDigit; | |
} | |
// Append to the hex string | |
$hex .= $hexDigit; | |
} | |
return $hash.$hex; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment