Basically I'm trying to write a clever single line of commands that outputs base64 encoded strings in place of where there used to be a path to an image. So:
background-image: url(path/to/my/image.png);
…would turn into:
background-image: url(data:image/png;base64,ABvR0…+tC==);
I normally turn an image into its base64 encoded string via:
openssl enc -base64 -in path/to/my/image.png
Which outputs the base64… but with newlines in it. This is fixed by piping it through tr
like:
openssl enc -base64 -in path/to/my/image.png | tr -d '\n'
which just outputs a long base64 encoded string. By using pbcopy (on Mac OS) that gets sent to the clipboard, like so:
openssl enc -base64 -in path/to/my/image.png | tr -d '\n' | pbcopy
Very nice for ad hoc replacing an occasional image with its base64 representation but what I'd like to do is have this automated for replacing all occurrences of url(path/to/whatever.ext)
in a file by their respective base64 strings. Making sure there are only actual paths and no data-uris in there is out of scope here :)
I have been trying to replace stuff with sed
but I got stuck in its horrible documentation. It's not too difficult to find the occurences of the url(…)
pattern in a css file, but the bit between parenthesis needs to be replaced by the output of the above command and I am clueless if this is at all possible. So, there it is, help or some pointers (do I need to look into awk as well?) would be much appreciated! A 'you cannot do this without a proper script' would also do of course :)
openssl
tool#!/bin/bash
awk -F'[()]' -v q="'" '
/background-image: url(.*)/ {
cmd=sprintf("openssl enc -base64 -in %s | tr -d %c\\n%c",$2,q,q)
cmd | getline b64
close(cmd)
$0=$1 "(data:image/png;base64," b64 ");"
}1' /path/to/css/file
See HERE for a working example
base64
tool#!/bin/bash
awk -F'[()]' '
/background-image: url(.*)/ {
cmd=sprintf("base64 -w0 %s",$2)
cmd | getline b64
close(cmd)
$0=$1 "(data:image/png;base64," b64 ");"
}1' /path/to/css/file
See HERE for a working example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With