CompileNix's Blog - generate data url on the terminal

Start Page | RSS Feed | Find Stuff

Create a data URL from a file

function get-dataurl {
    local mimeType
    mimeType=$(file -b --mime-type "$1")
    if [[ $mimeType == text/* ]]; then
        mimeType="${mimeType};charset=utf-8"
    fi
    echo "data:${mimeType};base64,$(openssl base64 -in "$1" | tr -d '\n')"
}

Usage examples: get-dataurl /path/to/file.png | less get-dataurl /path/to/file.png | xclip -selection clipboard get-dataurl /path/to/file.png >file.txt