Skip to content

Instantly share code, notes, and snippets.

@navix
Forked from stephenharris/color_luminance.php
Created February 2, 2016 13:22
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 navix/d059516b6f4e0e91886d to your computer and use it in GitHub Desktop.
Save navix/d059516b6f4e0e91886d to your computer and use it in GitHub Desktop.
Lighten or darken a given colour
<?php
/**
* Lightens/darkens a given colour (hex format), returning the altered colour in hex format.7
* @param str $hex Colour as hexadecimal (with or without hash);
* @percent float $percent Decimal ( 0.2 = lighten by 20%(), -0.4 = darken by 40%() )
* @return str Lightened/Darkend colour as hexadecimal (with hash);
*/
function color_luminance( $hex, $percent ) {
// validate hex string
$hex = preg_replace( '/[^0-9a-f]/i', '', $hex );
$new_hex = '#';
if ( strlen( $hex ) < 6 ) {
$hex = $hex[0] + $hex[0] + $hex[1] + $hex[1] + $hex[2] + $hex[2];
}
// convert to decimal and change luminosity
for ($i = 0; $i < 3; $i++) {
$dec = hexdec( substr( $hex, $i*2, 2 ) );
$dec = min( max( 0, $dec + $dec * $percent ), 255 );
$new_hex .= str_pad( dechex( $dec ) , 2, 0, STR_PAD_LEFT );
}
return $new_hex;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment