刷一下!!!上千图片转换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()