Skip to content

Instantly share code, notes, and snippets.

@jeromerobert
Last active December 12, 2023 18:46
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeromerobert/ff34f504acd7feb0306a to your computer and use it in GitHub Desktop.
Save jeromerobert/ff34f504acd7feb0306a to your computer and use it in GitHub Desktop.
Extract embedded images from svg
#! /usr/bin/env python3
import xml.etree.ElementTree as ET
import sys
import base64
import os
PREFIX="data:image/png;base64,"
ATTR="{http://www.w3.org/1999/xlink}href"
DEFAULT_NS="http://www.w3.org/2000/svg"
with open(sys.argv[1]) as f:
root = ET.parse(f)
file_id = 1
base_name = os.path.splitext(sys.argv[1])[0]
for e in root.findall(".//{%s}image" % DEFAULT_NS):
href = e.get(ATTR)
if href and href.startswith(PREFIX):
n_file_name = "%s%d.png" % (base_name, file_id)
with open(n_file_name, "wb") as f2:
f2.write(base64.b64decode(href[len(PREFIX):]))
file_id += 1
e.set(ATTR, os.path.basename(n_file_name))
root.write(sys.argv[1])
@flesser
Copy link

flesser commented Mar 9, 2016

Thanks for the script!
I used it as base for my script to compress embedded png images into jpg in svg files.

@UndarkAido
Copy link

Thank you so much! I accidentally hit ctrl+s in Inkscape after opening a png, and this got it back!

@aizquier
Copy link

Thank you! This saved my day!

@norpol
Copy link

norpol commented Jun 25, 2019

I had to replace line 18 with open(n_file_name, "w") as fp: with with open(n_file_name, "wb") as fp: to get it working.

The automatic patching of the svg is also nice, but make sure to create a backup!

@jeromerobert
Copy link
Author

@norpol updated, thanks.

@bio-james
Copy link

Useful script, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment