python批量转换文件夹下.png图片为base64字符串

python批量转换文件夹下.png图片为base64字符串,第1张

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)

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/723941.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)

保存