用户:
极光AXE查看:0 回复:0 评论:0 创建时间:2021-04-03T22:12:58
from tkinter import *
import tkinter.messagebox as message
import matplotlib.pyplot as plt
import tkinter.filedialog as file
from PIL import Image,ImageDraw
import sys,os
class MainWindow():
def __init__(self):
super().__init__()
self.screen = Tk()
self.setup()
self.screen.geometry('550x150')
self.screen.title('图片转字符串')
self.screen.resizable(0,0)
def setup(self):
self.choose = Button(text='选择图片',width=20,command = self.choose_function)
self.begin = Button(text='开始转换',width=20,command=self.pic_str)
self.save = Button(text = '保存字符串图片',width=20,command=self.save_function)
self.choose.place(x=30,y=10)
self.begin.place(x=200,y=10)
self.save.place(x=370,y=10)
def choose_function(self):
try:
self.image_path = file.askopenfilename(filetypes=[('图片文件','*.png'),('图片文件','jpg')])
except:
message.showerror('错误','出错了')
sys.exit()
def pic_str(self):
try:
w, h = 60, 60
self.img = Image.open(self.image_path).convert('L').resize((w, h))
ASCII_HIGH = ('''$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/||()1{}[]?-_+~<>i!lI;:,\"^`'. ''')
txt = ''
self.img_new=Image.new('RGB',(w*12,h*15),'white')
for y in range(h):
for x in range(w):
pos=(x,y)
gray=self.img.getpixel(pos)
index=int(gray/256*70)
txt += ASCII_HIGH[index] +' '
txt += '\n'
draw=ImageDraw.Draw(self.img_new)
self.screen.geometry('550x600')
draw.text((0, 0), txt, fill='black')
self.img_new.resize((500,500)).save("temp.gif")
self.img_tk = PhotoImage(file='temp.gif')
Label(image=self.img_tk,width=500,height=500).place(x=20,y=50)
os.remove('temp.gif')
except:
message.showerror("错误",'出错了')
sys.exit()
def save_function(self):
try:
w, h = 60, 60
path = file.asksaveasfilename()+'.jpg'
self.img_new.resize((w*12, w*12)).save(path)
message.showinfo('提示','保存成功 ^_^')
plt.imshow(Image.open(path))
plt.show()
except:
message.showerror("错误",'出错了')
sys.exit()
if __name__ == '__main__':
screen = MainWindow()
mainloop()
sys.exit()