Base64,简单地讲,就是用 64 个字符来表示二进制数据的方法。这 64 个字符包含小写字母 a-z、大写字母 A-Z、数字 0-9 以及符号"+"、"/",其实还有一个 "=" 作为后缀用途,所以实际上有 65 个字符。
Python 内置了一个用于 Base64 编解码的库:base64
:
- 编码使用
base64.b64encode()
- 解码使用
base64.b64decode()
对图片进行 Base64 编码和解码
import base64
def convert_image():
# Picture ==> base64 encode
with open('d:\\FileTest\\Hope_Despair.jpg', 'rb') as fin:
image_data = fin.read()
base64_data = base64.b64encode(image_data)
fout = open('d:\\FileTest\\base64_content.txt', 'w')
fout.write(base64_data.decode())
fout.close()
# base64 encode ==> Picture
with open('d:\\FileTest\\base64_content.txt', 'r') as fin:
base64_data = fin.read()
ori_image_data = base64.b64decode(base64_data)
fout = open('d:\\FileTest\\Hope_Despair_2.jpg', 'wb')
fout.write(ori_image_data)
fout.close()
if __name__ == '__main__':
convert_image()
对图片进行 Base64 编码和解码(Pythonic)
import base64
def convert_image():
# Picture ==> base64 encode
with open('d:\\FileTest\\Hope_Despair.jpg', 'rb') as fin, open('d:\\FileTest\\base64_content.txt', 'w') as fout:
fout.write(base64.b64encode(fin.read()).decode())
# base64 encode ==> Picture
with open('d:\\FileTest\\base64_content.txt', 'r') as fin, open('d:\\FileTest\\Hope_Despair_2.jpg', 'wb') as fout:
fout.write(base64.b64decode(fin.read()))
if __name__ == '__main__':
convert_image()