Copy base64 version of file to your clipboard
Oftentimes we want to include files as a base-64'd data URI, rather than a path to the resource itself.
Build tools like Grunt can automate this process – but occasionally you'll want/need to process individual files.
My old workflow often involved converting the file online, or converting via command line and then manually removing the newline characters… so I decided to make it quick and painless.
The Bash Function
Just add this function to your .bashrc
:
function b64() {
cat $1 | base64 | pbcopy;
}
And now you can b64 filename
in any directory, and its base64'd contents will be copied to your clipboard.
Enjoy!
Notes
Nick Douma thoughtfully suggested that I use base64
instead of openssl
, as it's more widely supported on *nix systems.
Previously the function looked like this…
function b64() {
openssl base64 -in $1 | tr -d "\n" | pbcopy;
}
My openssl
implementation also required that I strip newline characters from the output – however with base64
there is no such need.
Written by Derryl Carter
Related protips
4 Responses
Why use this solution, which depends on OpenSSL, while base64 is a builtin command on many Unixes:
cat image.png | base64 -w0
My simple reply is... there's no good reason :-P
I've always used the openssl
command. I wasn't aware that base64
was available as a standalone executable.
Thanks for sharing. I'll probably switch to this technique instead – as it's more terse and removes an extra step from the process.
By default there is no base64 installed on Mac machines. But python and OpenSSL is installed on almost every unix derivat.
So please keep it general with OpenSSL command.
It was available on mine – presumably by default, as I don't recall ever installing it. Feel free to use whichever version is supported by your system