Apply some of @kvid's suggestions for svgembed.py

Co-authored-by: kvid <kvid@users.noreply.github.com>
This commit is contained in:
Daniel Rojas 2020-12-06 12:54:55 +01:00 committed by GitHub
parent a18550e79e
commit 426c11b766
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -10,20 +10,13 @@ mime_subtype_replacements = {'jpg': 'jpeg', 'tif': 'tiff'}
def embed_svg_images(svg_in: str, base_path: Path):
# first, find any image references in SVG data, and cache the respective base64-encoded image
images_b64 = {} # cache of base64-encoded images
re_xlink=re.compile(r"xlink:href=\"(?P<URL>.*?)\"", re.IGNORECASE)
re_xlink=re.compile(r'xlink:href="(?P<URL>.*?)"', re.IGNORECASE)
for xlink in re_xlink.finditer(svg_in):
imgurl = xlink.group('URL')
if not imgurl in images_b64: # only encode/cache every unique URL once
if not Path(imgurl).is_absolute():
imgurl_abs = (Path(base_path) / imgurl).resolve()
else:
imgurl_abs = Path(imgurl)
with open(imgurl_abs,'rb') as img:
img_bin = img.read()
img_b64 = base64.b64encode(img_bin)
img_str = img_b64.decode('utf-8')
images_b64[imgurl] = img_str
images_b64[imgurl] = base64.b64encode(imgurl_abs.read_bytes()).decode('utf-8')
# second, replace links with the base64-encoded data
svg_out = svg_in
for url, b64 in images_b64.items():
@ -33,16 +26,15 @@ def embed_svg_images(svg_in: str, base_path: Path):
def get_mime_subtype(filename: Path):
mime_subtype = str(Path(filename).suffix[1:]).lower() # remove `.`
mime_subtype = filename.suffix.lstrip('.').lower()
if mime_subtype in mime_subtype_replacements:
mime_subtype = mime_subtype_replacements[mime_subtype]
return mime_subtype
def embed_svg_images_file(filename_in: Path, overwrite: bool = True):
filename_in = Path(filename_in).resolve()
filename_out = Path(f'{filename_in.with_suffix("")}.b64.svg')
with open(filename_in,'r') as file_in, open(filename_out,'w') as file_out:
file_out.write(embed_svg_images(file_in.read(), filename_in.parent))
filename_in = filename_in.resolve()
filename_out = filename_in.with_suffix('.b64.svg')
filename_out.write_text(embed_svg_images(filename_in.read_text(), filename_in.parent))
if overwrite:
filename_out.replace(filename_in)