Base64,簡單地講,就是用 64 個字符來表示二進(jìn)制數(shù)據(jù)的方法。這 64 個字符包含小寫字母 a-z、大寫字母 A-Z、數(shù)字 0-9 以及符號"+"、"/",其實還有一個 "=" 作為后綴用途,所以實際上有 65 個字符。
本文主要介紹如何使用 Python 進(jìn)行 Base64 編碼和解碼,關(guān)于 Base64 編碼轉(zhuǎn)換的規(guī)則可以參考 Base64 筆記。
Python 內(nèi)置了一個用于 Base64 編解碼的庫:base64:
base64.b64encode()base64.b64decode()下面,我們介紹文本和圖片的 Base64 編解碼。
>>> import base64
>>> str = 'hello world'
>>>
>>> base64_str = base64.b64encode(str) # 編碼
>>> print base64_str
aGVsbG8gd29ybGQ=
>>>
>>> ori_str = base64.b64decode(base64_str) # 解碼
>>> print ori_str
hello world
def convert_image():
# 原始圖片 ==> base64 編碼
with open('/path/to/alpha.png', 'r') as fin:
image_data = fin.read()
base64_data = base64.b64encode(image_data)
fout = open('/path/to/base64_content.txt', 'w')
fout.write(base64_data)
fout.close()
# base64 編碼 ==> 原始圖片
with open('/path/to/base64_content.txt', 'r') as fin:
base64_data = fin.read()
ori_image_data = base64.b64decode(base64_data)
fout = open('/path/to/beta.png', 'wb'):
fout.write(ori_image_data)
fout.close()