February 5, 2013

Base64 encode an image from the command line in OS X

I frequently use base64 encoding to include small images inline in my CSS. This helps me avoid loading lots of small images or managing an image sprite. Luckily, there's a super easy native command line tool in Mac OS X to do this. Use it like so:
openssl base64 -A -in your-image.png
If your image file is valid, your Terminal will generate a base64 string. You can then drop this into your CSS as a background-image or as the src of an img tag. You simply need to prepend the base64 string with the following header string:
In the 2 cases, your code would look something like this:
/* CSS */
#container {
  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAbCAYAAABr/T8RAAAB8qpOejw03OsRMxMR8RDujjC14YwEWEg/bF/6glXHxYm2JTCa4xRxoT/gW5/67s0Hu88AAAAABJRU5ErkJggg==")
<!-- HTML -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAbCAYAAABr/T8RAAAB8qpOejw03OsRMxMR8RDujjC14YwEWEg/bF/6glXHxYm2JTCa4xRxoT/gW5/67s0Hu88AAAAABJRU5ErkJggg==" />