Skip to content

Instantly share code, notes, and snippets.

@wayneashleyberry
Created October 17, 2012 14:06
Show Gist options
  • Save wayneashleyberry/3905676 to your computer and use it in GitHub Desktop.
Save wayneashleyberry/3905676 to your computer and use it in GitHub Desktop.
php color manipulation
<?php
function hex2rgb( $col ) {
if ( $col[0] == '#' ) {
$col = substr( $col, 1 );
}
if (strlen( $col ) == 6) {
list( $r, $g, $b ) = array( $col[0] . $col[1], $col[2] . $col[3], $col[4] . $col[5] );
} elseif (strlen( $col ) == 3) {
list( $r, $g, $b ) = array( $col[0] . $col[0], $col[1] . $col[1], $col[2] . $col[2] );
} else {
return false;
}
$r = hexdec( $r );
$g = hexdec( $g );
$b = hexdec( $b );
return array($r, $g, $b);
}
function hex2rgba( $hex, $a ) {
$arr = hex2rgb($hex);
$str = "rgba($arr[0],$arr[1],$arr[2],$a)";
return $str;
}
function rgb2hex( $arr ) {
$new = array();
$new[0] = (string) dechex($arr[0]);
$new[1] = (string) dechex($arr[1]);
$new[2] = (string) dechex($arr[2]);
foreach($new as $k => $v) {
if (strlen($v) === 1)
$new[$k] = "0$v";
}
return '#' . $new[0] . $new[1] . $new[2];
}
function darken( $hex, $steps ) {
$arr = hex2rgb($hex);
$r = max(0, min(255,$arr[0] - $steps) );
$g = max(0, min(255,$arr[1] - $steps) );
$b = max(0, min(255,$arr[2] - $steps) );
$rgb = array($r,$g,$b);
return rgb2hex($rgb);
}
function lighten( $hex, $steps ) {
$arr = hex2rgb($hex);
$r = max(0, min(255,$arr[0] + $steps) );
$g = max(0, min(255,$arr[1] + $steps) );
$b = max(0, min(255,$arr[2] + $steps) );
$rgb = array($r,$g,$b);
return rgb2hex($rgb);
}
@andrewrcollins
Copy link

Check out my mix(), tint(), tone(), and shade() PHP functions: https://gist.github.com/andrewrcollins/4570993

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