Last active
March 23, 2021 15:51
-
-
Save liuzhuan/3d2ea201b93a834e3775f54e624c991d to your computer and use it in GitHub Desktop.
Compress png inside svg, in python v3. Based on https://gist.github.com/flesser/3f9c80ff42879cad41bf
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
#!/bin/sh | |
# This is used to process multiple svg files | |
cp -r svg-original svg-compressed | |
cd svg-compressed | |
files=$(ls *.svg) | |
for file in $files | |
do | |
echo $file start | |
../compress.py $file | |
echo $file done | |
done | |
cd .. |
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 | |
import io | |
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 = io.BytesIO() | |
jpgimage = io.BytesIO() | |
pngimage.write(base64.b64decode(href[len(PREFIX_PNG):])) | |
Image.open(pngimage).save(jpgimage, "JPEG", quality=20) | |
e.set(ATTR, PREFIX_JPG + base64.b64encode(jpgimage.getvalue()).decode("utf-8")) | |
root.write(sys.argv[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment