刷一下!!!上千图片转换base64编码并保存到文本文件

目的:把各种格式的图片转换成为base64编码

程序运行结果图

 

程序完整代码:

 

import os
import readline
import base64


#可执行文件exe打包及粘贴功能支持
readline.parse_and_bind("control-v: paste")

class ImageCheck(object):
        
    def image_to_base64(self):
        #得到照片存放路径
        strfile = os.getcwd()+'\\testimage\\'
        
        #循环遍历目录下的照片文件
        for root,dirs,files in os.walk(strfile):
            for f in files:
                #取出符合图片后缀名称的图片
                if os.path.splitext(f)[1].upper() in ['.JPG','.PNG','.BMP','.JPEG']:
                  filepath = os.path.join(root, f)
                  with open(filepath,'rb') as f:
                     # b64encode是编码,b64decode是解码
                     base64_data = base64.b64encode(f.read())
                     image_base64 = str(base64_data, encoding='utf-8')
                     #s = base64.b64decode(base64_data)
                     #生成txt文件文件,并保存到图片目录中
                     filetxt = filepath[:-3]+"txt"                    
                     with open(filetxt,'wb') as fo:   
                         fo.write(bytes(image_base64,'UTF-8'))     
                         print("base64 转换完成"+filetxt)


        
    @staticmethod
    def print_menu():
        print("======开始运行程序======")
        print("0:退出程序")
        print("1:图片转Base64编码")
        print("2:待开发功能")
        return input("请输入功能对应的序号:")

        
    def run(self):
        while True:
            num = self.print_menu()
            if num == "0":
               break
            elif num == "1":
               self.image_to_base64()
            elif num == "2":
                pass
            else:
                print("输入有误!请重新输入...")
        

# main方法作为程序入口
def main():
    ic = ImageCheck()
    ic.run()

#运行程序入口
if __name__ =="__main__":
    main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值