Last active
February 25, 2019 07:34
-
-
Save ChrisAichinger/b369d80180212a9130b1ea55597e2d4c to your computer and use it in GitHub Desktop.
Embed images in HTML file as dataurl
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/python3 | |
import os | |
import argparse | |
import base64 | |
import mimetypes | |
import re | |
RE = b'src="([^"]*)"' | |
def img_to_data(path): | |
mime, _ = mimetypes.guess_type(path.decode('ascii', errors='replace')) | |
mime = mime.encode('ascii') | |
with open(path, 'rb') as fp: | |
data = fp.read() | |
data64 = b''.join(base64.encodebytes(data).splitlines()) | |
return b'data:%s;base64,%s' % (mime, data64) | |
def subfn(m): | |
fname = m.group(1) | |
dataurl = img_to_data(fname) | |
return b'src="%s"' % (dataurl,) | |
def main(): | |
parser = argparse.ArgumentParser(description='Embed images in HTML file as dataurl') | |
parser.add_argument('input', help='input file name') | |
parser.add_argument('output', help='output file name') | |
args = parser.parse_args() | |
# Chdir to the input HTML directory to correctly resolve relative links. | |
inputfname = os.path.abspath(args.input) | |
outputfname = os.path.abspath(args.output) | |
os.chdir(os.path.dirname(inputfname)) | |
data = open(inputfname, 'rb').read() | |
output = re.sub(RE, subfn, data) | |
with open(outputfname, 'wb') as f: | |
f.write(output) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment