前端的界面布局中,会经常用到图中的图片引用方式:把图片转换为一段加密的字符串,直接将字符串书写在代码中,而不是直接操作图片文件。
python3完整源码:
# -*- encoding: utf-8 -*-
"""
@File : png2base64.py
@Time : 2019-11-25 10:16
"""
import base64
from tkinter import *
from tkinter.filedialog import askopenfilename,asksaveasfilename
class mainWin(Tk):
def __init__(self):
super().__init__()
self.refreshTime = StringVar()
self.msgCount = StringVar()
self.wm_title('Img 2 base64 Codes By Xiaox@2019 Tel:18627472125')
self.configure(background='white')
self.wm_minsize(640, 360) # 设置窗口最小化大小
self.wm_maxsize(1200, 600) # 设置窗口最大化大小
self.resizable(width=True, height=True) # 设置窗口宽度不可变,高度可变
self.protocol("WM_DELETE_WINDOW", self.on_closing)
frmTitle1 = Frame(width=640, height=32) # 顶部,左边区域2个按钮
frmTitle1.grid(row=0, column=0, padx=(4, 4), pady=(4, 0),sticky=W )
self.cbImgToBase64 = Button(frmTitle1, text='img2base64', font=('微软雅黑', 10), width=10,command=self.ImgToBase64 )
self.cbImgToBase64.grid(row=0, column=0, pady=0)
self.cbBase64ToImg = Button(frmTitle1, text='Base2Img', font=('微软雅黑', 10), width=10, command=self.Base64ToImg)
self.cbBase64ToImg.grid(row=0, column=1, pady=0)
frmMain = Frame(width=632, height=280, bg='#F3B61E') # 主体listbox
frmMain.grid(row=1, column=0, columnspan=2, padx=(4, 4), pady=(4, 0), sticky=W)
self.mleShow = Text(frmMain, height=22,width=92,borderwidth=2) # flat、groove、raised、ridge、solid、sunken
self.mleShow.grid(row=0, column=0, sticky=W)
scr1 = Scrollbar(frmMain, width=16, orient=VERTICAL)
self.mleShow.configure(yscrollcommand=scr1.set)
scr1['command'] = self.mleShow.yview
scr1.grid(row=0, column=1, sticky=NS)
frmBottom = Frame(width=394, height=32, bg='#F3B61E')
frmBottom.grid(row=2, column=0, columnspan=2, padx=(4, 4), pady=(4, 0), sticky=W)
self.lb2 = Label(frmBottom, text="图片文件与base64编码互相转换 V2019.1.01", font=("微软雅黑", 9), bg='#FFFFFF')
self.lb2.grid(row=1, column=0, sticky=W)
self.mainloop()
def ImgToBase64(self):
path_ = askopenfilename()
if path_:
strBase64 = imgTobase64(path_)
self.mleShow.insert("end",path_+'\n'+strBase64+'\n')
def Base64ToImg(self):
path_ = asksaveasfilename()
if path_:
strs = self.mleShow.get("0.0","end")
base64Toimg(strs,path_)
def on_closing(self):
self.destroy()
def imgTobase64(target):
res=''
with open(target, 'rb') as f:
base64_data = base64.b64encode(f.read())
res = 'data:image/png;base64'+base64_data.decode()
return res
def base64Toimg(strs,outfile):
imgdata=base64.b64decode(strs)
with open(outfile,'wb') as f:
f.write(imgdata)
if __name__ == '__main__':
mywin = mainWin()