color-utils.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php declare( strict_types = 1 ); ?>
  2. <?php
  3. // These functions are borrowed from the colorline lib
  4. if ( ! function_exists( 'hex_to_rgb' ) ) {
  5. function hex_to_rgb( $hex ) {
  6. return sscanf( $hex, '%02X%02X%02X' );
  7. }
  8. }
  9. // RGB values: 0-255
  10. // LUM values: 0-1
  11. if ( ! function_exists( 'rgb_to_lum' ) ) {
  12. function rgb_to_lum( $rgb ) {
  13. list( $r, $g, $b ) = $rgb;
  14. return sqrt( 0.241 * $r * $r + 0.691 * $g * $g + 0.068 * $b * $b ) / 255;
  15. }
  16. }
  17. // RGB values: 0-255, 0-255, 0-255
  18. // HSV values: 0-360, 0-100, 0-100, 0-100
  19. if ( ! function_exists( 'rgb_to_hsvl' ) ) {
  20. function rgb_to_hsvl( $rgb ) {
  21. $l = rgb_to_lum( $rgb );
  22. list( $r, $g, $b ) = $rgb;
  23. $r = $r / 255;
  24. $g = $g / 255;
  25. $b = $b / 255;
  26. $max_rgb = max( $r, $g, $b );
  27. $min_rgb = min( $r, $g, $b );
  28. $chroma = $max_rgb - $min_rgb;
  29. $v = 100 * $max_rgb;
  30. if ( $chroma > 0 ) {
  31. $s = 100 * ( $chroma / $max_rgb );
  32. if ( $r === $min_rgb ) {
  33. $h = 3 - ( ( $g - $b ) / $chroma );
  34. } elseif ( $b === $min_rgb ) {
  35. $h = 1 - ( ( $r - $g ) / $chroma );
  36. } else { // $g === $min_rgb
  37. $h = 5 - ( ( $b - $r ) / $chroma );
  38. }
  39. $h = 60 * $h;
  40. return array( $h, $s, $v, $l );
  41. } else {
  42. return array( 0, 0, $v, $l );
  43. }
  44. }
  45. }
  46. if ( ! function_exists( 'change_color_luminescence' ) ) {
  47. function change_color_luminescence( $hex, $amount ) {
  48. $hex_without_hash = substr( $hex, 1, strlen( $hex ) );
  49. $rgb = hex_to_rgb( $hex_without_hash );
  50. $hsvl = rgb_to_hsvl( $rgb );
  51. return 'hsl( ' . $hsvl[0] . ',' . $hsvl[1] . '%,' . ( $hsvl[2] + $amount ) . '%)';
  52. }
  53. }