Created
September 3, 2019 13:02
-
-
Save earthboundkid/b72142d9c6a89b837385015e68d62687 to your computer and use it in GitHub Desktop.
For SVG files with bloated PNG embeds
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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