“This is the 10th day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.

Town building figure

One thing I want to say

Think that year WHEN I can’t Python, do a certificate under XX certificate software, 5 yuan each time, feel blood loss, now long ability, do their own certificate, XX certificate according to bye-bye to you ~


Necessary configuration

Make sure the following libraries are installed.

Tkinter: to achieve GUI programming (text boxes, buttons, labels and other components to achieve GUI development).

PIL: The third party image processing library is very powerful. Due to the large number of users and its great popularity, it is almost considered as the official image processing library of Python. Pathlib: Object-oriented programming to represent file system paths. Ttkthemes: Tkinter themes pack to make your components look better. Pyinstaller: a very simple library to package.py files. Removebg: As the name suggests, a library dedicated to image matting.

Removebg configuration

Install the corresponding Python library

pip install -i https://pypi.douban.com/simple removebg
Copy the code

Access to API Key

Enter theRemovebgOfficial website, complete account registration.

After filling in the registration information, a verification email will be sent to your mailbox. After clicking enter, the following interface will be entered.

Click on theRemove image background

Click in the red circle againTool & API

Click on theGet API Key.

Click on theShowNow you can look at the API Key, and you’d better write it down for later use in your code.


Version of the interface

Modify the background color of the image

When RemoveBg is used, apI-key and error. Log must be specified. After removing the background, an xxx_no_bg.png image will be generated in the same folder as the original image, and a background plate with the specified color will be created.

# Change the background color of the photo
def replace_bg(read_path, save_path, api_key, bg_color='blue') :
    # Create an error. Log file in the program's current directory to save error messages.
    Path('error.log').touch()
    rmbg = RemoveBg(api_key, 'error.log')
    This will generate an xxx_no_bg.png image in the same folder as read_path
    rmbg.remove_background_from_img_file(read_path)
    img_no_bg = Image.open(read_path + '_no_bg.png')
    # create a new image, RGB for true color, 3 channels,
    The color can be red or hexadecimal color code #00FF00
    new_img = Image.new('RGB', img_no_bg.size, color=bg_color)
    Paste an image without a background onto an image with a background color
    new_img.paste(img_no_bg, (0.0, *img_no_bg.size), img_no_bg)
    new_img.save(save_path)
Copy the code

Resize the image

Read the Image, directly modify the Image size using resize, Image.ANTIALIAS set to high quality.

# Change the photo size 295x413(standard one inch)
def change_size(read_path, save_path, width=295, height=413) :
    image = Image.open(read_path)
    resized_image = image.resize((int(width), int(height)), Image.ANTIALIAS)
    resized_image.save(save_path)
Copy the code


Updated version

Set the window theme and title

The theme used here is adapta, the official recommendation, and the style is very nice.

window = ThemedTk(theme="adapta", fonts=True, themebg=True)
window.title('Certificate Photo Generator')
Copy the code

Add the select picture path component

Select the path of the image to be modified.

def selectFilePath() :
    global img_path
    # select file path to receive file address
    img_path = Path(filedialog.askopenfilename(title='Select original image'))
    x, y = Image.open(img_path).size
    entry4.insert(0.str(x) + 'x' + str(y))
    path1.set(img_path)
    
path1 = tk.StringVar()
entry1 = ttk.Entry(window, textvariable=path1, width=30)
entry1.insert(0.'Format required PNG')
button1 = ttk.Button(window,width=10, text = "Picture path", command = selectFilePath)
Copy the code

Add the select save path component

Select the save path of the modified picture, which is a folder.

def selectDirPath() :
    global dir_path
    # select file path to receive file address
    dir_path = Path(filedialog.askdirectory(title='Select image save path'))
    path2.set(dir_path)
    
path2 = tk.StringVar()
entry2 = ttk.Entry(window, textvariable=path2, width=30)
button2 = ttk.Button(window,width=10, text = "Save path", command = selectDirPath)
Copy the code

Add the select background color component

Here we use tkinter’s ColorChooser as a color palette, which, I have to say, is pretty darn good.

def ChooseColor() :
    global bg_color
    # return color codes in two formats, save hexadecimal only
    _, bg_color = colorchooser.askcolor(title='Color picker')
    path3.set(bg_color)
    
path3 = tk.StringVar()
entry3 = ttk.Entry(window, textvariable=path3, width=30)
button3 = ttk.Button(window, text='Background color', command=ChooseColor)
Copy the code

Add the Fill in picture size component

If you want to modify the picture, fill in this column, the default is the original size, here if you want to standard size, I suggest you baidu first, such as standard one inch is 295×413(standard one inch).

# Set image size to 295x413(standard one inch)
label = ttk.Label(window, text='Default size of original image, if you want to change it, please press [] inside \ format, such as [295x413] (standard one-inch photo)', wraplength=200, style='two.TLabel')
entry4 = ttk.Entry(window, width=30)
label1 = ttk.Label(window, text='Picture size', style='three.TLabel')
Copy the code

Add fill in the API-key component

Set the display value to “*” in the input box to hide the display value. This is the place to fill in the apI-key obtained above.

# fill in API - key
entry5 = ttk.Entry(window, width=30, show="*")
label2 = ttk.Label(window, text='api-key', style='three.TLabel')
Copy the code

Add control buttons

  • Modify background button: only modify the background of the original image, you need to specify the original image path, save path, background color, etc.
  • Modify size button: only modify the size of the original picture, you need to specify the original picture path, save path, picture size, etc.
  • Modify button at the same time: Modify the size and background of the original picture at the same time, you need to specify the original picture path, save path, picture color (optional), picture size (optional), if the color is not selected, the default size is blue, picture size is 295×413(standard one inch).
# Add "Simultaneously modify" button
button4 = ttk.Button(window, text = "Simultaneous modification", command=change_bg_size)
# Add "Modify Background" button
button5 = ttk.Button(window, text = "Modify background", command=replace_bg)
# Add "Resize" button
button6 = ttk.Button(window, text = "Resize", command=change_size)
Copy the code

Add output box display

The running result is displayed.

# Add output box display
tree = ttk.Treeview(height=1, show=("tree"."headings"))
Copy the code

Setting component Locations

Grid () is used here to set the location, or pick() can be used, but PERSONALLY I prefer the former.

main_label.grid(row = 0, column = 0, pady=5)
entry1.grid(row = 1, column = 0, pady=5)
button1.grid(row = 1, column = 1, padx=20)
entry2.grid(row = 2, column = 0, pady=5)
button2.grid(row = 2, column = 1, padx=20)
entry3.grid(row = 3, column = 0, pady=5)
button3.grid(row = 3, column = 1, padx=20)
label.grid(row = 4, column = 0, pady=5)
entry4.grid(row = 5, column = 0, pady=5)
label1.grid(row = 5, column = 1, pady=5)
entry5.grid(row = 6, column = 0, pady=5)
label2.grid(row = 6, column = 1, pady=5)
button4.grid(row = 7, column = 1, padx=5)
button5.grid(row = 7, column = 0, padx=5)
button6.grid(row = 8, column = 0, padx=5)
tree.grid(row=9, column=0, pady=5)
Copy the code

Setting component Styles

Modify your favorite styles from the original components.

label_style = ttk.Style()
label_style.configure("one.TLabel", font=(Microsoft Yahei.16.'bold'), foreground="red", background="yellow")

label_style1 = ttk.Style()
label_style1.configure("two.TLabel", font=(Microsoft Yahei.9), foreground="blue", background="yellow")    

label_style2 = ttk.Style()
label_style2.configure("three.TLabel", font=(Microsoft Yahei.10), foreground="blue", background="yellow")
Copy the code


The source code package

Although packaging has been covered many times in previous articles, I’ll cover it briefly for new readers. Make sure you have PyInstaller installed. If not, install it first.

pip install -i https://pypi.douban.com/simple pyinstaller 
Copy the code

The meanings of these parameters are as follows:

-f: Package a single file to generate a single file for deployment (default). If all the code is written in a.py file, do not use it if the project has multiple files

pyinstaller -F xxx.py
Copy the code

-d: Packages multiple files, producing a directory for deployment (default), which is used to package code written by the framework

Pyinstaller -d xxx.pyCopy the code

–key=keys: use keys for encryption packaging

pyinstaller --key=123456 -F xxx.py
Copy the code

-d: Generates the debug executable file

-p: used to add the package used by the program location, set the import path, can be used; (Linux uses 🙂 partitioning to specify multiple directories.

-w: Indicates that the command line is not opened when the program is started (only for Windows).

-c: Opens the console window, executes using the console subsystem, and opens the command line when the program starts (default)(Windows only)

-i: Add file.ico as an executable resource and change the program icon (Windows only)

Once the installation is complete, create a new folder, place the source files in this folder, and open itcmd.CD Go to the folder(Key), execute the following statement

The generated file structure is as follows

exeThe executable file is indistdirectory

❤️ Obtain the source code from ❤️

Search “Python New Horizons” on wechat and reply to “ID photo Generator” to obtain the source code. There are also a variety of learning resources waiting for you to receive oh ~.