Created
March 27, 2023 15:08
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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