import os
import re
import base64
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showinfo
from PIL import Image
frameT = Tk()
frameT.geometry('500x200+400+200')
frameT.title('选择需要输入处理的文件')
frame = Frame(frameT)
frame.pack(padx=10, pady=10) # 设置外边距
frame_1 = Frame(frameT)
frame_1.pack(padx=10, pady=10) # 设置外边距
frame1 = Frame(frameT)
frame1.pack(padx=10, pady=10)
v1 = StringVar()
v2 = StringVar()
ent = Entry(frame, width=50, textvariable=v1).pack(fill=X, side=LEFT) # x方向填充,靠左
ent2 = Entry(frame_1, width=50, textvariable=v2).pack(fill=X, side=LEFT) # x方向填充,靠左
def fileopen():
file_sql = askopenfilename()
if file_sql:
v1.set(file_sql)
def fileopen_1():
file_YuD = askopenfilename()
if file_YuD:
v2.set(file_YuD)
#图片转透明处理函数
def transparent_back(pict_path):
# 循环遍历remobg文件夹中的所有图片
for pict in os.listdir(pict_path):
img_file = os.path.join(pict_path, pict)
#print(img_file)
# 执行去除背景色操作
img = Image.open(img_file)
img = img.convert('RGBA')
#img.show()
pixdata = img.load()
for y in range(img.size[1]):
for x in range(img.size[0]):
if pixdata[x, y][0] > 225 and pixdata[x, y][1] > 225 and pixdata[x, y][2] > 225 and pixdata[x, y][3] > 225:
pixdata[x, y] = (255, 255, 255, 0)
# 重命名
name = img_file.split('.')
#os.rename(os.path.join(pict_path, name[0] + ".png")
img.save(name[0] + ".png")
print("%s is done" % img_file)
# 保存结果到txt
def save_parse_result(content):
pathfile = v2.get()
print('****************************')
#print(path)
f = open(pathfile, 'a+', encoding='utf-8')
f.write(content + '
')
f.close()
#图片转base64
def pic_to_base64(pict_path):
# 循环遍历remobg文件夹中的所有图片
for pict in os.listdir(pict_path):
back_file = os.path.join(pict_path, pict)
with open(back_file, 'rb') as fp: # 二进制方式打开图文件
fpBase64 = base64.b64encode(fp.read()) # 读取文件内容,转换为base64编码
content = '{}
, base64:{}'.format(back_file, fpBase64)
print(content)
save_parse_result(content)
def match():
#调运行函数
pict_path = v1.get()
#print(pict_path)
transparent_back(pict_path)
pic_to_base64(pict_path)
#print(v1.get(), v2.get())
pass
btn = Button(frame, width=20, text='图片路径', font=("宋体", 14), command=fileopen).pack(fil=X, padx=10)
btn_1 = Button(frame_1, width=20, text='结果文件', font=("宋体", 14), command=fileopen_1).pack(fil=X, padx=10)
ext = Button(frame1, width=10, text='运行', font=("宋体", 14), command=match).pack(fill=X, side=LEFT)
etb = Button(frame1, width=10, text='退出', font=("宋体", 14), command=frameT.quit).pack(fill=Y, padx=10)
frameT.mainloop()