Longhand HEX colour to shorthand equivalent


/ Published in: PHP
Save to your folder(s)

Turn a HEX colour value into its 3 character equivalent.


Copy this code and paste it in your HTML
  1. /*--------------------------------------------------------------------
  2.  *
  3.  * Turn a HEX colour value into its 3 character equivalent.
  4.  *
  5.  * The colour of the shorthand will differ slightly from the original
  6.  * in some cases. This is because we loose half the storage capacity,
  7.  * from 6 to 3 nibbles (24 to 12 bits).
  8.  *
  9.  */
  10. function hex_to_shorthand($hex, $uppercase=true)
  11. {
  12. // Remove preceding hash if present
  13. if ($hex[0] == "#") $hex = substr($hex, 1);
  14.  
  15. // If it already is shorthand, nothing more to do here
  16. if (strlen($hex) == 3) return "#$hex";
  17.  
  18. // If it is not 6 characters long then it is invalid
  19. elseif (strlen($hex) !== 6) return "";
  20.  
  21. // The final shorthand HEX value
  22. $final = "";
  23.  
  24. // Get the triplets
  25. $triplets = str_split($hex, 2);
  26.  
  27. // Go over each triplet separately
  28. foreach ($triplets as $t)
  29. {
  30. // Get the decimal equivalent of triplet
  31. $dec = base_convert($t, 16, 10);
  32.  
  33. // Find the remainder
  34. $remainder = $dec % 17;
  35.  
  36. // Go to the nearest decimal that will yield a double nibble
  37. $new = ($dec%17 > 7) ? 17+($dec-$remainder) : $dec-$remainder;
  38.  
  39. // Convert decimal into HEX
  40. $hex = base_convert($new, 10, 16);
  41.  
  42. // Add one of the two identical nibbles
  43. $final .= $hex[0];
  44. }
  45. // Return the shorthand HEX colour value
  46. return $uppercase ? strtoupper($final) : strtolower($final);
  47. }
  48.  
  49. /*--------------------------------------------------------------------
  50.  *
  51.  * 25 samples...
  52.  *
  53.  */
  54. echo "<style>p{margin:0;padding:.75em;font-size:1.4em;}</style>";
  55. for ($i=0; $i<25; $i++) {
  56. $original = substr(str_shuffle("0000011111222223333344444555556666677777"
  57. . "8888899999FFFFFEEEEEDDDDDCCCCCBBBBBAAAAA"), 0, 6);
  58. $newcolor = hex_to_shorthand($original);
  59. echo "<p style='background:#$original;'>Longhand: <b>#$original</b></p>";
  60. echo "<p style='background:#$newcolor;'>Shorthand: <b>#$newcolor</b></p>";
  61. echo "<br>";
  62. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.