1. Overview
In this short article, we’re going to see how we can convert an image to Base64. We’ll use the base64 tool available on most Linux distributions for that purpose.
2. Converting an Image to Base64
Sometimes, we might need to encode binary data to transfer over a medium that deals only with textual data. On Linux, we have access to the base64 utility, which can encode and decode a file and display it on the standard output. It’s pretty minimal and easy to use.
The base64 package ships with GNU Coreutils, which is installed on most Linux distros. We can verify it in the terminal simply by issuing the command:
$ base64 --version
base64 (GNU coreutils) 8.32
Copyright (C) 2020 Free Software Foundation, Inc.
2.1. Using the base64 Utility
The syntax for base64 is simple. We run the command base64 followed by options and a file:
$ base64 [OPTIONS]... [FILE]
Let’s convert an image to Base64 and display the result to the standard output:
$ base64 ~/Pictures/book.jpg
/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxAQEhUQEA8VFRUQEBUPFRUVFQ8VFRUVFRUWFhUV
FRUYHSggGBolHRUVITEhJSkrLi4uFx8zODMtNygtLisBCgoKDg0OFxAQGCsiHyUtLS0rLy0rLSst
LS0tLS0rLS0rLSsrLTUrLS0tLS0wLSstLSstLS0rLSstLSstKystK//AABEIAMIBAwMBIgACEQED
EQH/xAAcAAEAAgMBAQEAAAAAAAAAAAAAAQIDBAUHBgj/xABHEAACAQICBQcICAQFAwUAAAAAAQID
...
We can see that it prints the encoded data to the standard output. Of course, the output will be longer, depending on the file size. For clarity, the remaining lines have been omitted.
Moreover, there’s an option –wrap or -w that we can use to limit the output columns. For instance, if we need to limit the width of a line to 56, we can pass it to the –wrap option:
$ base64 --wrap 56 ~/Pictures/book.jpg
/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxAQEhUQEA8VFRUQEBUP
FRUVFQ8VFRUVFRUWFhUVFRUYHSggGBolHRUVITEhJSkrLi4uFx8zODMt
...
On the other hand, passing 0 as the argument will result in a long single-line Base64 string.
2.2. Encoding an Image for HTML
We can write a shell script to create an img element and embed the Base64 data in it. It should detect the image format automatically and use it as the MIME type. We’ll provide it with the image file, and it should print the img element to the standard output:
#!/bin/bash
usage() {
echo "Usage: ./base64img [FILE]"
echo "Formats: APNG BMP GIF JPEG PNG WEBP"
}
# Print usage and exit if the file was not provided
[ $# -eq 0 ] && usage && exit 1
# Grab the image format
fmt=$(file "$1" | grep -iEo 'apng|bmp|gif|jpeg|png|webp' | head -n1 | tr '[:upper:]' '[:lower:]')
# Check if the image format is supported
[ -z "$fmt" ] && usage && exit 1
# Create an IMG template
img="<img src='data:image/"$fmt";base64, $(base64 -w 0 "$1")' />"
echo "$img"
First of all, we write the usage function in case of errors. Then, we grab the image format using the file command and convert it to lowercase. Afterward, we check whether it’s an empty variable because the variable will be empty in case of unsupported formats. Finally, we create a template and print it out to the standard output.
Let’s test it out:
$ ./base64img.sh ~/Pictures/block.png
<img src='data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAABhWlDQ1BJQ0MgcHJvZmlsZQAAKJF9kT1Iw0AYht+mSotULNhBxCFDddGCqIijVqEIFUKt0KqDyaV/0KQhaXFxFFwLDv4sVh1cnHV1cBUEwR8QNzcnRRcp8buk0CLGO457eO97X+6+A4RGmWlW1zig6VUzlYiLmeyqGHhFEGGaowjLzDLmJCkJz/F1Dx/f72I8y7vuz9Gr5iwG+ETiWWaYVeIN4unNqsF5nzjCirJKfE48ZtIFiR+5rrj8xrngsMAzI2Y6NU8cIRYLHax0MCuaGvEUcVTVdMoXMi6rnLc4a+Uaa92TvzCU01eWuU5rCAksYgkSRCiooYQyqojRrpNiIUXncQ//oOOXyKWQqwRGjgVUoEF2/OB/8Lu3Vn5ywk0KxYHuF9v+GAYCu0Czbtvfx7bdPAH8z8CV3vZXGsDMJ+n1thY9Avq2gYvrtqbsAZc7wMCTIZuyI/lpCfk88H5G35QF+m+BnjW3b61znD4AaepV8gY4OARGCpS97vHuYGff/q1p9e8HZDNyobFmBakAAAAJcEhZcwAALiMAAC4jAXilP3YAAAAUSURBVAjXY3SufccAA0wMSAA3BwBUVQG2LRn5IQAAAABJRU5ErkJggg==' />
2.3. Copying the Base64 Contents to the Clipboard
Sometimes, it can be difficult to accurately copy the text from the terminal window. So, we can either save the output to a text file, or we can just copy it to the system clipboard. Luckily, on Linux, we can use a tool called xclip, through which we can access the system clipboard.
The xclip package is not installed on some Linux distributions, but we can install it from the official repository using yum or apt. Once installed, we can use it as given in the following snippet:
$ xclip -selection clipboard file.txt
Let’s break down the above command:
- The -selection option specifies where to copy the contents
- The clipboard argument specifies that we want to copy the contents to the system clipboard
- The last argument is the file that we want to copy from
In our case, we want to copy the Base64 contents from the standard output. Therefore, we will pipe the base64 output to xclip:
$ base64 ~Pictures/block.png | xclip -selection clipboard
This will effectively copy the Base64 data to the clipboard, ready to paste.
3. Conclusion
In this article, we learned how we could use the base64 tool to encode images. We also wrote a small shell script for creating an HTML img tag out of the Base64 data.
Finally, we learned how we could copy the Base64 data from the terminal to the clipboard using xclip.