将自己学的贴一下
import base64
import tkinter as mytk
import tkinter.filedialog as dialog
import requests
from PIL import Image, ImageTk # pip install pillow
from PIL.Image import Resampling
window = mytk.Tk() # 实例化对象
imgpath = mytk.StringVar()
def get_imgpath():
files_img_path = dialog.askopenfilename(title='选择图片', initialdir='.',
filetypes=(('图像文件', '*.jpg;*.jpeg;*.bmp;*.png'), ('所有文件', '*.*')))
if files_img_path == ' ':
pass
else:
imgpath.set(files_img_path)
image = Image.open(files_img_path)
img_re = image.resize((240, 320), Resampling.BILINEAR)
img = ImageTk.PhotoImage(img_re)
canvas.create_image(0, 0, image=img, anchor=mytk.NW)
canvas.image = img
def get_carton():
img_path = text1.get()
if img_path == '':
pass
else:
with open(img_path, 'rb') as fp:
imgdata = base64.b64encode(fp.read())
# 编码为base64格式二进制文件
'''
获取属于你自己的访问令牌(access_token)
需要API Key和Secret Key,在官网获取,包含在host内
'''
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id' \
'=your API Key&client_secret=your Secret Key'
response = requests.get(host)
access_token = response.json()['access_token']
request_url = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime"
params = {"image": imgdata}
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers) # 将图片包含进表单内提交
data_json = response.json() # 获取json文件
print('获取到json')
img_base = data_json['image'] # 提取返回的图片
print('获取到编码')
img_res = base64.b64decode(img_base) # 解码图片
print('正在创建画布')
with open('D:\Scrapy\\' + img_path.split('/')[-1], 'wb') as file: # 解码的图片写入到文件夹
file.write(img_res)
file.close()
new_img = Image.open('D:\Scrapy\\' + img_path.split('/')[-1])
new_img = new_img.resize((240, 320), Image.BILINEAR) # 尺寸调整
out_img = ImageTk.PhotoImage(new_img)
canvas2.create_image(0, 0, image=out_img, anchor=mytk.NW)
canvas2.image = out_img # 在第二张画布输出图片
# 主窗口
window.title("获取你的动漫脸")
sc_wid = window.winfo_screenwidth() # 1536
sc_heig = window.winfo_screenheight() # 864
win_wid, win_heig = 800, 450
init_x = (sc_wid - win_wid) / 2 # 368
init_y = (sc_heig - win_heig) / 2 # 207
window.geometry('%dx%d+%d+%d' % (win_wid, win_heig, init_x, init_y))
# 按键
button1 = mytk.Button(window, text='载入图片', font=('微软雅黑', 12, 'bold'), command=get_imgpath)
button1.place(x=2, y=3)
text1 = mytk.Entry(window, textvariable=imgpath, font=('微软雅黑', 12, 'bold'), width=35)
text1.place(x=150, y=3)
button2 = mytk.Button(window, text='开始生成', font=('微软雅黑', 12, 'bold'), command=get_carton)
button2.place(x=500, y=3)
# 画布
canvas = mytk.Canvas(window, width=240, height=320)
canvas.place(x=150, y=100)
canvas2 = mytk.Canvas(window, width=240, height=320)
canvas2.place(x=400, y=100)
window.mainloop() # 持续运行