用python3写的图片与base64互转工具

一个图片与base64互转工具,方便在markdown中直接插入图片

程序效果
avatar
最新代码路径: https://gitee.com/cavin_sun/python_tools.git



#使用python将图片转化为base64字符串,或者将base64字符串转换为图片
import os,sys
import base64

def image_to_base64(img_path,bs_file_path):
    print(sys._getframe().f_code.co_name)  # 打印自身函数名
    img_path = str(img_path)
    img_path = img_path.rstrip()
    bs_file_path = str(bs_file_path)
    bs_file_path = bs_file_path.rstrip()


    if bs_file_path == '':
        bs_file_path = 'bs_file.txt'
    if os.path.exists(img_path) is not True:
        print("image path is invalid")
        return False
    if os.path.exists(os.path.dirname(bs_file_path)) is not True:
        print("base file  path  is invalid")
        return False
    f_img=open(img_path,'rb') #二进制方式打开图文件
    ls_f=base64.b64encode(f_img.read()) #读取文件内容,转换为base64编码
    f_img.close()
    #print(ls_f)
    str_bs = ls_f.decode()
    f_bs=open(bs_file_path,'w+')
    f_bs.write(str_bs)
    f_bs.close()
    print("convert end!")
    

def base64_to_image(img_path,bs_file_path):
    print(sys._getframe().f_code.co_name)  # 打印自身函数名
    img_path = str(img_path)
    img_path = img_path.rstrip()
    bs_file_path = str(bs_file_path)
    bs_file_path = bs_file_path.rstrip()    

    if img_path == '':
        img_path = 'image_file.jpg'
    print("bs_file_path:" + bs_file_path)
    print("img_path:"+img_path)
    if os.path.exists(os.path.dirname(img_path)) is not True:
        print("image path is invalid")
        return False
    if os.path.exists(bs_file_path) is not True:
        print("base file  path  is invalid")
        return False
    
    bs_f = open(bs_file_path,'rb')
    bs_str = bs_f.read(os.path.getsize(bs_file_path))
    bs_str = bs_str.decode()
    bs = bs_str.rstrip()
    imgdata=base64.b64decode(bs)
    file=open(img_path,'wb+')
    file.write(imgdata)
    file.close()
    print("convert end!")
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
class Entry_FileSelct():
    def __init__(self,parent,lab_txt):

        self.__root = parent
        self.lab_txt = lab_txt
        self.__cfg_file_name = ''
        self.lab = ttk.Label(self.__root, text=self.lab_txt, width=15)
        self.entry_txt = ttk.Entry(self.__root, width=20)
        self.btn_file = ttk.Button(self.__root, text='...', width=2, command=self.open_cfg_file)

    def grid(self,row_num,column_num_base):
        pass
        off_padx = 10
        off_pady = 5
        row_num = int(row_num)
        column_num = int(column_num_base)+int(0)
        self.lab.grid(row=row_num, column=column_num,columnspan=1,padx=off_padx, pady=off_pady,sticky='E')
        column_num = column_num + 1
        self.entry_txt.grid(row=row_num, column=column_num, columnspan=2,sticky='W')
        column_num = column_num + 2
        self.btn_file.grid(row=row_num, column=column_num, columnspan=1,sticky='E')
    def grid_forget(self):
        self.btn_file.grid_forget()
        self.entry_txt.grid_forget()
        self.lab.grid_forget()

    def pack(self):
        off_padx = 10
        off_pady = 5
        self.lab.pack(padx=off_padx, pady=off_pady)
        self.entry_txt.pack(padx=off_padx, pady=off_pady)
        self.btn_file.pack(padx=off_padx, pady=off_pady)
        pass
    def open_cfg_file(self):
        print("openfile")
        self.__cfg_file_name = filedialog.askopenfilename()
        if self.__cfg_file_name != '':
            print(u"你选择的文件是:" + self.__cfg_file_name)
            self.entry_txt.delete(0, tk.END)
            self.entry_txt.insert(tk.END,self.__cfg_file_name)

        else:
            print(u"您没有选择任何文件")
    def get_entry_txt(self):
        str_get = self.entry_txt.get()
        if str_get=='':
            log = ("您没有选择任何文件")
            print(log)
            messagebox.showerror("错误", log)
            return False
        print(str_get)
        str_get = str(str_get)
        str_get = str_get.rstrip()
        if os.path.exists(str_get) is False:
            log = ("The path:\'%s\' is invalid!"%str_get)
            print(log)
            messagebox.showerror("错误", log)
            return False
        return str_get
class Entry_FileSave():
    def __init__(self,parent,lab_txt):

        self.__root = parent
        self.lab_txt = lab_txt
        self.__cfg_file_name = ''
        self.lab = ttk.Label(self.__root, text=self.lab_txt, width=15)
        self.entry_txt = ttk.Entry(self.__root, width=20)
        self.btn_file = ttk.Button(self.__root, text='...', width=2, command=self.saveAsFile)

    def grid(self,row_num,column_num_base):
        pass
        off_padx = 10
        off_pady = 5
        row_num = int(row_num)
        column_num = int(column_num_base)+int(0)
        self.lab.grid(row=row_num, column=column_num,columnspan=1,padx=off_padx, pady=off_pady,sticky='E')
        column_num = column_num + 1
        self.entry_txt.grid(row=row_num, column=column_num, columnspan=2,sticky='W')
        column_num = column_num + 2
        self.btn_file.grid(row=row_num, column=column_num, columnspan=1,sticky='E')
    def grid_forget(self):
        self.btn_file.grid_forget()
        self.entry_txt.grid_forget()
        self.lab.grid_forget()
    def pack(self):
        off_padx = 10
        off_pady = 5
        self.lab.pack(padx=off_padx, pady=off_pady)
        self.entry_txt.pack(padx=off_padx, pady=off_pady)
        self.btn_file.pack(padx=off_padx, pady=off_pady)
        pass
    def saveAsFile(self):
        print("openfile")
        self.__cfg_file_name = filedialog.asksaveasfilename()
        if self.__cfg_file_name != '':
            print(u"你选择的文件是:" + self.__cfg_file_name)
            self.entry_txt.delete(0, tk.END)
            self.entry_txt.insert(tk.END,self.__cfg_file_name)

        else:
            print(u"您没有选择任何文件")
    def get_entry_txt(self):
        str_get = self.entry_txt.get()
        if str_get=='':
            log = ("您没有选择任何文件")
            print(log)
            messagebox.showerror("错误", log)
            return False
        print(str_get)
        str_get = str(str_get)
        str_get = str_get.rstrip()

        if os.path.exists(os.path.dirname(str_get)) is False:
            log = ("The direct:\'%s\' is invalid!"%os.path.dirname(str_get))
            print(log)
            messagebox.showerror("错误", log)
            return False
        return str_get

class DlgTop():
    def __init__(self):
        self.root = tk.Tk()
        root = self.root
        root.title("图像到base64互转工具1.0")
        self.wd_set(root, width=450, heigt=300)

        tag = tk.IntVar()
        tagWidth = 23

        tk.Radiobutton(root, text="图像转Base64", command=self.funcSelect_image2base, variable=tag, width=tagWidth,
                    value=0, bd=1,indicatoron=True).grid(column=0, row=0)
        tk.Radiobutton(root, text="Base64转图像", command=self.funcSelect_base2image, variable=tag, width=tagWidth,
                        value=1, bd=1, indicatoron=True).grid(column=1, row=0)
        self.cls_entry_dlg_image = Entry_FileSelct(parent=root, lab_txt="图像文件:")
        self.cls_entry_dlg_base64 = Entry_FileSelct(parent=root, lab_txt="Base64文件:")
        self.cls_entry_dlg_image_save = Entry_FileSave(parent=root, lab_txt="图像保存为:")
        self.cls_entry_dlg_base64_save = Entry_FileSave(parent=root, lab_txt="Base64保存为:")

        self.btn_to_base64 = ttk.Button(root, text="图像转Base64", width=20, command=self.btn_click_IMage2Base64)
        self.btn_to_image = ttk.Button(root, text="Base64转图像", width=20, command=self.btn_click_Base642IMage)

        tag.set(0)

        if tag.get() == 0:
            self.funcSelect_image2base()
        else:
            self.funcSelect_base2image()
        self.root.mainloop()
    def funcSelect_image2base(self):
        pass
        self.btn_to_image.grid_forget()
        self.cls_entry_dlg_image_save.grid_forget()
        self.cls_entry_dlg_base64.grid_forget()
        self.btn_to_base64.grid(row=3, column=0, columnspan=1, sticky='E')
        self.cls_entry_dlg_image.grid(row_num=1, column_num_base=0)
        self.cls_entry_dlg_base64_save.grid(row_num=2, column_num_base=0)
    def funcSelect_base2image(self):
        pass
        self.btn_to_base64.grid_forget()
        self.cls_entry_dlg_image.grid_forget()
        self.cls_entry_dlg_base64_save.grid_forget()
        self.btn_to_image.grid(row=3, column=0, columnspan=1, sticky='E')
        self.cls_entry_dlg_image_save.grid(row_num=2, column_num_base=0)
        self.cls_entry_dlg_base64.grid(row_num=1, column_num_base=0)
    def wd_set(self,wd_root,width,heigt):
        wd_width = width
        wd_height = heigt
        # 获取屏幕尺寸以计算布局参数,使得窗口在屏幕中央
        screen_width = wd_root.winfo_screenwidth()
        screen_height = wd_root.winfo_screenheight()
        print("screen size:%d x %d " % (screen_width, screen_height))
        alignstr = "%dx%d+%d+%d" % (wd_width, wd_height, (screen_width - wd_width) / 2, (screen_height - wd_height) / 2)
        # 设置窗口尺寸和位置
        wd_root.geometry(alignstr)
        # 设置窗口是否可变长宽
        wd_root.resizable(width=False, height=False)

    def btn_click_IMage2Base64(self):

        img_path = self.cls_entry_dlg_image.get_entry_txt()
        if img_path is False:
            return
        bs_path = self.cls_entry_dlg_base64_save.get_entry_txt()
        if bs_path is False:
            return
        self.btn_to_base64.config(state="disabled")
        image_to_base64(img_path,bs_path)
        self.btn_to_base64.config(state="active")

    def btn_click_Base642IMage(self):
        img_path = self.cls_entry_dlg_image_save.get_entry_txt()
        if img_path is False:
            return
        bs_path = self.cls_entry_dlg_base64.get_entry_txt()
        if bs_path is False:
            return
        self.btn_to_image.config(state="disabled")
        base64_to_image(img_path, bs_path)
        self.btn_to_image.config(state="active")


def main():
    dlg = DlgTop()


    
if __name__ == "__main__":
    main()

你可能感兴趣的:(python)