The base64 module encodes binary data as ASCII text. Essential for embedding binary in JSON, emails, and URLs.
Basic Encoding/Decoding
import base64
# Encode bytes to base64
data = b"Hello, World!"
encoded = base64.b64encode(data)
print(encoded) # b'SGVsbG8sIFdvcmxkIQ=='
# Decode back to bytes
decoded = base64.b64decode(encoded)
print(decoded) # b'Hello, World!'Working with Strings
import base64
# String → base64 string
text = "Hello, World!"
encoded = base64.b64encode(text.encode()).decode()
print(encoded) # 'SGVsbG8sIFdvcmxkIQ=='
# Base64 string → string
decoded = base64.b64decode(encoded).decode()
print(decoded) # 'Hello, World!'URL-Safe Base64
Standard base64 uses + and / which are special in URLs. Use URL-safe variant:
import base64
data = b'\xfb\xff\xfe' # Contains bytes that produce + and /
# Standard (not URL-safe)
standard = base64.b64encode(data)
print(standard) # b'++/+'
# URL-safe (- instead of +, _ instead of /)
urlsafe = base64.urlsafe_b64encode(data)
print(urlsafe) # b'--_-'
# Decode URL-safe
decoded = base64.urlsafe_b64decode(urlsafe)Encoding Files
import base64
# Encode file to base64
with open('image.png', 'rb') as f:
encoded = base64.b64encode(f.read())
# Decode base64 to file
with open('output.png', 'wb') as f:
f.write(base64.b64decode(encoded))Data URLs
import base64
import mimetypes
def to_data_url(filepath):
"""Convert file to data URL."""
mime_type, _ = mimetypes.guess_type(filepath)
with open(filepath, 'rb') as f:
encoded = base64.b64encode(f.read()).decode()
return f"data:{mime_type};base64,{encoded}"
# Usage
data_url = to_data_url('image.png')
# data:image/png;base64,iVBORw0KGgo...Base32 and Base16
import base64
data = b"Hello"
# Base32 (A-Z, 2-7)
b32 = base64.b32encode(data)
print(b32) # b'JBSWY3DP'
# Base16 (hex)
b16 = base64.b16encode(data)
print(b16) # b'48656C6C6F'
# Decode
base64.b32decode(b32)
base64.b16decode(b16)ASCII85 (Base85)
More compact than base64:
import base64
data = b"Hello, World!"
# ASCII85 encoding
a85 = base64.a85encode(data)
print(a85) # b'87cURD]j7BEbo80'
# Base85 (Git/Mercurial style)
b85 = base64.b85encode(data)
print(b85) # b'NM&qnZy;B1a%^M'Practical Examples
JWT-Style Tokens
import base64
import json
def encode_payload(payload: dict) -> str:
"""Encode dict as URL-safe base64."""
json_bytes = json.dumps(payload).encode()
return base64.urlsafe_b64encode(json_bytes).decode().rstrip('=')
def decode_payload(encoded: str) -> dict:
"""Decode URL-safe base64 to dict."""
# Add padding back
padding = 4 - len(encoded) % 4
if padding != 4:
encoded += '=' * padding
json_bytes = base64.urlsafe_b64decode(encoded)
return json.loads(json_bytes)
payload = {'user': 'alice', 'exp': 1234567890}
token = encode_payload(payload)
print(token) # 'eyJ1c2VyIjoiYWxpY2UiLCJleHAiOjEyMzQ1Njc4OTB9'Email Attachments
import base64
from email.mime.base import MIMEBase
from email import encoders
def create_attachment(filepath):
"""Create base64-encoded email attachment."""
with open(filepath, 'rb') as f:
data = f.read()
part = MIMEBase('application', 'octet-stream')
part.set_payload(data)
encoders.encode_base64(part)
return partAPI Image Upload
import base64
import requests
def upload_image(filepath, api_url):
"""Upload image as base64 to API."""
with open(filepath, 'rb') as f:
image_data = base64.b64encode(f.read()).decode()
response = requests.post(api_url, json={
'image': image_data,
'filename': filepath
})
return response.json()Inline Images in HTML
import base64
def img_to_html(filepath):
"""Convert image to inline HTML img tag."""
with open(filepath, 'rb') as f:
encoded = base64.b64encode(f.read()).decode()
ext = filepath.split('.')[-1]
mime = {'png': 'image/png', 'jpg': 'image/jpeg', 'gif': 'image/gif'}
return f'<img src="data:{mime.get(ext, "image/png")};base64,{encoded}" />'Basic Auth Header
import base64
def basic_auth_header(username: str, password: str) -> str:
"""Create HTTP Basic Auth header."""
credentials = f"{username}:{password}"
encoded = base64.b64encode(credentials.encode()).decode()
return f"Basic {encoded}"
header = basic_auth_header("user", "pass")
# 'Basic dXNlcjpwYXNz'Padding
Base64 output length is always a multiple of 4, padded with =:
import base64
# Different input lengths
base64.b64encode(b'a') # b'YQ==' (2 padding)
base64.b64encode(b'ab') # b'YWI=' (1 padding)
base64.b64encode(b'abc') # b'YWJj' (no padding)
base64.b64encode(b'abcd') # b'YWJjZA==' (2 padding)Quick Reference
import base64
# Standard Base64
base64.b64encode(bytes) # bytes → base64 bytes
base64.b64decode(bytes) # base64 bytes → bytes
# URL-safe Base64
base64.urlsafe_b64encode(bytes)
base64.urlsafe_b64decode(bytes)
# Other encodings
base64.b32encode(bytes) # Base32
base64.b32decode(bytes)
base64.b16encode(bytes) # Base16 (hex)
base64.b16decode(bytes)
base64.a85encode(bytes) # ASCII85
base64.a85decode(bytes)
base64.b85encode(bytes) # Base85
base64.b85decode(bytes)| Encoding | Chars | Efficiency | Use Case |
|---|---|---|---|
| Base64 | A-Za-z0-9+/ | 75% | General |
| URL-safe | A-Za-z0-9-_ | 75% | URLs |
| Base32 | A-Z2-7 | 62.5% | Case-insensitive |
| Base16 | 0-9A-F | 50% | Hex |
| Base85 | 85 printable | 80% | Compact |
base64 is the standard way to represent binary data as text. Use it for APIs, emails, and anywhere binary doesn't fit.
React to this post: