How do you base-64 encode a PNG image for use in a data-uri in a CSS file?

Viewed 60419

I want to base-64 encode a PNG file, to include it in a data:url in my stylesheet. How can I do that?

I’m on a Mac, so something on the Unix command line would work great. A Python-based solution would also be grand.

7 Answers
import base64

def image_to_data_url(filename):
    ext = filename.split('.')[-1]
    prefix = f'data:image/{ext};base64,'
    with open(filename, 'rb') as f:
        img = f.read()
    return prefix + base64.b64encode(img).decode('utf-8')

b64encode is not installed by default in some distros (@Clint Pachl's answer), but python is.

So, just use:

python -mbase64 image.jpeg | tr -d '\n' > b64encoded.txt

In order to get base64 encoded image from the command line.

The remaining steps were already answered by @Clint Pachl (https://stackoverflow.com/a/20467682/1522342)

This should work in Python3:

from io import BytesIO
import requests, base64

def encode_image(image_url):
    buffered = BytesIO(requests.get(image_url).content)
    image_base64 = base64.b64encode(buffered.getvalue())
    return b'data:image/png;base64,'+image_base64

Call decode to get str as in python3 base64.b64encode returns a bytes instance.

And just for the record, if you want to do it in Node.js instead:

const fs = require('fs');
const base64encodedString = fs.readFileSync('image_file.jpg', {encoding:'base64'});
Related