Last active
August 12, 2024 21:26
-
-
Save jeromerobert/ff34f504acd7feb0306a to your computer and use it in GitHub Desktop.
Extract embedded images from svg
This file contains hidden or 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
#! /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]) |
Thank you so much! I accidentally hit ctrl+s in Inkscape after opening a png, and this got it back!
Thank you! This saved my day!
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!
@norpol updated, thanks.
Useful script, thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the script!
I used it as base for my script to compress embedded png images into jpg in svg files.