Skip to content

Instantly share code, notes, and snippets.

@earthboundkid
Created September 3, 2019 13:02
Show Gist options
  • Save earthboundkid/b72142d9c6a89b837385015e68d62687 to your computer and use it in GitHub Desktop.
Save earthboundkid/b72142d9c6a89b837385015e68d62687 to your computer and use it in GitHub Desktop.
For SVG files with bloated PNG embeds
def xtract_pngs_from_svgs(name):
fname = name +'.svg'
#
with open(fname) as f:
raw = f.read()
#
prefix = 'xlink:href="data:image/png;base64,'
suffix = '"'
chunks = []
found = []
pos = 0
#
while True:
start = raw.find(prefix, pos)
if start == -1:
chunks.append(raw[pos:])
break
#
startwithprefix = start+len(prefix)
end = raw.index(suffix, startwithprefix)
chunks.append(raw[pos:startwithprefix])
chunks.append("REPLACEME")
found.append(raw[startwithprefix:end])
pos = end
#
blank_svg = ''.join(chunks)
with open(name+'-blank.svg', 'w') as f:
f.write(blank_svg)
#
pngs = (base64.urlsafe_b64decode(chunk) for chunk in found)
for n, png in enumerate(pngs):
with open(f'{name}-{n}.png', 'wb') as f:
f.write(png)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment