gists/2013.python.embed-png-in-css-as-datauri.py

27 lines
728 B
Python
Raw Normal View History

2025-05-03 18:48:38 +02:00
#!/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()