Created
March 2, 2020 14:23
-
-
Save XavierTolza/69229e2a88db7ee561a2570088585c21 to your computer and use it in GitHub Desktop.
Embed HTML images
This file contains 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
#!python3 | |
import re | |
from argparse import ArgumentParser | |
from base64 import b64encode | |
from os.path import basename, abspath, dirname, join | |
parser = ArgumentParser() | |
parser.add_argument("filename") | |
args = parser.parse_args() | |
folder = dirname(abspath(args.filename)) | |
with open(args.filename, "r") as fp: | |
data = fp.read() | |
for im, alt in re.findall('<img src="(.{,100})" alt="()">', data): | |
with open(join(folder, im), "rb") as fp: | |
imb64 = b64encode(fp.read()) | |
ext = ".".join(basename(im).split(".")[1:]) | |
data = data.replace(im, f'data:image/{ext};base64,{imb64.decode("utf-8")}') | |
with open(args.filename, "w") as fp: | |
fp.write(data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment