-
-
Save Kodiologist/57716792103f315e5e3d541e12498268 to your computer and use it in GitHub Desktop.
Embed images into an HTML document with data URIs
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 | |
| """ | |
| 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