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).
import base64, urllib, pyperclip
url = "https://brand.cornell.edu/assets/images/examples/trademarks/brand_registered.svg"
local_img = "convert.svg" # Dummy local file name
urllib.request.urlretrieve(url, local_img) # Save the image to local
with open(local_img, "rb") as img_file:
base64_ = base64.b64encode(img_file.read()) # Encode to base64
base64_string = base64_.decode('utf-8') # Otherwise output is enclosed with b''
pyperclip.copy(base64_string)
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: