Python How to Convert Base64 to Image File
base64 module to decode the base64 string and write the bytes to an image file with open('filename', 'wb'). For example: open('image.png', 'wb').write(base64.b64decode(base64_string)).Examples
How to Think About It
Algorithm
Code
import base64 base64_string = 'iVBORw0KGgoAAAANSUhEUgAAAAUA' image_data = base64.b64decode(base64_string) with open('output.png', 'wb') as file: file.write(image_data) print('Image saved as output.png')
Dry Run
Let's trace decoding a short base64 string and saving it as an image file.
Decode base64 string
Input string 'iVBORw0KGgoAAAANSUhEUgAAAAUA' is decoded to bytes like b'\x89PNG\r\n\x1a\n\x00\x00\x00\r\nIHDR\x00\x00\x00\x05\x00'
Write bytes to file
Open 'output.png' in binary write mode and write the decoded bytes.
| Step | Action | Value |
|---|---|---|
| 1 | Decode base64 | b'\x89PNG\r\n\x1a\n\x00\x00\x00\r\nIHDR\x00\x00\x00\x05\x00' |
| 2 | Write to file | 'output.png' created with image bytes |
Why This Works
Step 1: Decode base64 string
The base64.b64decode() function converts the base64 text back into the original binary image data.
Step 2: Write binary data to file
Opening a file in binary write mode 'wb' allows saving the raw bytes exactly as they are, recreating the image.
Alternative Approaches
import base64 from io import BytesIO from PIL import Image base64_string = 'iVBORw0KGgoAAAANSUhEUgAAAAUA' image_data = base64.b64decode(base64_string) image = Image.open(BytesIO(image_data)) image.save('output_pil.png') print('Image saved as output_pil.png')
import base64 from pathlib import Path base64_string = 'iVBORw0KGgoAAAANSUhEUgAAAAUA' image_data = base64.b64decode(base64_string) Path('output_pathlib.png').write_bytes(image_data) print('Image saved as output_pathlib.png')
Complexity: O(n) time, O(n) space
Time Complexity
Decoding base64 and writing bytes both process each byte once, so time grows linearly with input size.
Space Complexity
The decoded bytes require memory proportional to the image size, so space is linear.
Which Approach is Fastest?
Direct decoding and writing with base64.b64decode and file write is fastest and simplest. Using PIL adds overhead but allows image manipulation.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct decode and write | O(n) | O(n) | Simple conversion to image file |
| PIL with BytesIO | O(n) | O(n) | Image processing before saving |
| Pathlib write_bytes | O(n) | O(n) | Concise file writing |
'wb' to correctly save image bytes.