Last Updated: February 25, 2016
·
604
· sukima

Convert file contents to Data URI format

Simple bash function to convert a file to Data URI format. (outputs to stdout)

datauri() {
  local type=$(file -0 --mime-type "$1" | cut -f 2 -d ' ')
  cat <(printf "data:${type};base64,") <(base64 "$1")
}

Usage:

$ datauri /path/to/image.png > image.datauri
$ echo "<img src=\"$(datauri /path/to/image.png)\">" > image_tag.html
$ datauri /path/to/image.png | pbcopy # Mac OS X clipboard