At some point I found myself wanting to convert a PNG image to Base64 to embed it in a stylesheet. I’m not a big fan of online tools, therefore I decided to check if there is a CLI (command-line interface) available. Turns out it’s already installed on your machine if you’re using a Mac.

Since I couldn’t find all the information right away, this is a complete writeup of the information I needed.

Converting the image

# Go to the image location, e.g. on your desktop
cd ~/Desktop
# Convert the image to Base64 and store the result in a TXT file
base64 image.png > image.txt

Embedding the image in your stylesheet

/* embed the image in your css */
.body{
    background-image:url(data:image/png;base64,/* paste the contents of your TXT file here */);
}

To use this for different filetypes by replacing image/png string with a valid MIME type:

  • image/gif
  • image/jpeg
  • image/png
  • image/svg+xml
  • image/tiff
  • image/webp

A word of caution

  • A Base64 encoded image filesize is larger than the original image.
  • There is a size limit for the data URI, which varies per browser. The lowest limit is 32768 bytes (IE8).
  • In most use cases it’s better to use regular images (due to caching & performance). In general, embedded images are great for small images that are used often.
  • Don’t use this technique if you need to support versions prior to IE8.

Please check out the Sources below for more details.


Sources