Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python Image Encoding in Data URI Scheme Base 64. #python #base64
data_uri = open("sample.png", "rb").read().encode("base64").replace("\n", "")
# HTML Image Element
img_tag = '<img alt="" src="data:image/png;base64,{0}">'.format(data_uri)
print img_tag
# CSS Background Image
css = 'background-image: url(data:image/png;base64,{0});'.format(data_uri)
print css
@SonOfLilit

This comment has been minimized.

Copy link

SonOfLilit commented May 12, 2015

Could be useful to the next guy googling this:

import glob
import os
import png

output = []
for path in glob.glob('*.png'):
    name = os.path.basename(path)[:-4]
    raw = open(path, "rb").read()
    width, height, _, _ = png.Reader(bytes=raw).read()
    data = raw.encode("base64").replace("\n", "")
    output.append('''.%(name)s {
  height: %(height)dpx;
  width: %(width)dpx;
  background-image: url(data:image/png;base64,%(data)s);
}
''' % locals())
print '\n'.join(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.