Base64,简单地讲,就是用 64 个字符来表示二进制数据的方法。这 64 个字符包含小写字母 a-z、大写字母 A-Z、数字 0-9 以及符号"+"、"/",其实还有一个 "=" 作为后缀用途,所以实际上有 65 个字符。
Python 内置了一个用于 Base64 编解码的库:base64:
编码使用 base64.b64encode()
解码使用 base64.b64decode()
1 对图片进行 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()
2 对图片进行 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()
import base64
#base_str1 = "data:image/jpg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD/"
base_str= "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAoBIADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAA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PX/AMdNFFAB9vtv+ev/AI6aPt9t/wA9f/HTRRQAfb7b/nr/AOOmj7fbf89f/HTRRQAfb7b/AJ6/+Omj7fbf89f/AB00UUAH2+2/56/+Omj7fbf89f8Ax00UUAH2+2/56/8Ajpo+323/AD1/8dNFFAB9vtv+ev8A46aPt9t/z1/8dNFFAB9vtv8Anr/46aPt9t/z1/8AHTRRQAfb7b/nr/46aPt9t/z1/wDHTRRQAfb7b/nr/wCOmj7fbf8APX/x00UUAH2+2/56/wDjpo+323/PX/x00UUAH2+2/wCev/jpo+323/PX/wAdNFFAB9vtv+ev/jpo+323/PX/AMdNFFAB9vtv+ev/AI6aPt9t/wA9f/HTRRQAfb7b/nr/AOOmj7fbf89f/HTRRQAfb7b/AJ6/+Omj7fbf89f/AB00UUAH2+2/56/+Omj7fbf89f8Ax00UUAH2+2/56/8Ajpo+323/AD1/8dNFFAB9vtv+ev8A46aPt9t/z1/8dNFFAB9vtv8Anr/46aPt9t/z1/8AHTRRQAfb7b/nr/46aPt9t/z1/wDHTRRQAfb7b/nr/wCOmj7fbf8APX/x00UUAH2+2/56/wDjpo+323/PX/x00UUAH2+2/wCev/jpo+323/PX/wAdNFFAB9vtv+ev/jpo+323/PX/AMdNFFAB9vtv+ev/AI6aPt9t/wA9f/HTRRQAfb7b/nr/AOOmj7fbf89f/HTRRQAfb7b/AJ6/+Omj7fbf89f/AB00UUAH2+2/56/+Omj7fbf89f8Ax00UUAH2+2/56/8Ajpo+323/AD1/8dNFFAB9vtv+ev8A46aPt9t/z1/8dNFFAB9vtv8Anr/46aPt9t/z1/8AHTRRQAfb7b/nr/46aPt9t/z1/wDHTRRQAfb7b/nr/wCOmj7fbf8APX/x00UUAH2+2/56/wDjpo+323/PX/x00UUAH2+2/wCev/jpo+323/PX/wAdNFFAB9vtv+ev/jpo+323/PX/AMdNFFAH/9k="
img= base64.b64decode(base_str)
file= open("./text.jpg","wb")
file.write(img)
file.close()