Skip to content

Instantly share code, notes, and snippets.

@0x79H
Created November 30, 2022 09:15
Show Gist options
  • Save 0x79H/23bb99778683685fa34d6d38c38eae9b to your computer and use it in GitHub Desktop.
Save 0x79H/23bb99778683685fa34d6d38c38eae9b to your computer and use it in GitHub Desktop.
markdown_img_to_base64.py
import re, pathlib, base64
from urllib.parse import unquote
_re = re.compile(b"!\[[^\[\]]*\]\(([^\(\)]+)\)")
_template = b"data:image/{{FORMAT}};base64,{{DATA}}"
def markdown_img_to_base64(_input, _output=None):
assert _output
with open(_input, "rb") as f1:
ff1=f1.read()
for i in _re.findall(ff1):
_path = unquote(i.decode())
_p1 = pathlib.Path(_path)
_ext = _p1.suffix.strip(".")
_b64_file = _template
with open(_p1,"rb") as f:
_b64_file = _b64_file.replace(b"{{DATA}}", base64.b64encode(f.read()))\
.replace(b"{{FORMAT}}", _ext.encode())
ff1 = ff1.replace(i,_b64_file)
with open(_output, "wb") as f2:
f2.write(ff1)
_input = './test.md'
_output = './test_embed.md'
markdown_img_to_base64(_input, _output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment