When you need to transmit binary data (like an image file or a compiled executable) through a purely text-based protocol (like JSON or an email system), the raw binary code will immediately corrupt and break the data stream. To safely embed binary files inside text-only formats, you must convert the raw data into a continuous string of standard ASCII characters using the Base64 encoding standard. In Linux, you can instantly perform this mathematical conversion using the built-in base64 command.
How to Encode a File to Base64
The base64 command is incredibly simple and is installed by default on almost every modern Linux distribution as part of the GNU coreutils package.
To convert a small image (e.g., logo.png) into a safe, text-only Base64 string, simply run:
base64 logo.png
The terminal will instantly vomit a massive, chaotic wall of alphanumeric characters (like iVBORw0KGgoAAAANSUhEUgAA...). This long string of gibberish is the exact binary data of the image, perfectly represented using only 64 safe ASCII characters.
Because printing the data directly to your terminal screen is rarely useful, you should always redirect the output into a new text file:
base64 logo.png > encoded_logo.txt
You can now safely copy the entire contents of encoded_logo.txt and paste it directly into an HTML file or a JSON payload without any fear of data corruption.
How to Decode Base64 Back to Binary
When you receive a Base64 string from a server or an API, you must reverse the process to reconstruct the original, usable file (such as restoring the image or the executable script).
To decode a text file containing Base64 data back into its original binary form, you must use the -d (decode) flag.
base64 -d encoded_logo.txt > restored_logo.png
The command will read the chaotic string of characters, perform the reverse mathematical translation, and output a perfectly intact, identical copy of the original .png file to your hard drive.
Encoding Raw Text Strings
You can also use the command to quickly encode short strings of text (like a password or an API key) directly in the terminal without using any physical files. You do this by piping the output of the echo command directly into base64.
echo -n "MySecretPassword" | base64
(Note: You must always use the -n flag with echo to prevent it from injecting an invisible newline character into your password before encoding it, which would completely corrupt the final Base64 string).