Skip to content

Instantly share code, notes, and snippets.

@MattMoony
Created March 19, 2021 15:07
Show Gist options
  • Save MattMoony/8099b31f8427b307e68a04e769d1d750 to your computer and use it in GitHub Desktop.
Save MattMoony/8099b31f8427b307e68a04e769d1d750 to your computer and use it in GitHub Desktop.

Revisions

  1. MattMoony revised this gist Mar 19, 2021. No changes.
  2. MattMoony created this gist Mar 19, 2021.
    42 changes: 42 additions & 0 deletions standalone-markdown.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    #!/usr/bin/env python3

    """
    Title: Standalone Markdown
    Date: March 2021
    Author: mattmoony (https://github.com/MattMoony)
    Short python script that converts a markdown file, which
    requires a path to load images from to a "standalone"
    markdown file which already contains the images using
    HTML img tags and base64 sources.
    """

    import re
    import os
    import sys
    from base64 import b64encode

    def main():
    if len(sys.argv) != 2:
    print(f'[-] Usage: ./{os.path.basename(__file__)} <markdown-file>')
    sys.exit(1)
    fname: str = sys.argv[1]
    bpath: str = os.path.dirname(fname)
    if not os.path.isfile(fname):
    print(f'[-] File "{fname}" doesn\'t exist ... ')
    sys.exit(1)
    with open(fname, 'r') as f:
    with open(f'{".".join(fname.split(".")[:-1])}.standalone.md', 'w') as o:
    c: str = f.read()
    for m in re.findall(r'!\[[^\]]*\]\([^\)]*\)', c):
    iname: str = m.split('(')[1].split(')')[0]
    alt: str = m.split('[')[1].split(']')[0]
    with open(os.path.join(bpath, iname), 'rb') as img:
    base: str = b64encode(img.read()).decode()
    c = c.replace(m, f'<div align="center"><img src="data:image/{iname.split(".")[-1]};base64,{base}" alt="{alt}" /></div>')
    o.write(c)

    if __name__ == '__main__':
    main()