Skip to content

Instantly share code, notes, and snippets.

@Kodiologist
Forked from Matjaz-B/embedder.py
Last active June 12, 2019 15:54
Show Gist options
  • Save Kodiologist/57716792103f315e5e3d541e12498268 to your computer and use it in GitHub Desktop.
Save Kodiologist/57716792103f315e5e3d541e12498268 to your computer and use it in GitHub Desktop.
Embed images into an HTML document with data URIs
#!/usr/bin/env python3
"""
Embed images into an HTML document
"""
import base64, mimetypes, re, sys
## from https://gist.github.com/jsocol/1089733
def img_to_data(path):
"""Convert a file (specified by a path) into a data URI."""
with open(path, 'rb') as o:
img_data = o.read()
return 'data:{};base64,{}'.format(
mimetypes.guess_type(path)[0],
base64.b64encode(img_data).decode('ASCII'))
if __name__ == '__main__':
html = sys.stdin.read()
for path in [x[0] or x[1] for x in re.findall(
r'''<\s*img[^>]*?\ssrc\s*=\s*(?:"([^"]+)"|'([^']+)')''',
html, flags = re.IGNORECASE)]:
html = html.replace(path, img_to_data(path))
print(html, end = '')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment