Python How to Convert Image to Base64 String
base64.b64encode() to encode it, then decode to get a string like this: base64.b64encode(open('image.png', 'rb').read()).decode().Examples
How to Think About It
Algorithm
Code
import base64 with open('image.png', 'rb') as image_file: encoded_string = base64.b64encode(image_file.read()).decode() print(encoded_string)
Dry Run
Let's trace converting a small image file 'test.png' with bytes [137, 80, 78, 71].
Open file in binary mode
Open 'test.png' to read bytes [137, 80, 78, 71]
Read bytes
Read bytes: b'\x89PNG'
Encode to base64
base64.b64encode(b'\x89PNG') -> b'iVBORw=='
Decode to string
b'iVBORw==' decoded to 'iVBORw=='
| Step | Operation | Value |
|---|---|---|
| 1 | Read bytes | [137, 80, 78, 71] |
| 2 | Base64 encode | b'iVBORw==' |
| 3 | Decode to string | 'iVBORw==' |
Why This Works
Step 1: Read image as bytes
The image file is opened in binary mode to get the exact bytes without any change.
Step 2: Encode bytes to base64
Base64 encoding converts binary data into ASCII characters, making it safe to transmit or store as text.
Step 3: Decode bytes to string
The encoded base64 bytes are decoded to a string so you can use it easily in text-based formats.
Alternative Approaches
import base64 with open('image.png', 'rb') as f: data = f.read() encoded = base64.standard_b64encode(data).decode() print(encoded)
import base64 from io import BytesIO from PIL import Image img = Image.new('RGB', (10, 10), color='red') buffer = BytesIO() img.save(buffer, format='PNG') encoded = base64.b64encode(buffer.getvalue()).decode() print(encoded)
Complexity: O(n) time, O(n) space
Time Complexity
Reading the entire image file and encoding it takes time proportional to the file size n.
Space Complexity
The base64 string requires extra space proportional to the input size, about 4/3 times the original bytes.
Which Approach is Fastest?
Using built-in base64.b64encode is efficient and fast; alternatives like in-memory conversion add overhead but are useful for special cases.
| Approach | Time | Space | Best For |
|---|---|---|---|
| base64.b64encode from file | O(n) | O(n) | Simple file to base64 conversion |
| base64.standard_b64encode | O(n) | O(n) | Explicit standard base64 encoding |
| In-memory BytesIO with PIL | O(n) | O(n) | Images created or manipulated in memory |