Wednesday, June 3, 2009

I've finally realized the merits of standalone SVG files using data URIs, so I wrote this simple Python script to convert an SVG with >image xlink:href="filename" ... /< to one with data URIs instead.

from sys import stderr, argv, exit
from base64 import b64encode
from os.path import isfile
from mimetypes import init, guess_type
from xml.dom.ext.reader import Sax2
from xml.dom.ext import Print

mp = '', 'href'

if len(argv) == 2:
fname = argv[1]
# Input
with open(fname) as f:
doc = Sax2.Reader().fromStream(f)
# Replace
root = doc.documentElement
imgs = root.getElementsByTagName('image')
for img in imgs:
href = img.getAttributeNS(*mp)
if isfile(href):
mtype = guess_type(href)[0]
b64data = None
with open(href) as f:
b64data = b64encode(
if not b64data is None:
img.setAttributeNS(*mp, value = ''.join(['data:', mtype, ';base64,', b64data]))
print >>stderr, 'Unable to generate Base64 data:', href
print >>stderr, 'Unable to find image:', href
# Output
if fname[-4:] == '.svg':
fname = fname[:-4] + '.standalone' + fname[-4:]
fname = fname + '.standalone.svg'

with open(fname, 'w') as f:
Print(doc, stream = f)
print >>stderr, 'Usage: %s file.svg' % argv[0]
Post a Comment