python3 图片进行base64编码与解码
2023-04-26 本文已影响0人
朝畫夕拾
下列代码复制后可直接运行
# base64编码后的二进制图片文件
a=b'/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAwICQoJBwwKCQoNDAwOER0TERAQESMZGxUdKiUsKyklKCguNEI4LjE/MigoOk46P0RHRT+I4NLKkl0Ul0+vgscbWzvwJJNV1spUngfdw+7j/sPU3cWQ7ltRyK01bVproytpp01TRzs06y7R0AAUJQAAEkEgAcuMle35ZWzt1Mc7WzNiDNLD/b9DagcHeNmLM4sqh3LEZaZp+TJehC6krp9QifcP0JQZRD6UzFoyfUxAxtrowAVNR//2Q=='
import base64
# base64解码(解成二进制串)
decode_jpg = base64.b64decode(a)
# print(decode_jpg)
# 写入jpg文件
with open('./new.jpg', 'wb') as f:
f.write(decode_jpg)
# 读取图片二进制文件
with open('./new.jpg', 'rb') as f:
ccc = f.read()
# 进行base64编码
encode_jpg = base64.b64encode(ccc)
# print(encode_jpg.decode()) # 二进制decode
# 进行base64解码,并写入一个图片文件
decode_jpg = base64.b64decode(encode_jpg)
with open('new2.jpg','wb')as f:
f.write(decode_jpg)