Last active
June 1, 2024 23:25
-
-
Save flesser/3f9c80ff42879cad41bf to your computer and use it in GitHub Desktop.
Compress embedded png images to jpg in SVG files. (based on https://gist.github.com/jeromerobert/ff34f504acd7feb0306a)
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 python | |
import xml.etree.ElementTree as ET | |
import sys | |
import base64 | |
import os | |
import StringIO | |
from PIL import Image | |
PREFIX_PNG = "data:image/png;base64," | |
PREFIX_JPG = "data:image/jpg;base64," | |
ATTR = "{http://www.w3.org/1999/xlink}href" | |
DEFAULT_NS = "http://www.w3.org/2000/svg" | |
with open(sys.argv[1]) as svgfile: | |
root = ET.parse(svgfile) | |
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_PNG): | |
pngimage = StringIO.StringIO() | |
jpgimage = StringIO.StringIO() | |
pngimage.write(base64.b64decode(href[len(PREFIX_PNG):])) | |
Image.open(pngimage).save(jpgimage, "JPEG") | |
e.set(ATTR, PREFIX_JPG + base64.b64encode(jpgimage.getvalue())) | |
root.write(sys.argv[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the script!
I change a little in Python v3 syntax. svg-compress-embedded-png-v3.py