Skip to content

Instantly share code, notes, and snippets.

@docwhat
Created March 27, 2023 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save docwhat/22851841570e07e7563f72f6e7ba384c to your computer and use it in GitHub Desktop.
Save docwhat/22851841570e07e7563f72f6e7ba384c to your computer and use it in GitHub Desktop.
Just a simple algorithm for figuring out colors based on a string hash
#!/bin/bash
#
# Usage: ./run.bash $(sort --random-sort /usr/share/dict/words| head -n10 ) | tee /tmp/foo.html
set -euo pipefail
function string_to_color_hex {
local -r string="$1"
local -r hash=$(echo -n "$string" | md5sum | cut -d' ' -f1)
local -ir r=$((16#${hash:0:2}))
local -ir g=$((16#${hash:2:2}))
local -ir b=$((16#${hash:4:2}))
local -ir luma=$(printf "%0.0f" "$(bc -e "0.299 * $r + 0.587 * $g + 0.114 * $b")")
local text_color
if (( luma > 128 )); then
text_color=black
else
text_color=white
fi
readonly text_color
printf '<p style="color: %s; background-color: #%02x%02x%02x; text-align: center;">%s</p>\n' "$text_color" "$r" "$g" "$b" "$string"
}
echo '<html>'
for string in "$@"; do
string_to_color_hex "$string"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment