To restore “Base64 encoded strings” received from Web APIs or email attachments back to their original binary data (images, PDFs, audio files, etc.), use the b64decode() function from the standard base64 module.
This article explains how to decode a received Base64 string and save it as a PNG image file.
Implementation Example: Restoring and Saving Data
In this scenario, we assume we received a Base64 string from a server. We will decode it and save it locally as restored_image.png.
Source Code
import base64
# 1. Base64 string to decode
# (In reality, this would be a very long string from an API response)
# We use short dummy data here as an example
received_b64_str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
# 2. Decode Base64 string to binary data (bytes)
# b64decode() accepts str or bytes and returns decoded bytes
decoded_data = base64.b64decode(received_b64_str)
# 3. Open the file in binary write mode ('wb') and save
# Use 'wb' (Write Binary) instead of 'w' because this is not text
output_filename = "restored_image.png"
try:
with open(output_filename, "wb") as f:
f.write(decoded_data)
print(f"Saved successfully: {output_filename}")
print(f"File size: {len(decoded_data)} bytes")
except Exception as e:
print(f"Failed to save: {e}")
Execution Result
Saved successfully: restored_image.png
File size: 70 bytes
Explanation
base64.b64decode(s)
This function accepts a Base64 format string (or bytes) and converts it into the original binary data (bytes type). If the input string contains invalid characters or lacks padding (the = at the end), a binascii.Error may occur.
File Mode ‘wb’ (Write Binary)
Decoded data is binary data, such as images or audio. When writing this to a file, you must specify the "wb" mode.
- “w”: Text write mode. (This performs character encoding conversions, so it is not suitable for binary data.)
- “wb”: Binary write mode. (Writes the raw data exactly as is.)
Important Note: Removing the Header
If you receive data in the Data URI Scheme format (like data:image/png;base64,iVBORw...) from a web application, the header part (data:image/...;base64,) is not part of the Base64 body. You must remove this header (by replacing it or slicing the string) before decoding.
