Forked from andrewrcollins/mix_tint_tone_shade.php
Last active
February 20, 2021 18:57
-
-
Save thegroovetrain/d18972a9232449968dd08f2db85faa82 to your computer and use it in GitHub Desktop.
Color Mixing, Tint, Tone, and Shade in PHP
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 mix($color_1 = array(0, 0, 0), $color_2 = array(0, 0, 0), $weight = 0.5) | |
{ | |
$f = function($x) use ($weight) { return (1 - $weight) * $x; }; | |
$g = function($x) use ($weight) { return $weight * $x; }; | |
$h = function($x, $y) { return round($x + $y); }; | |
return array_map($h, array_map($f, $color_1), array_map($g, $color_2)); | |
} | |
function tint($color, $weight = 0.5) | |
{ | |
$t = (is_string($color) ? hex2rgb($color) : $color); | |
$u = mix($t, array(255,255,255), $weight); | |
return (is_string($color) ? rgb2hex($u) : $u); | |
} | |
function tone($color, $weight = 0.5) | |
{ | |
$t = (is_string($color) ? hex2rgb($color) : $color); | |
$u = mix($t, array(128,128,128), $weight); | |
return (is_string($color) ? rgb2hex($u) : $u); | |
} | |
function shade($color, $weight = 0.5) | |
{ | |
$t = (is_string($color) ? hex2rgb($color) : $color); | |
$u = mix($t, array(0,0,0), $weight); | |
return (is_string($color) ? rgb2hex($u) : $u); | |
} | |
function hex2rgb($hex = "#000000") | |
{ | |
$f = function($x) { return hexdec($x); }; | |
return array_map($f, str_split(str_replace("#", "", $hex), 2)); | |
} | |
function rgb2hex($rgb = array(0, 0, 0)) | |
{ | |
$f = function($x) { return str_pad(dechex($x), 2, "0", STR_PAD_LEFT); }; | |
return "#" . implode("", array_map($f, $rgb)); | |
} | |
print_r("#67ff34"); | |
echo "\n"; | |
print_r(hex2rgb("#67ff34")); | |
echo "\n"; | |
print_r(rgb2hex(hex2rgb("#67ff34"))); | |
echo "\n"; | |
print_r(tint("#67ff34")); | |
echo "\n"; | |
print_r(tone("#67ff34")); | |
echo "\n"; | |
print_r(shade("#67ff34")); | |
echo "\n"; | |
print_r(shade(hex2rgb("#67ff34"))); | |
echo "\n"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment