In this post, I will share a simple script I wrote for converting image to Base64.
- I was working on a project that requires using
react.jsbut 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 pyperclipbefore running this code.
- If you are encoding a local image, specify the path of
local_imgand delete the line of
- Make sure your file format is consistent throughout the
Well, it copies a string like this to your clipboard:
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: