In this post, I will share a simple script I wrote for converting image to Base64.
The Problem
- I was working on a project that requires using
react.js
but currently it does not have a good way to generate self-contained slides. (i.e. if the images you are referencing is on the local computer it would not work.) - So I wanted to simply replace all the image references in my jupyter notebook with base64 encodings of that image.
- This little script would help me on that.
What This Does
- You just give it a url of the image or a local path of the image and run it.
- It automatically copies the base64 encoding of the image to the clipboard.
- Quite neat, huh?
Show Me The Code!
- You might need to run
pip install pyperclip
before running this code. - If you are encoding a local image, specify the path of
local_img
and delete the line ofurllib.request.urlretrieve(url, local_img)
. - Make sure your file format is consistent throughout the
url
,local_img
, andsrc
(later).
The Results
Well, it copies a string like this to your clipboard:
PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWx...
Which does not really make sense.
However, once you insert this string into the following HTML label depending on your file type (In this example, svg):
<img src="data:image/svg+xml;base64, YOUR_STRING_HERE">
<img src="data:image/jpg;base64, YOUR_STRING_HERE">
<img src="data:image/png;base64, YOUR_STRING_HERE">
We should be able to see an image like this: