Advertisement
Guest User

Untitled

a guest
Apr 21st, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. function hexToHsl($hex) {
  2. $hex = array($hex[0].$hex[1], $hex[2].$hex[3], $hex[4].$hex[5]);
  3. $rgb = array_map(function($part) {
  4. return hexdec($part) / 255;
  5. }, $hex);
  6.  
  7. $max = max($rgb);
  8. $min = min($rgb);
  9.  
  10. $l = ($max + $min) / 2;
  11.  
  12. if ($max == $min) {
  13. $h = $s = 0;
  14. } else {
  15. $diff = $max - $min;
  16. $s = $l > 0.5 ? $diff / (2 - $max - $min) : $diff / ($max + $min);
  17.  
  18. switch($max) {
  19. case $rgb[0]:
  20. $h = ($rgb[1] - $rgb[2]) / $diff + ($rgb[1] < $rgb[2] ? 6 : 0);
  21. break;
  22. case $rgb[1]:
  23. $h = ($rgb[2] - $rgb[0]) / $diff + 2;
  24. break;
  25. case $rgb[2]:
  26. $h = ($rgb[0] - $rgb[1]) / $diff + 4;
  27. break;
  28. }
  29.  
  30. $h = round($h * 60);
  31. }
  32.  
  33. return array($h, $s, $l);
  34. }
  35.  
  36. function hslToHex($hsl)
  37. {
  38. list($h, $s, $l) = $hsl;
  39.  
  40. if ($s == 0) {
  41. $r = $g = $b = 1;
  42. } else {
  43. $q = $l < 0.5 ? $l * (1 + $s) : $l + $s - $l * $s;
  44. $p = 2 * $l - $q;
  45.  
  46. $r = hue2rgb($p, $q, $h + 1/3);
  47. $g = hue2rgb($p, $q, $h);
  48. $b = hue2rgb($p, $q, $h - 1/3);
  49. }
  50.  
  51. return rgb2hex($r) . rgb2hex($g) . rgb2hex($b);
  52. }
  53.  
  54. function hue2rgb($p, $q, $t) {
  55. if ($t < 0) $t += 1;
  56. if ($t > 1) $t -= 1;
  57. if ($t < 1/6) return $p + ($q - $p) * 6 * $t;
  58. if ($t < 1/2) return $q;
  59. if ($t < 2/3) return $p + ($q - $p) * (2/3 - $t) * 6;
  60.  
  61. return $p;
  62. }
  63.  
  64. function rgb2hex($rgb) {
  65. return str_pad(dechex($rgb * 255), 2, '0', STR_PAD_LEFT);
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement