Intro
During the development of my BitBar plugin (ShiftStats), I had to convert quite a lot of icons to base64 strings. Because I've been using Icons8 as my main source for icons it really bothered me to download every icon to then convert them. Those tiny png files started cluttering up my workspace rather quickly and I never used any of them again. Why not delete them? Well... that's a good point, but I have this terrible habit of just downloading those kinds of "temporary files" into whatever path the "save at"-dialog is at that very moment, so they end up not just in the downloads folder, but pretty much everywhere.
So my plan was to make a very simple python script, that can convert any image from a URL into a base64 string.
Requirements
We need python 3.4,requests
to get stuff from URLs, base64
to do the conversion as well as sys
and io
.
The Python script
This time the script is very VERY short. Just 14 lines in total:
import requests, base64, sys
from io import BytesIO
try:
url=sys.argv[1]
except IndexError:
url="https://i.stack.imgur.com/r390N.png"
buffered = BytesIO(requests.get(url).content)
img_base64 = base64.b64encode(buffered.getvalue())
print(img_base64.decode())
Going over the lines real quick:
1-3 Are our imports, as always. In line 5 to 8 we check whether an argument has been supplied or not. If not, just use a hardcoded URL. I used the standard "broken image" icon
On line 9 we write the stream of the image into our buffer.
On line 10 we convert the bytes from said buffer to Base64.
And finally print it to stdout
We could now go ahead and call out script with a URL as the first argument:
$ python3.4 imgurl2base64.py http://minzkraut.com/content/images/2016/11/logo-m-3.png
And get it in Base64
iVBORw0KGgoAAAANSUhEUgAAAaoAAAGqCAYAAABajwD2AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4AsXCg0DQb5FNAAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAgAElEQVR42uy9+ZMs13Xn9z33ZmbtVb3vy+v99eu3Ag8gAAIEARIASYgUN40oUSSDkiyJ0lgKz8gzEXb4B4d/8BLhsP8Ex4xiHOGwHWE7HLZnQqMZTYgSJe4ECBDAA/D2td/rfanKvNc/5FI3szKrsvp19+vqvieioqurt+qqzPvJ7znfew5Bhw4d7QTt8++T+iXVoaN5GPol0KGjLfjQEXi+Gm46NKh06DhhIOo0UGmo6dAnsA4dx/B43svX6DEeSwsLuY8/cxC/Q4cO... ... and so on
This code on GitHub https://github.com/JanGross/imgurl2base64
Thats it.
So simple, yet so handy.