python3 圖片轉化為字元,並做成視覺化操作工具
阿新 • • 發佈:2018-12-26
python3 圖片轉化為字元,並轉化成視覺化操作工具。
然後生成EXE檔案,發給妹子,又裝逼成功~
先上效果圖
執行 python 檔案,然後上傳一張小圖:
生成txt 的檔案:
原始碼:
from tkinter import * from tkinter import filedialog from tkinter.filedialog import askdirectory from PIL import Image, ImageTk import tkinter.messagebox if __name__ == "__main__": root = Tk() File='' frame = Frame(root, bd=2, relief=SUNKEN) frame.grid_rowconfigure(0, weight=1) frame.grid_columnconfigure(0, weight=1) xscroll = Scrollbar(frame, orient=HORIZONTAL) xscroll.grid(row=1, column=0, sticky=E+W) yscroll = Scrollbar(frame) yscroll.grid(row=0, column=1, sticky=N+S) canvas = Canvas(frame, bd=0, xscrollcommand=xscroll.set, yscrollcommand=yscroll.set) canvas.grid(row=0, column=0, sticky=N+S+E+W) xscroll.config(command=canvas.xview) yscroll.config(command=canvas.yview) frame.pack(fill=BOTH,expand=1) # 開始轉化為字串 codeLib = '''@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'. '''#生成字元畫所需的字符集 count = len(codeLib) def printcoords(): global File File = filedialog.askopenfilename(parent=root, initialdir="C:/",title='Choose an image.') filename = ImageTk.PhotoImage(Image.open(File)) canvas.image = filename # <--- keep reference of your image canvas.create_image(0,0,anchor='nw',image=filename) def check(): if not File: tkinter.messagebox.showinfo('錯誤','還沒上傳圖片') else: path = askdirectory() if path: fp = open(File,'rb') image_file = Image.open(fp) image_file=image_file.resize((int(image_file.size[0]*0.6), int(image_file.size[1]*0.4)))#調整圖片大小 tmp = open(path+'/image.txt','w') tmp.write(transform1(image_file)) tmp.close() tkinter.messagebox.showinfo('成功','已成功儲存為txt檔案') def transform1(image_file): image_file = image_file.convert("L")#轉換為黑白圖片,引數"L"表示黑白模式 codePic = '' for h in range(0,image_file.size[1]): #size屬性表示圖片的解析度,'0'為橫向大小,'1'為縱向 for w in range(0,image_file.size[0]): gray = image_file.getpixel((w,h)) #返回指定位置的畫素,如果所開啟的影象是多層次的圖片,那這個方法就返回一個元組 codePic = codePic + codeLib[int(((count-1)*gray)/256)]#建立灰度與字符集的對映 codePic = codePic+'\r\n' return codePic def transform2(image_file): codePic = '' for h in range(0,image_file.size[1]): for w in range(0,image_file.size[0]): g,r,b = image_file.getpixel((w,h)) gray = int(r* 0.299+g* 0.587+b* 0.114) codePic = codePic + codeLib[int(((count-1)*gray)/256)] codePic = codePic+'\r\n' return codePic Button(root,text='選取圖片',command=printcoords).pack(side=LEFT,expand=YES,fill=Y) Button(root,text='選擇儲存路徑',command=check).pack(side=LEFT,expand=YES,fill=Y) root.mainloop()
然後自己再轉化成exe檔案,發給妹子玩
github: https://github.com/a519395243/Python_Item/