需求:
有时候,图片需要储存到数据库时,可以进行base64,进行先转换再进行保存到数据库,然后取出来时在使用base64,解码转换:
base64与图片互转
直接上代码,需要的可以参考。
import base64
# 图片转base64
def from_photo_to_base64(path):
with open(path, "rb") as file_photo: # 转为二进制格式
ret = file_photo.read()
base64_data = base64.b64encode(ret) # 使用base64进行加密
print(base64_data)
with open('base64.txt', 'w', encoding='utf-8') as file_w_base64: # 写成文本格式
file_w_base64.write(base64_data.decode('utf-8'))
# base64转图片
def from_base64_to_photo(path):
with open(path, "r") as file_read_base64:
base64_str = file_read_base64.read()
imgdata = base64.b64decode(base64_str)
with open('美女2.jpg', 'wb') as file_w_photo:
file_w_photo.write(imgdata)
if __name__ == '__main__':
path = "美女.jpg"
from_photo_to_base64(path)
path2 = 'base64.txt'
from_base64_to_photo(path2)