import os
import re
import base64
import json
#--------------------------------------------------------
def images2base64json(img_dir,json_file_location):
'''
将目录下的png图片文件批量转换成base64字符串并以json格式保存到文件
img_dir 资源文件夹
json_file_location 保存json的文件名
json格式为 {"原文件名":"base64字符串"}
'''
image_json={}
for file_name in os.listdir(img_dir):
#print(file_name)
if file_name.endswith(".png"):
image_name=re.sub(r"\.png$","",file_name)
image_location=img_dir+file_name
image=open(image_location,"rb")
image_bytes=image.read()
image_base64=base64.b64encode(image_bytes)
if isinstance(image_base64,bytes):
image_base64=str(image_base64, encoding='utf-8');
image.close()
image_json[image_name]=image_base64
#print(image_json)
image_save=open(json_file_location,"w",encoding='UTF-8')
image_save.write(json.dumps(image_json))
image_save.close()
print("result saved to: "+json_file_location)
#--------------------------------------------------------
img_dir="d:/tests/NationEventGraph/static/countryflags/"
json_file_location="e:/tests/base64flags.txt"
images2base64json(img_dir,json_file_location)
|