0
0
PythonHow-ToBeginner · 2 min read

Python How to Convert Image to Base64 String

To convert an image to base64 in Python, open the image file in binary mode, read its content, and use base64.b64encode() to encode it, then decode to get a string like this: base64.b64encode(open('image.png', 'rb').read()).decode().
📋

Examples

Inputimage file 'test.png' with content bytes [137, 80, 78, 71]
OutputiVBORw==
Inputimage file 'photo.jpg' with content bytes [255, 216, 255, 224]
Output/9j/4A==
Inputempty image file
Output
🧠

How to Think About It

To convert an image to base64, you first read the image as raw bytes because base64 works on binary data. Then you encode those bytes into base64 format, which turns the binary data into readable text characters. Finally, you convert the encoded bytes to a string so you can use or store it easily.
📐

Algorithm

1
Open the image file in binary read mode.
2
Read all bytes from the image file.
3
Use base64 encoding to convert the bytes to base64 bytes.
4
Decode the base64 bytes to a string.
5
Return or print the base64 string.
💻

Code

python
import base64

with open('image.png', 'rb') as image_file:
    encoded_string = base64.b64encode(image_file.read()).decode()

print(encoded_string)
Output
iVBORw0KGgoAAAANSUhEUgAA...
🔍

Dry Run

Let's trace converting a small image file 'test.png' with bytes [137, 80, 78, 71].

1

Open file in binary mode

Open 'test.png' to read bytes [137, 80, 78, 71]

2

Read bytes

Read bytes: b'\x89PNG'

3

Encode to base64

base64.b64encode(b'\x89PNG') -> b'iVBORw=='

4

Decode to string

b'iVBORw==' decoded to 'iVBORw=='

StepOperationValue
1Read bytes[137, 80, 78, 71]
2Base64 encodeb'iVBORw=='
3Decode 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

Using base64.standard_b64encode
python
import base64
with open('image.png', 'rb') as f:
    data = f.read()
encoded = base64.standard_b64encode(data).decode()
print(encoded)
Works the same as b64encode but uses standard base64 alphabet explicitly.
Using io.BytesIO for in-memory images
python
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)
Useful when you have an image in memory and want to convert it without saving to disk.

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.

ApproachTimeSpaceBest For
base64.b64encode from fileO(n)O(n)Simple file to base64 conversion
base64.standard_b64encodeO(n)O(n)Explicit standard base64 encoding
In-memory BytesIO with PILO(n)O(n)Images created or manipulated in memory
💡
Always open the image file in binary mode ('rb') to get the correct bytes for base64 encoding.
⚠️
Trying to open the image file in text mode ('r') causes errors or wrong base64 output.