Last active
August 29, 2015 14:04
-
-
Save GhostToast/2439f1d2913a7672524d to your computer and use it in GitHub Desktop.
Hex Conversions and Comparisons
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
/** | |
* Convert hex to decimal, taking care of '#' and length, for comparing hex values | |
* | |
* @param $hex | |
* | |
* @return number | |
*/ | |
public function hex2dec( $hex ) { | |
if ( empty( $hex ) ) { | |
return $hex; | |
} | |
if ( '#' == substr( $hex, 0, 1 ) ) { | |
$temp_hex = trim( $hex, '#' ); | |
} else { | |
$temp_hex = $hex; | |
} | |
if ( 3 == strlen( $temp_hex ) ) { | |
$temp_rgb = str_split( $temp_hex, 1 ); | |
$rgb = array( | |
$temp_rgb[0], | |
$temp_rgb[0], | |
$temp_rgb[1], | |
$temp_rgb[1], | |
$temp_rgb[2], | |
$temp_rgb[2], | |
); | |
$decimal = hexdec( implode( '', $rgb ) ); | |
} elseif ( 6 == strlen( $temp_hex ) ) { | |
$decimal = hexdec( $temp_hex ); | |
} else { | |
return $hex; | |
} | |
return $decimal; | |
} |
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
/** | |
* Tint hex color by a percentage | |
* | |
* @param string $hex - #FFFFFF or FFF | |
* @param int $percentage - Positive or negative | |
* | |
* @return string Returns modified $hex, lighter or darker | |
*/ | |
public function hex_tint( $hex, $percentage=0 ) { | |
if ( empty( $hex ) || 0 == $percentage || ! is_int( $percentage ) ) { | |
return $hex; | |
} | |
if ( '#' == substr( $hex, 0, 1 ) ) { | |
$temp_hex = trim( $hex, '#' ); | |
$trimmed = true; | |
} else { | |
$temp_hex = $hex; | |
$trimmed = false; | |
} | |
if ( 3 == strlen( $temp_hex ) ) { | |
$temp_rgb = str_split( $temp_hex, 1 ); | |
$rgb = array( | |
$temp_rgb[0], | |
$temp_rgb[0], | |
$temp_rgb[1], | |
$temp_rgb[1], | |
$temp_rgb[2], | |
$temp_rgb[2], | |
); | |
$rgb = str_split( implode( $rgb ), 2 ); | |
} elseif ( 6 == strlen( $temp_hex ) ) { | |
$rgb = str_split( $temp_hex, 2 ); | |
} else { | |
return $hex; | |
} | |
foreach ( $rgb as $key => $value ) { | |
$value = hexdec( $value ); | |
// modify by percentage, keep in range of 0-255, turn back into hexadecimal and padd with 0s for length | |
$value = str_pad( dechex( max( min( ( ( ( $percentage / 100 ) * 255 ) + $value ), 255 ), 0 ) ), 2, '0', STR_PAD_LEFT ); | |
$rgb[$key] = $value; | |
} | |
$hex = ( $trimmed ? '#' : '' ).implode( $rgb ); | |
return $hex; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment