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]) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
I had to replace line
18with open(n_file_name, "w") as fp:withwith 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!