Friday, April 25, 2014

Convert image to base64 string and embed it in html

With just one command, you can take a screenshot and encode it in base64 string, then get the the output in this form of img tag:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..."/>

This python script depends on kdialog and deepin-scrot , you can use other similar tools, feel free to modify it to suit your own needs. Licensed under GPL v2!

Convert image to base64 string and embed it in html
#!/usr/bin/python3

import base64
import os, sys, time
import subprocess


if(len(sys.argv) == 1):
    fpath = "/tmp/" + str(time.time()) + ".png"
    subprocess.call(["deepin-scrot", "-o", fpath])
else:
    fpath = sys.argv[1]

with open(fpath, "rb") as fh:
    pngcode  = base64.b64encode(fh.read()).decode()

fn,extn = os.path.splitext(fpath)
htmlstring = """<img src="data:image/{};base64,{}"/>""".format(extn, pngcode)
htmlTempfile = "/tmp/imgBase64Temp.html"
with open(htmlTempfile, "w") as fh:
    fh.write(htmlstring)

with open(htmlTempfile, "r") as fh:
    p = subprocess.Popen(["xsel", "-b"], stdin=fh)
    p.wait()

os.system("kdialog --title Screenshot --passivepopup 'Encoded to html/base64!'")

0 comments: