file2datauri

#!/bin/sh
# Outputs contents of file argument as data URI.
test -f "$1" || exit 1
MIMETYPE=$(file --brief --mime "$1" | tr -d ' ' | sed -e 's/;charset=binary//')
BASE64=$(base64 --wrap 0 "$1")
URI=$(printf 'data:%s;base64,%s' "$MIMETYPE" "$BASE64")

case $MIMETYPE in text/* | *charset=us-ascii)
  PERCENT=$(od -An -tx1 <"$1" | tr ' ' % | tr -d '\n' | sed -e 's/%2d/-/g;s/%5f/_/g;s/%2e/./g;s/%7e/~/g;s/%41/A/g;s/%42/B/g;s/%43/C/g;s/%44/D/g;s/%45/E/g;s/%46/F/g;s/%47/G/g;s/%48/H/g;s/%49/I/g;s/%4a/J/g;s/%4b/K/g;s/%4c/L/g;s/%4d/M/g;s/%4e/N/g;s/%4f/O/g;s/%50/P/g;s/%51/Q/g;s/%52/R/g;s/%53/S/g;s/%54/T/g;s/%59/Y/g;s/%56/V/g;s/%57/W/g;s/%58/X/g;s/%59/Y/g;s/%5a/Z/g;s/%61/a/g;s/%62/b/g;s/%63/c/g;s/%64/d/g;s/%65/e/g;s/%66/f/g;s/%67/g/g;s/%68/h/g;s/%69/i/g;s/%6a/j/g;s/%6b/k/g;s/%6c/l/g;s/%6d/m/g;s/%6e/n/g;s/%6f/o/g;s/%70/p/g;s/%71/q/g;s/%72/r/g;s/%73/s/g;s/%74/t/g;s/%75/u/g;s/%76/v/g;s/%77/w/g;s/%78/x/g;s/%79/y/g;s/%7a/z/g;s/%30/0/g;s/%31/1/g;s/%32/2/g;s/%33/3/g;s/%34/4/g;s/%35/5/g;s/%36/6/g;s/%37/7/g;s/%38/8/g;s/%39/9/g;')
  URI_2=$(printf 'data:%s,%s' "$MIMETYPE" "$PERCENT")
  [ ${#URI} -ge ${#URI_2} ] && URI=$URI_2
esac

printf '%s\n' $URI | sed 's/data:text\/plain/data:/;s/data:;charset=us-ascii/data:/'