/ Published in: PHP
Turn a HEX colour value into its 3 character equivalent.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/*-------------------------------------------------------------------- * * Turn a HEX colour value into its 3 character equivalent. * * The colour of the shorthand will differ slightly from the original * in some cases. This is because we loose half the storage capacity, * from 6 to 3 nibbles (24 to 12 bits). * */ function hex_to_shorthand($hex, $uppercase=true) { // Remove preceding hash if present // If it already is shorthand, nothing more to do here // If it is not 6 characters long then it is invalid // The final shorthand HEX value $final = ""; // Get the triplets // Go over each triplet separately foreach ($triplets as $t) { // Get the decimal equivalent of triplet // Find the remainder $remainder = $dec % 17; // Go to the nearest decimal that will yield a double nibble $new = ($dec%17 > 7) ? 17+($dec-$remainder) : $dec-$remainder; // Convert decimal into HEX // Add one of the two identical nibbles $final .= $hex[0]; } // Return the shorthand HEX colour value } /*-------------------------------------------------------------------- * * 25 samples... * */ echo "<style>p{margin:0;padding:.75em;font-size:1.4em;}</style>"; for ($i=0; $i<25; $i++) { . "8888899999FFFFFEEEEEDDDDDCCCCCBBBBBAAAAA"), 0, 6); $newcolor = hex_to_shorthand($original); echo "<p style='background:#$original;'>Longhand: <b>#$original</b></p>"; echo "<p style='background:#$newcolor;'>Shorthand: <b>#$newcolor</b></p>"; echo "<br>"; }