第五章

Python 中的 Base64

使用 Python 内置库进行高效编码和解码

5.1 基础使用

Python 标准库提供了 base64 模块。最常用的两个函数是 b64encodeb64decode

import base64

# 1. 准备数据(必须是 bytes 类型)
text = "Hello, World!"
data = text.encode('utf-8')

# 2. 编码
encoded = base64.b64encode(data)
print(encoded) 
# 输出: b'SGVsbG8sIFdvcmxkIQ=='

# 3. 转为字符串(可选)
encoded_str = encoded.decode('utf-8')
print(encoded_str)
# 输出: SGVsbG8sIFdvcmxkIQ==

# 4. 解码
decoded = base64.b64decode(encoded)
print(decoded.decode('utf-8'))
# 输出: Hello, World!

⚠️ 注意事项:

Base64 处理的是二进制数据(bytes)。在编码前必须将字符串 encode() 为 bytes,解码后得到的也是 bytes,通常需要 decode() 回字符串。

5.2 处理二进制文件(图片等)

读取图片、音频等文件并转换为 Base64 字符串:

import base64

# 读取文件并编码
with open('image.png', 'rb') as f:
    image_data = f.read()
    encoded_str = base64.b64encode(image_data).decode('utf-8')
    print(encoded_str)

# 解码并保存为新文件
decoded_data = base64.b64decode(encoded_str)
with open('restored_image.png', 'wb') as f:
    f.write(decoded_data)

5.3 Base64URL 变种

标准的 Base64 包含 +/,这两个字符在 URL 中有特殊含义。URL 安全的 Base64 将它们替换为 -_

import base64

url_data = "https://example.com/a?b=c".encode('utf-8')

# 标准编码
standard = base64.b64encode(url_data)
# 结果可能包含 + 或 /

# URL 安全编码 (使用 - 和 _)
url_safe = base64.urlsafe_b64encode(url_data)

print(url_safe.decode('utf-8'))