Skip to content

Instantly share code, notes, and snippets.

@madr
Created April 4, 2013 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madr/5309403 to your computer and use it in GitHub Desktop.
Save madr/5309403 to your computer and use it in GitHub Desktop.
Embed Images as data-URIs in CSS files
#!/usr/bin/env python
import base64, re, argparse
parser = argparse.ArgumentParser(description='CSS-Embed PNG images as data-URIs')
parser.add_argument('files', metavar='file', nargs="+", type=str,
help='path to a css file')
img = re.compile("url\('?\"?(.*\.png)'?\"?\)")
repl = "url(data:image/png;base64,%s)"
cssfiles = parser.parse_args().files
if "swapcase" in dir(["a"]):
cssfiles = [cssfiles]
for cssfile in cssfiles:
css = open(cssfile, "r").read()
for image_path in img.findall(css):
data = base64.b64encode(open(image_path, "r").read())
pattern = "url\('?\"?%s'?\"?\)" % image_path
css = re.sub(re.compile(pattern), repl % data, css)
f = open(cssfile, "w")
f.write(css)
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment