How to Use Base64 in Python
Python's built-in base64 module provides functions for encoding and decoding binary data to Base64. This guide covers everything from basic string encoding to working with images and files.
Basic String Encoding and Decoding
To encode a string to Base64, you first need to convert it to bytes, then useb64encode():
import base64
text = "Hello, World!"
text_bytes = text.encode("utf-8")
base64_bytes = base64.b64encode(text_bytes)
base64_string = base64_bytes.decode("utf-8")
print(base64_string) # SGVsbG8sIFdvcmxkIQ==To decode back:
decoded_bytes = base64.b64decode(base64_string)
decoded_text = decoded_bytes.decode("utf-8")
print(decoded_text) # Hello, World!Encoding Images to Base64
To encode an image file to a Base64 data URI (usable in HTML):
import base64
with open("image.png", "rb") as f:
image_bytes = f.read()
base64_string = base64.b64encode(image_bytes).decode("utf-8")
data_uri = f"data:image/png;base64,{base64_string}"
print(data_uri[:50] + "...") # data:image/png;base64,iVBORw0KGgo...URL-Safe Base64
For URLs and JWT tokens, use URL-safe encoding which replaces + with - and / with _:
url_safe = base64.urlsafe_b64encode(b"Hello, World!")
print(url_safe.decode()) # SGVsbG8sIFdvcmxkIQ==
decoded = base64.urlsafe_b64decode(url_safe)
print(decoded.decode()) # Hello, World!Saving Decoded Base64 to a File
To decode a Base64 string and save it as a binary file:
import base64
base64_string = "iVBORw0KGgoAAAANSUhEUg..." # Your Base64 string here
# Remove data URI prefix if present
if "," in base64_string:
base64_string = base64_string.split(",")[1]
image_bytes = base64.b64decode(base64_string)
with open("decoded-image.png", "wb") as f:
f.write(image_bytes)
print("Image saved as decoded-image.png")Working with Large Files
For large files, process data in chunks to avoid memory issues:
import base64
def encode_large_file(input_path, output_path):
with open(input_path, "rb") as f_in, open(output_path, "w") as f_out:
while chunk := f_in.read(57 * 1024): # 57KB chunks
encoded = base64.b64encode(chunk)
f_out.write(encoded.decode("utf-8"))
encode_large_file("large-file.bin", "encoded.txt")Error Handling
Always handle potential errors when decoding:
import base64
def safe_decode(base64_string):
try:
return base64.b64decode(base64_string).decode("utf-8")
except (base64.binascii.Error, UnicodeDecodeError) as e:
print(f"Error: {e}")
return None
result = safe_decode("invalid-base64!")
# Error: Invalid base64-encoded stringConclusion
Python's base64 module is simple yet powerful. Whether you're encoding strings, images, or large files, the API is consistent and easy to use. Remember to handle encoding/decoding errors gracefully, especially when working with user-provided data.