Encode an SVG file using base64 encoding

Public, Command Line, Tricks, Other Languages


Created: Sep 22, 2016     Updated: Sep 22, 2016

Here is how to encode an SVG file, using base64 encoding, and then leverage the encoded string to set an element's background-image property to the SVG file in question.

1 - Open up an irb session
2 - Read the file into a variable, using the path to the SVG file

files_content = File.read("/Users/harrylevine/Downloads/message-like-assets/MessageLikeBadge.svg")

3 - Load/require the base64 module

$ require "base64"

4 - Encode the file

$ encoded_file = Base64.encode64(files_content)

5 - Remove the new line character

$ cleaned_file = encoded_file.gsub("\n", "")

The cleaned_file is going to be a very long string of alphanumeric characters (i.e. PD94bWwgdmVyc2lv....)

6 - Set the CSS of the element in question like this:

#div-in-question {
  background-image: url("data:image/svg+xml;base64,PD94bWwgdmVyc2lv....");