All Articles Kinsa Creative

Encode SVG Images into CSS with Python using Base64 Encoding

When changing icons on hover state for example, avoid the flash of unstyled content while the file is retrieved by encoding it directly into the stylesheet.

In Python, open and encode a SVG file into Base64:

import base64
f=open('/path/to/file.svg', 'r')
base64.b64encode(f.read().encode('utf-8'))

Copy the byte string output, that is, everything between b' and the closing '.

In CSS, use that as the background image for an element, replacing eggs with the copied byte string value:

spam {
    background: url('data:image/svg+xml;base64,eggs') no-repeat right center; 
}

Run it as a script. Create a file named encode_images.py and add the following:

import base64
import getopt
import sys

def main(argv):
    helpstr = 'python3 encode_images.py -f "foo.svg bar.svg"'

    try:
        opts, args = getopt.getopt(argv, "hf:", ["files="])
    except getopt.GetoptError:
        print(helpstr)
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print(helpstr)
            sys.exit()
        elif opt in ("-f", "--files"):
            files = arg

            for file in files.split(' '):
                f = open(file, 'r')
                byte_string = base64.b64encode(f.read().encode('utf-8'))
                print(f'background-image: url("data:image/svg+xml;base64,{byte_string.decode("utf-8")}");')


if __name__ == '__main__':
    main(sys.argv[1:])

To run it, provide a space separated list of relative file paths to the -f argument as in python3 encode_images.py -f "foo.svg bar.svg". It will print lines for each file which can be copy-pasted directly into CSS to set background images.

Feedback?

Email us at enquiries@kinsa.cc.