Wednesday, June 3, 2009

svg_standalone.py

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.

svg_standalone.py

#!/usr/bin/python
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 = 'http://www.w3.org/1999/xlink', 'href'
init()

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(f.read())
if not b64data is None:
img.setAttributeNS(*mp, value = ''.join(['data:', mtype, ';base64,', b64data]))
else:
print >>stderr, 'Unable to generate Base64 data:', href
else:
print >>stderr, 'Unable to find image:', href
# Output
if fname[-4:] == '.svg':
fname = fname[:-4] + '.standalone' + fname[-4:]
else:
fname = fname + '.standalone.svg'

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

No comments: