图片美化软件开发

图片美化软件开发_第1张图片

# -*-coding:UTF-8 -*-
import tkinter,requests,base64,time
from tkinter import ttk
from ttkthemes import *
from tkinter.filedialog import *
from tkinter.messagebox import *
from PIL import ImageGrab
from PIL import Image, ImageTk
apiidchk = '21746'
APIKey_wordchk = 'e51heKPO6AzBd'
secretKey_wordchk = "6oIpx6UiNxT5nWr8ieasSxR"
global authhost
authhost = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=e51hk8lO6nzBd&client_secret=6oI6U8iMeasSxR'
def selectpic():
    global oldpicPath
    oldpicPath = askopenfilename()
    filefrontnameandpath = oldpicPath.split('.')[-2]
    global oldimgfilefrontname
    oldimgfilefrontname = filefrontnameandpath.split('/')[-1]
    print(oldimgfilefrontname)
    img = Image.open(oldpicPath)
    global photo,image_Label
    photo = ImageTk.PhotoImage(img)
    image_Label = tkinter.Label(txmh, image=photo,width=1280,height=600)
    image_Label.grid(row=0, column=1, rowspan=20,columnspan=20)
    txmh.update()
def HeibaiTXShangse():#黑白图像上色
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/colourize?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    params = {"image": myimg}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['image'])
    img_str = response.json()['image']
    img_data = base64.b64decode( img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng=asksaveasfilename(initialfile='%s-黑白图上色后.png'%oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)

def Tx2cartoon():#卡通画风格
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    params = {"image": myimg,"option":"cartoon"}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['image'])
    img_str = response.json()['image']
    img_data = base64.b64decode( img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng=asksaveasfilename(initialfile='%s-变卡通画风后.png'%oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)
def zdy_bg():#zdy bg
    # from PIL import Image
    showinfo('注意', '已经选择图片(透明),现在选择背景,输出混合图层画面。.')
    # infile1 = '01.png'
    # infile1=askopenfilename()
    # oldpicPath=infile1
    infile1=oldpicPath
    # infile2 = '02.png'
    infile2 = askopenfilename()
    # outfile = '03.png'
    outfile =asksaveasfilename(initialfile='%s-混合后.png' % oldimgfilefrontname, defaultextension='.png')

    # im1 = Image.open(infile1) # 读取前景图片
    # r, g, b, mask = im1.split() # 提取图片中包含的透明通道
    #
    # im2 = Image.open(infile2) # 读取背景图片
    # image = im2.copy() # 复制背景图片,这样子原图不会被修改
    # image.paste(im1, (100, 90), mask) # 指定前景图片粘贴到背景图片上的位置(100, 100)
    # image.save(outfile) # 保存输出图片
    def CompositePng(png1, png2, out):
        """
        将两张PNG图片进行叠加,核心运用的函数是Image.composite
        png1:前景
        png2:背景
        """
        im1 = Image.open(png1)
        r, g, b, a = im1.split()  # 提取透明通道
        w1, h1 = im1.size
        im2 = Image.open(png2)
        w2, h2 = im2.size
        # todo 这个if-else结构的操作其实就是将前景和背景图片的图片尺寸做个修改,以防尺寸不一样带来的错误
        if w2 >= h2:
            radio = h2 / h1
            w3 = int(w2 / radio)
            h3 = int(h2 / radio)
            im2 = im2.resize((w3, h3))  # PNG图片大小的缩放
            left = int((w3 - w1) / 2)
            im2 = im2.crop(((left), (0), (left + w1), (h1)))  # PNG图片大小的裁剪
        else:
            radio = w2 / w1
            w3 = int(w2 / radio)
            h3 = int(h2 / radio)
            im2 = im2.resize((w3, h3))
            upper = int((h3 - h1) / 2)
            im2 = im2.crop(((0), (upper), (w1), (upper + h1)))
        im = Image.composite(im1, im2, a)  # 使用image.paste(im1, (100, 100), mask)函数可以指定合成的位置
        im = im.convert('RGB')
        im.save(out, format='JPEG', quality=50)

    CompositePng(infile1, infile2, outfile)
    os.startfile(outfile)
def zdy_style():#zdy风格
    showinfo('注意', '先点击选择图片的按钮,选择第一个图,然后点击 自定义风格 选择第二个图片,输出混合图层画面。.')
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/customize_stylization?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')

    newpicPath = askopenfilename()
    fnew = open(newpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    myimgnew = base64.b64encode(fnew.read())
    params = {"image": myimg,"style":myimgnew}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['image'])
    img_str = response.json()['image']
    img_data = base64.b64decode( img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng=asksaveasfilename(initialfile='%s-自定义风后.png'%oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)
def Tx2pencil_heibai():#黑白铅笔风格
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    params = {"image": myimg,"option":"pencil"}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['image'])
    img_str = response.json()['image']
    img_data = base64.b64decode( img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng=asksaveasfilename(initialfile='%s-黑白铅笔风后.png'%oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)
def Tx2warm():#caise 彩色糖块油画风格
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    params = {"image": myimg,"option":"warm"}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['image'])
    img_str = response.json()['image']
    img_data = base64.b64decode( img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng=asksaveasfilename(initialfile='%s-彩糖油画风后.png'%oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)
def Tx2wave():#caise 神奈川冲浪里油画风格
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    params = {"image": myimg,"option":"wave"}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['image'])
    img_str = response.json()['image']
    img_data = base64.b64decode( img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng=asksaveasfilename(initialfile='%s-神奈川冲浪里油画风.png'%oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)
def Tx2lavender():#caise 薰衣草油画风格
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    params = {"image": myimg,"option":"lavender"}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['image'])
    img_str = response.json()['image']
    img_data = base64.b64decode( img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng=asksaveasfilename(initialfile='%s-薰衣草油画风.png'%oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)
def Tx2mononoke():#caise 奇异油画风格
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    params = {"image": myimg,"option":"mononoke"}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['image'])
    img_str = response.json()['image']
    img_data = base64.b64decode( img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng=asksaveasfilename(initialfile='%s-奇异油画风.png'%oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)
def Tx2scream():#caise 呐喊油画风格
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    params = {"image": myimg,"option":"scream"}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['image'])
    img_str = response.json()['image']
    img_data = base64.b64decode( img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng=asksaveasfilename(initialfile='%s-呐喊油画风.png'%oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)
def Tx2gothic():#caise 哥特油画风格
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    params = {"image": myimg,"option":"gothic"}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['image'])
    img_str = response.json()['image']
    img_data = base64.b64decode( img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng=asksaveasfilename(initialfile='%s-哥特油画风.png'%oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)

def Tx2RXdmh():#caise 人像动漫化
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    params = {"image": myimg}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['image'])
    img_str = response.json()['image']
    img_data = base64.b64decode( img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng=asksaveasfilename(initialfile='%s-人像动漫化.png'%oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)
def quwu():#caise 图像去雾
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/dehaze?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    params = {"image": myimg}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['image'])
    img_str = response.json()['image']
    img_data = base64.b64decode( img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng=asksaveasfilename(initialfile='%s-图像去雾.png'%oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)
def xuduopng2jpg():
    from os import listdir
    from PIL import Image
    showinfo('提示', '选择一个文件夹,里边放png 图片,稍后同目录会输出jpg图片.')
    xuduopng_pictures = askdirectory()
    # # num = 1
    # global fnamepng
    # ims = [Image.open(xuduopng_pictures + '\\' + fnamepng) for fnamepng in listdir(xuduopng_pictures) if fnamepng.endswith(".png")]  # 打开路径下的所有图片
    #
   

    def png2jpg(filename, output_filename):
        im = Image.open(filename).convert('RGB')
        im.save(output_filename)
    dirname = xuduopng_pictures
    dirnameout = xuduopng_pictures
    filenames = os.listdir(dirname)
    for filename in filenames:
        if filename.endswith('png')or filename.endswith('PNG'):
            base, ext = filename.split('.')
            new_name = base + '.jpg'
            filename = dirname + '/' + filename
            output_filename = dirnameout + '/' + new_name
            png2jpg(filename, output_filename)
    showinfo('提示', '完成批量png转化jpg')

def pinjiezx():
    from PIL import Image
    from os import listdir
    ''' result_path_target 图片存放目标路径  cut_pictures 待拼接图片存放路径  num 图片命名以数字按序增加  '''
    # cut_pictures = r'.\1'
    showinfo('提示', '选择一个文件夹,里边放你需要纵向合并的jpg 图片,稍后会输出纵向拼接长图,它会包含那些图.')
    cut_pictures = askdirectory()
    # result_path_target = r'.\1'
    result_path_target = cut_pictures

    # e1workwherewzsbtp_laowendang.delete(0, 'end')
    # e1workwherewzsbtp_laowendang.insert(0, cut_pictures)
    num = 1
    ims = [Image.open(cut_pictures + '\\' + fn) for fn in listdir(cut_pictures) if fn.endswith(".jpg")]  # 打开路径下的所有图片
    width, height = ims[0].size  # 获取拼接图片的宽和高
    print(ims)
    result = Image.new(ims[0].mode, (width, height * len(ims)))
    for j, im in enumerate(ims):
        result.paste(im, box=(0, j * height))
    print(j)
    result.save(result_path_target + '\\' + 'mylongpic.jpg')
    os.startfile(result_path_target + '\\' + 'mylongpic.jpg')
def qudiwen():
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/doc_repair?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    params = {"image": myimg}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['result'])
    img_str = response.json()['result']
    img_data = base64.b64decode(
        img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng = asksaveasfilename(initialfile='%s-去除底纹.png' % oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)

def Wusunfangda():#caise 无损放大
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/image_quality_enhance?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    params = {"image": myimg}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['image'])
    img_str = response.json()['image']
    img_data = base64.b64decode( img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng=asksaveasfilename(initialfile='%s-无损放大.png'%oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)

def LashenXiufu():#caise 拉伸图恢复
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/stretch_restore?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    params = {"image": myimg}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['image'])
    img_str = response.json()['image']
    img_data = base64.b64decode( img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng=asksaveasfilename(initialfile='%s-拉伸图恢复.png'%oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)
def QinxiduZQ():#caise 清晰度增强
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/image_definition_enhance?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    params = {"image": myimg}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['image'])
    img_str = response.json()['image']
    img_data = base64.b64decode( img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng=asksaveasfilename(initialfile='%s-清晰度增强.png'%oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)
def SecaiZQ():#caise 色增强
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/color_enhance?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    params = {"image": myimg}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['image'])
    img_str = response.json()['image']
    img_data = base64.b64decode( img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng=asksaveasfilename(initialfile='%s-色彩增强.png'%oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)
import json,urllib.parse
def quyubetter():
    showinfo('注意', '先点击选择图片的按钮,然后在画图软件左or右下角记录图片去除区域的坐标后填写 然后本点击区域去除按钮。.')   #
    # os.startfile(os.getcwd() + "\\goldtools\\mspaint.exe")
    try:
        if var1zuoshang_x.get() == '去除区域的左上角x坐标' or var2zuoshang_y.get() == '左上角y坐标' or var3youshang_x.get() == '右上角x坐标' or var4zuoxia_y.get() == '左下角y坐标':
            os.startfile(os.getcwd() + "\\goldtools\\mspaint.exe")
        def get_file_content_as_base64(path, urlencoded=False):
            """  获取文件base64编码  :param path: 文件路径  :param urlencoded: 是否对结果进行urlencoded  :return: base64编码信息  """
            with open(path, "rb") as f:
                content = base64.b64encode(f.read()).decode("utf8")
                if urlencoded:
                    content = urllib.parse.quote_plus(content)
            return content
        myimg2=get_file_content_as_base64(oldpicPath)
        response_token = requests.get(authhost)
        token = response_token.json()['access_token']   #print(token)
        url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/inpainting?access_token=' + token   # 二进制方式打开图片文件
        f = open(oldpicPath, 'rb')  # myimg = base64.b64encode(f.read())    # params = {"image": myimg}
        mytx_zuoshang_x=int(var1zuoshang_x.get())
        left = mytx_zuoshang_x
        mytx_zuoshang_y =int(var2zuoshang_y.get())
        top = mytx_zuoshang_y
        youshang_x=int(var3youshang_x.get())
        # youshang_y=146    # zuoxia_x=478
        zuoxia_y=int(var4zuoxia_y.get())
        width=youshang_x-mytx_zuoshang_x
        height=zuoxia_y-mytx_zuoshang_y
        print('left:%d'%left)
        print('top:%d'%top)
        print('width:%d'%width)
        print('height:%d'%height)   # params = {"rectangle":[{"width":width,"top":top,"height":height,"left":left}],"image":myimg}
        payload = json.dumps({
            "rectangle": [
                {
                    "width": width,
                    "height": height,
                    "top": top,
                    "left": left
                }
            ],
            "image": myimg2
        })
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        } # headers = {'content-type': 'application/x-www-form-urlencoded'}  # headers = {'content-type': 'application/json'}   # response = requests.post(url, data=payload, headers=headers)
        response = requests.request("POST", url, headers=headers, data=payload)
        # if response:   #     print(response.json()['image'])
        img_str = response.json()['image']    # print(img_str)
        img_data = base64.b64decode(img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
        savepng = asksaveasfilename(initialfile='%s-区域去除.png' % oldimgfilefrontname, defaultextension='.png')
        with open(savepng, 'wb') as fout:
            fout.write(img_data)
        time.sleep(1)
        fout.close()
        os.startfile(savepng)
    except:
        showinfo('注意', '缺少区域坐标参数或其他问题..')
def quzao():#caise 图像去噪
    response_token = requests.get(authhost)
    token = response_token.json()['access_token']
    print(token)
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/denoise?access_token=' + token
    # 二进制方式打开图片文件
    f = open(oldpicPath, 'rb')
    myimg = base64.b64encode(f.read())
    zao = var6base2lie.get()
    params = {"image": myimg, "option":zao}
    # params = "{\"rectangle\":[{\"width\":92,\"top\":95,\"height\":36,\"left\":543}],\"image\":\"%s\"}"%myimg
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        print(response.json()['result'])
    img_str = response.json()['result']
    img_data = base64.b64decode( img_str)  # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
    savepng=asksaveasfilename(initialfile='%s-图像去噪.png'%oldimgfilefrontname, defaultextension='.png')
    with open(savepng, 'wb') as fout:
        fout.write(img_data)
    time.sleep(1)
    fout.close()
    os.startfile(savepng)
def sgkoutu():
#https://www.remove.bg/dashboard#api-key
# [email protected] Syke1
    content = oldpicPath
    content2=content.replace('\n','')
    #file = get_file_content(content2)

    response = requests.post(
        'https://api.remove.bg/v1.0/removebg',
        files={'image_file': open(content2, 'rb')},  # 这里填写图片路径
        # 这里填写图片路径
        data={'size': 'auto'},
        headers={'X-Api-Key': 'BMzLSBqJ1bLV4Bv4gwbm2MTq'},  # 这里替换成你的api key
    )
    outfilenamepng = asksaveasfilename(title='保存抠图', initialfile='未命名抠图.png', defaultextension='.png')
    save_path = outfilenamepng
    if response.status_code == requests.codes.ok:
        with open(save_path, 'wb') as out:
            out.write(response.content)
    else:
        print("Error:", response.status_code, response.text)
    os.startfile(save_path)
class MyCapture:
    def __init__(self, png):
        # 变量X和Y用来记录鼠标左键按下的位置
        self.X = tkinter.IntVar(value=0)
        self.Y = tkinter.IntVar(value=0)
        # 屏幕尺寸
        screenWidth = txmh.winfo_screenwidth()
        screenHeight = txmh.winfo_screenheight()
        # 创建顶级组件容器
        self.top = tkinter.Toplevel(txmh, width=screenWidth, height=screenHeight)
        # 不显示最大化、最小化按钮
        self.top.overrideredirect(True)
        self.canvas = tkinter.Canvas(self.top, bg='white', width=screenWidth, height=screenHeight)
        # 显示全屏截图,在全屏截图上进行区域截图
        self.image = tkinter.PhotoImage(file=png)
        self.canvas.create_image(screenWidth // 2, screenHeight // 2, image=self.image)

        # 鼠标左键按下的位置
        def onLeftButtonDown(event):
            self.X.set(event.x)
            self.Y.set(event.y)
            # 开始截图
            self.sel = True

        self.canvas.bind('', onLeftButtonDown)

        # 鼠标左键移动,显示选取的区域
        def onLeftButtonMove(event):
            if not self.sel:
                return
            global lastDraw
            try:
                # 删除刚画完的图形,要不然鼠标移动的时候是黑乎乎的一片矩形
                self.canvas.delete(lastDraw)
            except Exception as e:
                pass
            lastDraw = self.canvas.create_rectangle(self.X.get(), self.Y.get(), event.x, event.y, outline='black')

        self.canvas.bind('', onLeftButtonMove)

        # 获取鼠标左键抬起的位置,保存区域截图
        def onLeftButtonUp(event):
            self.sel = False
            try:
                self.canvas.delete(lastDraw)
            except Exception as e:
                pass
            time.sleep(0.1)
            # 考虑鼠标左键从右下方按下而从左上方抬起的截图
            left, right = sorted([self.X.get(), event.x])
            top, bottom = sorted([self.Y.get(), event.y])
            pic = ImageGrab.grab((left + 1, top + 1, right, bottom))
            # 弹出保存截图对话框
            fileName2 = tkinter.filedialog.asksaveasfilename(title='保存截图', filetypes=[('JPG files', '*.jpg')])
            if fileName2:
                pic.save(fileName2 + '.jpg')
            # 关闭当前窗口
            os.startfile(fileName2+ '.jpg')
            self.top.destroy()

        self.canvas.bind('', onLeftButtonUp)
        self.canvas.pack(fill=tkinter.BOTH, expand=tkinter.YES)
    # 开始截图

def pscrjietu():
    # 最小化主窗口
    txmh.state('icon')
    time.sleep(0.2)
    filename = 'temp.png'
    im = ImageGrab.grab()
    im.save(filename)
    im.close()
    # 显示全屏幕截图
    w = MyCapture(filename)
    b16jietu.wait_window(w.top)
    # 截图结束,恢复主窗口,并删除临时的全屏幕截图文件
    txmh.state('normal')
    os.remove(filename)
import webbrowser
def AIgetImage():
    tgttitle = var7tgtget.get()
    style = var7base2liest.get()
    import wenxin_api  # 可以通过"pip install wenxin-api"命令安装
    from wenxin_api.tasks.text_to_image import TextToImage
    wenxin_api.ak = "agjkbF4ygqtlqcyUjsk" wenxin
    wenxin_api.sk = "wxGFQHUTk0eGIyDh"
    input_dict = {
        "text": tgttitle,
        "style": style,
        # "style": "写实风格",
        "resolution": "1024*1024",
        "num": 2,
    }
    try:
        rst = TextToImage.create(**input_dict)['imgUrls']
        time.sleep(3)
        showinfo('提示', '耐心等待-30秒后调用浏览器打开2张你要的主题图片。')
        rst1 = rst[0]
        rst2 = rst[1]
        # rst3=rst[2]
        # rst4 = rst[3]
        rst5='https://wenxin.baidu.com/ernie-vilg'
        print(rst)
        # play_url01 = rst1
        webbrowser.open(rst5)
        time.sleep(2)
        webbrowser.open(rst1)
        webbrowser.open(rst2)
        # webbrowser.open(rst3)
        # webbrowser.open(rst4)
    except:
        showinfo('提示', '失败,再来一次.')

def AIgetImage2(): #BDY--aigc-image
    import requests
    import json
    tgttitle = var7tgtget.get()
    global style
    style = var7base2liest.get()
    showinfo('提示', '填写图片标题内容需求-比如:苹果,然后右边选择风格,比如写实风格。耐心等16秒后调用浏览器打开你要的主题图片。')
    app_id_AIgetImage2='3211' 百度云
    app_apikey_AIgetImage2 ='wGVGQuDO'
    app_sec_key_AIgetImage2='HkPPGaFtrVcxlui7'
    authhostai = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=wGVGQf376KBuzujfDO&client_secret=HkPIf1MgPVIqoxlui7'
    try:
        response_token = requests.get(authhostai)
        token = response_token.json()['access_token']
        print(token)
    except:
        showinfo('提示', '失败,再来一次.可能网络问题.')

    def mainAIgetImage2():
        url = "https://aip.baidubce.com/rpc/2.0/ernievilg/v1/txt2img?access_token=" + token

        payload = json.dumps({
            "text": tgttitle,
            "style": style,
            "resolution": "1024*1024",
            "num": 1
        })
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }

        response = requests.request("POST", url, headers=headers, data=payload)

        print(response.json()['data']['taskId'])
        global myaizpid
        myaizpid=response.json()['data']['taskId']
    try:
        mainAIgetImage2()
    except:
        showinfo('提示', '失败,再来一次.可能网络问题.')
    #----------------------
    API_KEY = "wGVGDO"
    SECRET_KEY = "HkPPGaFtIf1Vcxlui7"
    def maingetai():
        url_ai = "https://aip.baidubce.com/rpc/2.0/ernievilg/v1/getImg?access_token=" + token

        payload = json.dumps({
            "taskId": myaizpid
        })
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }

        response = requests.request("POST", url_ai, headers=headers, data=payload)

        print(response.json()['data']['img'])
        global myaizplink
        myaizplink = response.json()['data']['img']
    try:
        maingetai()
    except:
        showinfo('提示', '失败,再来一次.可能网络问题.')
    time.sleep(16)
    maingetai()
    webbrowser.open(myaizplink)


def jietumode():
    txmh.geometry('160x100+180+100')
    txmh.wm_attributes("-topmost", 1)


def meitumode():
    txmh.geometry('1680x750+180+100')
    txmh.wm_attributes("-topmost", 0)


    txmh.update()
txmh = ThemedTk(theme="radiance", toplevel=True, themebg=True)  # txmh= tkinter.Tk()
txmh.geometry('160x100+250+100')
# txmh.geometry('1440x768+250+100')
txmh.iconbitmap('luo4.ico')
txmh.title('图像美化 1.6 Rogabet Beutify')
b1xt=ttk.Button(txmh,text="选择图片",width=15,command=selectpic)
b1xt.grid(row=1,column=0)
b16jietu=ttk.Button(txmh,text="框选截图",width=15,command=pscrjietu)
b16jietu.grid(row=0,column=0)

b0chsmall2=ttk.Button(txmh,text="截图模式",width=15,command=jietumode)
b0chsmall2.grid(row=3,column=0)

b0chbig2=ttk.Button(txmh,text="美图模式",width=15,command=meitumode)
b0chbig2.grid(row=2,column=0)


b3warm=ttk.Button(txmh,text="彩糖油画风",width=15,command=Tx2warm)
b3warm.grid(row=4,column=0)

b4wave=ttk.Button(txmh,text="神奈川冲浪里油画",width=15,command=Tx2wave)
b4wave.grid(row=5,column=0)
b1xtss=ttk.Button(txmh,text="黑白图上色",width=15,command=HeibaiTXShangse)
b1xtss.grid(row=6,column=0)

b5lavender=ttk.Button(txmh,text="薰衣草油画风",width=15,command=Tx2lavender)
b5lavender.grid(row=7,column=0)

b6mononoke=ttk.Button(txmh,text="奇异油画风格",width=15,command=Tx2mononoke)
b6mononoke.grid(row=8,column=0)

b7scream=ttk.Button(txmh,text="呐喊油画风格",width=15,command=Tx2scream)
b7scream.grid(row=9,column=0)

b8gothic=ttk.Button(txmh,text="哥特油画风格",width=15,command=Tx2gothic)
b8gothic.grid(row=10,column=0)

b10quwu=ttk.Button(txmh,text="图像去雾",width=15,command=quwu)
b10quwu.grid(row=11,column=0)

b11Wusunfangda=ttk.Button(txmh,text="无损放大",width=15,command=Wusunfangda)
b11Wusunfangda.grid(row=12,column=0)

b12LashenXiufu=ttk.Button(txmh,text="拉伸图恢复",width=15,command=LashenXiufu)
b12LashenXiufu.grid(row=13,column=0)

b12QinxiduZQ=ttk.Button(txmh,text="清晰度增强",width=15,command=QinxiduZQ)
b12QinxiduZQ.grid(row=14,column=0)

b13SecaiZQ=ttk.Button(txmh,text="色彩增强",width=15,command=SecaiZQ)
b13SecaiZQ.grid(row=15,column=0)

b15sgkoutu=ttk.Button(txmh,text="傻瓜抠图",width=15,command=sgkoutu)
b15sgkoutu.grid(row=16,column=0)
b3pencil_qb=ttk.Button(txmh,text="黑白铅笔风",width=15,command=Tx2pencil_heibai)
b3pencil_qb.grid(row=17,column=0)

var7base2liest = StringVar()
sizeofzaost = ttk.Entry(txmh,show=None,textvariable=var7base2liest,width=22)
sizeofzaost.grid(row=18,column=3)
sizeofzaost.insert(0,'填或(右边)选-写实风格等')

var7tgtget = StringVar()
txtoftgtget = ttk.Entry(txmh,show=None,textvariable=var7tgtget,width=22)
txtoftgtget.grid(row=18,column=2)
txtoftgtget.insert(0,'这里填 内容标题')

b2cartoon=ttk.Button(txmh,text="BD-AI创作2",width=15,command=AIgetImage)
b2cartoon.grid(row=18,column=1)

b2cartoon2=ttk.Button(txmh,text="BDY-AI创作",width=15,command=AIgetImage2)
b2cartoon2.grid(row=18,column=0)

rikwketc=('写实风格','古风','二次元','油画','未来主义','水彩画','卡通画','蒸汽波艺术','浮世绘','赛博朋克','探索无限','像素风格','概念艺术','超现实主义')
def printinfostock_style():
    kxiantype=stylespin.get()
    print(kxiantype)
    if kxiantype=='写实风格':
        style='写实风格'
        sizeofzaost.delete(0,'end')
        sizeofzaost.insert(0,'写实风格')
    if kxiantype=='古风':
        style ='古风'
        sizeofzaost.delete(0, 'end')
        sizeofzaost.insert(0, '古风')
    if kxiantype=='二次元':
        style ='二次元'
        sizeofzaost.delete(0, 'end')
        sizeofzaost.insert(0, '二次元')
    if kxiantype=='油画':
        style ='油画'
        sizeofzaost.delete(0, 'end')
        sizeofzaost.insert(0, '油画')
    if kxiantype=='未来主义':
        style ='未来主义'
        sizeofzaost.delete(0, 'end')
        sizeofzaost.insert(0, '未来主义')
    if kxiantype=='水彩画':
        style ='水彩画'
        sizeofzaost.delete(0, 'end')
        sizeofzaost.insert(0, '水彩画')
    if kxiantype=='卡通画':
        style ='卡通画'
        sizeofzaost.delete(0, 'end')
        sizeofzaost.insert(0, '卡通画')
    if kxiantype=='蒸汽波艺术':
        style ='蒸汽波艺术'
        sizeofzaost.delete(0, 'end')
        sizeofzaost.insert(0, '蒸汽波艺术')
    if kxiantype=='浮世绘':
        style ='浮世绘'
        sizeofzaost.delete(0, 'end')
        sizeofzaost.insert(0, '浮世绘')
    if kxiantype=='赛博朋克':
        style ='赛博朋克'
        sizeofzaost.delete(0, 'end')
        sizeofzaost.insert(0, '赛博朋克')
    if kxiantype=='探索无限':
        style ='探索无限'
        sizeofzaost.delete(0, 'end')
        sizeofzaost.insert(0, '探索无限')
    if kxiantype=='像素风格':
        style ='像素风格'
        sizeofzaost.delete(0, 'end')
        sizeofzaost.insert(0, '像素风格')
    if kxiantype=='概念艺术':
        style ='概念艺术'
        sizeofzaost.delete(0, 'end')
        sizeofzaost.insert(0, '概念艺术')
    if kxiantype=='超现实主义':
        style ='超现实主义'
        sizeofzaost.delete(0, 'end')
        sizeofzaost.insert(0, '超现实主义')
stylespin=ttk.Spinbox(txmh,values=rikwketc,command=printinfostock_style,width=10)
stylespin.grid(row=18,column=4)

b14quzao=ttk.Button(txmh,text="图像去噪",width=15,command=quzao)
b14quzao.grid(row=19,column=0)

var6base2lie = StringVar()
sizeofzao = ttk.Entry(txmh,show=None,textvariable=var6base2lie,width=20)
sizeofzao.grid(row=19,column=1)
sizeofzao.insert(0,'去噪系数50-200')

b11qudiwen=ttk.Button(txmh,text="文档图片去底纹",width=15,command=qudiwen)
b11qudiwen.grid(row=19,column=2)

b11pinjiezx=ttk.Button(txmh,text="多图片纵向拼接",width=15,command=pinjiezx)
b11pinjiezx.grid(row=19,column=3)

b11xuduopng2jpg=ttk.Button(txmh,text="批量PNG转JPG",width=12,command=xuduopng2jpg)
b11xuduopng2jpg.grid(row=19,column=4)

b15quyub=ttk.Button(txmh,text="区域去除",width=15,command=quyubetter)
b15quyub.grid(row=22,column=0)


var1zuoshang_x = StringVar()
varzuoshang_x = ttk.Entry(txmh,show=None,textvariable=var1zuoshang_x,width=20)
varzuoshang_x.grid(row=22,column=1)
varzuoshang_x.insert(0,'去除区域的左上角x坐标')

var2zuoshang_y = StringVar()
varzuoshang_y = ttk.Entry(txmh,show=None,textvariable=var2zuoshang_y,width=10)
varzuoshang_y.grid(row=22,column=2)
varzuoshang_y.insert(0,'左上角y坐标')

var3youshang_x = StringVar()
varyuoshang_x = ttk.Entry(txmh,show=None,textvariable=var3youshang_x,width=10)
varyuoshang_x.grid(row=22,column=3)
varyuoshang_x.insert(0,'右上角x坐标')

var4zuoxia_y = StringVar()
varzuoxia_y = ttk.Entry(txmh,show=None,textvariable=var4zuoxia_y,width=10)
varzuoxia_y.grid(row=22,column=4)
varzuoxia_y.insert(0,'左下角y坐标')


# b16gpt=ttk.Button(txmh,text="GPT-AI创作",width=15,command=AIgetImage2)
# b16gpt.grid(row=21,column=0)


b9RXdmh=ttk.Button(txmh,text="人像动漫化",width=15,command=Tx2RXdmh)
b9RXdmh.grid(row=20,column=0)
b2cartoon=ttk.Button(txmh,text="卡通画风格",width=15,command=Tx2cartoon)
b2cartoon.grid(row=20,column=1)
bzdyfg=ttk.Button(txmh,text="自定义风格",width=15,command=zdy_style)
bzdyfg.grid(row=20,column=2)
bzdyfgbg=ttk.Button(txmh,text="自定义背景",width=15,command=zdy_bg)
bzdyfgbg.grid(row=20,column=3)
txmh.mainloop()
'''
   # image_Label.forget()
    # imgsave_open = Image.open(savepng)
    # imgsave_png = ImageTk.PhotoImage(imgsave_open)
    # label_imgout = tkinter.Label(txmh, image=imgsave_png)
    # label_imgout.grid(row=2, column=1, columnspan=2)
    # txmh.update()
'''

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