将txt文件转化为bmp文件 python源码 tkinter学习

写了一个将txt文件与bmp文件互转的python脚本

环境要求不高

Pillow==8.3.1
numpy==1.19.5

话不多说,直接上代码

"""
Pillow==8.3.1
numpy==1.19.5
"""
from PIL import Image
import math
from tkinter import filedialog
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox as msg
import numpy as np


def selectPath():
    path_input = filedialog.askopenfilename(title="find path",
                                            filetypes=[('txt', '.txt'), ('bmp', '.bmp')])  # 选择路径函数
    path_input = path_input.replace("/", "\\")  # 路径符号转换
    pathIn.set(path_input)  # 路径存储到变量pathIn
    # 判断是否为所需文件
    if (pathIn.get()[-4:]) != '.txt' and (pathIn.get()[-4:]) != '.bmp' and len(pathIn.get()) != 0:
        msgBox_typeError()  # 若否,显示类型错误


# 错误信息显示弹窗
def msgBox_typeError():
    msg.showerror('文件类型错误', '请选择txt或bmp文件!')


def msgBox_SaveError():
    msg.showerror('错误', '请选择输入文件与保存文件!')


def transform_SaveError():
    msg.showerror('错误', '输入文件错误或已被损坏!')


# 存储路径选择函数
def saveDir():
    filetypes = []
    endls = ''
    if pathIn.get()[-4:] == '.txt':
        filetypes.append(('bmp', '.bmp'))
        endls = ".bmp"
    elif pathIn.get()[-4:] == '.bmp':
        filetypes.append(('txt', '.txt'))
        endls = ".txt"
    path_save = filedialog.asksaveasfilename(title="set headfiles path",
                                             filetypes=filetypes,
                                             defaultextension=endls)
    path_save = path_save.replace("/", "\\")
    pathOut.set(path_save)


# 弹窗提示:转换成功
def msgBox_Success():
    msg.showinfo('SUCCESS', '转换成功!')


def transformation():
    global converting
    if converting == 0:  # 确保在转换过程中用户的多次点击无效
        converting = 1 - converting
        if pathOut.get() == '' or pathIn.get() == '':  # 确保含有输入输出地址
            msgBox_SaveError()

        try:
            if pathIn.get()[-4:] == '.txt':
                with open(pathIn.get(), encoding="utf-8") as f:
                    text = f.read()
                str_len = len(text) * 2 + 4
                width = math.ceil((str_len / 3) ** 0.5)
                height = width
                while width * height * 3 - str_len >= width * 3:
                    height -= 1
                src = [(str_len & 0xFF000000) >> 24, (str_len & 0xFF0000) >> 16,
                       (str_len & 0xFF00) >> 8, str_len & 0xFF]
                for i in text:
                    num = ord(i)
                    src.append((num & 0xFF00) >> 8)
                    src.append(num & 0xFF)
                for i in range(width * height * 3 - len(src)):
                    src.append(0)
                src = np.array(src, dtype='uint8').reshape([width, height, 3])
                Image.fromarray(src).save(pathOut.get())
                msgBox_Success()
            elif pathIn.get()[-4:] == '.bmp':
                src = np.array(Image.open(pathIn.get()))
                array_img = src.reshape(-1)
                str_len = (array_img[0] << 24) + (array_img[1] << 16) + (array_img[2] << 8) + array_img[3]
                array_img = array_img[4:str_len].reshape(-1, 2).tolist()
                lst = []
                for i in array_img:
                    lst.append(chr((i[0] << 8) + i[1]))
                with open(pathOut.get(), 'w', encoding="utf-8") as f:
                    f.write(''.join(lst))
                msgBox_Success()
            converting = 1 - converting
        except:
            transform_SaveError()


converting = 0
if __name__ == '__main__':
    # =============== 建立界面窗口 ================#
    win = tk.Tk()
    win.title("txt文本与bmp图片加密互转")

    # =============== 建立txt文件或者bmp图片地址输入框===============#
    mighty1 = ttk.LabelFrame(win, text=' txt文件或者bmp图片: ')  # 限制在第一个子框架内
    mighty1.grid(column=0, row=0, padx=8, pady=4)  # 子框架位置

    pathIn = tk.StringVar()  # 字符变量:传入文件路径

    # 路径选择框
    tk.Label(mighty1, text="目标路径:").grid(row=0, column=0)  # 标签:txt文件或者bmp图片路径
    tk.Entry(mighty1, width=20, textvariable=pathIn).grid(row=0, column=1, columnspan=2)  # 输入框:路径输入框
    tk.Button(mighty1, text="选择文件", command=selectPath).grid(row=0, column=3)  # 按钮:路径选择,调用函数selectPath

    # ================== 转换操作 =====================#
    # 建立第二个子框架
    mighty2 = ttk.LabelFrame(win, text='转换文件')
    mighty2.grid(column=0, row=3, padx=8, pady=4)

    pathOut = tk.StringVar()  # 字符变量:转换文件的路径

    # 转换路径选择框架
    tk.Label(mighty2, text="存储路径:").grid(row=0, column=0)  # 标签:存储路径
    tk.Entry(mighty2, width=20, textvariable=pathOut).grid(row=0, column=1, columnspan=2)  # 输入框:存储路径
    tk.Button(mighty2, text="保存文件", command=saveDir).grid(row=0, column=3)  # 按钮:存储选择路径
    # 按钮:转换操作,调用函数transformation
    mergeButton = ttk.Button(mighty2, text='转换', command=transformation)
    mergeButton.grid(column=1, row=1)

    # ================== 主循环 =======================#
    win.mainloop()

你可能感兴趣的:(python,pycharm,开发语言,tkinter)