Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

At the same time, I participated in the “Digitalstar Project” to win the creative gift package and challenge the creative incentive money

Talk in front of the

This article is on the article two years ago you still in @wechat official? I’m going to teach you to use Python to generate an optimization of the wechat avatar you want, while updating the material.

I wish you a happy National Day in advance.

I remember at that time, it was the 19th National Day, the whole country celebrated the 70th anniversary of the founding of the People’s Republic of China, somehow, many friends appeared in the circle of friendsWechat officialAdd a five-star red flag to your profile picture.Almost point believe true, in fact is false, so, WE still do it honestly.

See this, if you just want to quickly generate a National Day image on wechat, do not want to know the relevant technology, it is very simple, directly click the card below, follow the public account: takeout movie entertainment, click the menu bar National Day image, you can be generated.

After demand analysis at that time, we finally chose the method of image merging. Today, we mainly optimize the following points based on the previous program:

1. Add image templates. There are currently 6 templates

2, console added text menu, automatic reading profile picture, template file, want to choose who choose

3, add GUI program software interface, choose what picture to upload, choose what template

4. Add a Web port and choose your own profile picture and template to upload

Recently, I realized that a long article is actually not conducive to learning and reading. In this era of fragmented learning, except for students, it may be difficult for anyone to concentrate on studying for several hours, let alone writing on wechat technology. The dense code can also make you feel dizzy.

Therefore, every time I have a project, I will try to share it in pieces and make it into a small series, so that I can polish each part of the series more carefully. After all, I want to make sure that everyone can understand it.

The wechat profile picture processing series will also be divided into many chapters, for example, there are now three clear chapters:

  • Celebrate National Day wechat avatar processing so simple? A few lines of code in a second
  • Write a GUI interface to qingguo Micro channel avatar processing program
  • Flask implements qing-guo wechat avatar processing program web excuses

Celebrate National Day wechat avatar processing so simple? A few lines of code in a second

Now we are going to write the simplest and most core part, write the code according to the requirements, then talk about the requirements, and split the function:

Need: Paste the template picture onto wechat profile picture and save the processed fileSplit required functions: 1. Read wechat profile picture and template picture; 2. Adjust the size of the two images to be the same (700)*700) 3. Paste the template picture on wechat profile picture 4. Save the processed fileCopy the code

Based on the above feature splitting, we can implement the code step by step. 0) Import related packages

from PIL import Image
Copy the code

1) Read wechat profile picture and template picture

Open image template
img1 = Image.open("./img/7.jpg")
img1 = img1.convert('RGBA')
# Open the original wechat profile picture
img2 = Image.open("./img/Avatar/old/3.jpeg")
img2 = img2.convert('RGBA')
Copy the code

To read the image, we directly use the open function of the image object in PIL, just passing in the image path.

Then we also call the convert function color the picture format to the RGBA, the benefits of such a unified image color is format, convenient later merged images, another is RGBA is the true color of transparent channel model, we can set the mask at the time of merger, the merger transparent part will not be copy and paste onto the original image,. Other modes include:

  • RGB: 24-bit color image
  • 1:1 bit pixel, black and white, stored as 8 bits per pixel
  • L: 8-bit pixels, grey

2) Adjust the size of the two images to be the same (700*700)

size = (700.700)
ifimg1.size ! = size:Size = 700*700
    # Resize the image
    img1.thumbnail(size)
    
ifimg2.size ! = size:Size = 700*700
    # Resize the image
    img2.thumbnail(size)
Copy the code

Here we call the size property in the Image to get the size of the Image, length * width (pixels), and judge and modify the size uniformly. Here we use the thumbnail function to scale the Image, which will scale the Image in the same proportion as length and width according to the size we set. The Image content will not be deformed.

Of course, we can also use the resize function to reset the size, but may cause the image content distortion.

3) Paste the template picture on the wechat profile picture

# Image paste selection
loc = (0.0.700.700)
Paste img1 into img2
img2.paste(img1, loc, img1)
Copy the code

The operation here is to paste the template Image directly onto the original wechat profile picture. Here, we use the paste function in Image, which has three parameters: the first is the Image to be pasted, and the second is the position to paste. You can set the coordinate of the upper left pixel (X,y), and also set the paste area (A, B, C, D).

There is also an optional parameter mask to set the mask. After setting the mask, the image paste will be pasted according to the designated area of the mask. In RGBA mode, the alpha (transparent channel) band is used as the mask, so that the transparent part of the template will not be pasted over when pasting the template to the original wechat profile picture.

4) Save the processed files

img2.show()   # display images
img2.save("./img//Avatar/new/3.png")   # Save the generated profile picture
Copy the code

To save the Image, we use the save function of Image to directly specify the saving path. In addition, we also call the show function to explicitly show the processed Image.

Through the above four steps, we completed the generation of wechat profile picture of The National Day.

After the first optimization, the program console outputs the menu, and the user chooses which wechat avatar to deal with, which template to choose, and directly enters the code.

For the first version, manually input the original wechat profile picture directory and fix the name of print template
from PIL import Image
import os

"" demand: add Chinese national flag to the lower right corner of the picture to welcome National Day and express love for the motherland. """

# define an image manipulation class
class Picture:
    
    "Print menu"
    def print_menu_national_day_picture(self) :
        # 1 print the menu
        print('****** Welcome to the National Day wechat avatar generation program ******')
        Enter the original wechat profile picture address first
        old_img_path = input('****** please enter your wechat profile picture path: ')
        while not os.path.isfile(old_img_path):
            print('The image path you entered does not exist, please re-enter')
            old_img_path = input('****** please enter your wechat profile picture path: ')
        while True:
            Here we fix a few templates
            print('****** please select the image template, the current template design type is ******')
            print(***1. National Flag)
            print(***2. Transparent Flag)
            print(***3, the motherland happy birthday ')
            print('***4, Celebrate National Day ')
            print('***5, here's a red flag ')
            print(6. Tian 'anmen square)
            print(7. Flag of Tian 'anmen square)
            print('****** You can also enter: 0 to exit the program directly ******')
            img_template_st = input('please enter your choice :(enter numeric number)')
            # 2. Judge the input
            if img_template_str == '1':
                return old_img_path, './img/1.png'
            elif img_template_str == '2':
                return old_img_path, './img/2.png'
            elif img_template_str == '3':
                return old_img_path, './img/3.png'
            elif img_template_str == '4':
                return old_img_path, './img/4.png'
            elif img_template_str == '5':
                return old_img_path, './img/5.png'
            elif img_template_str == '6':
                return old_img_path, './img/6.png'
            elif img_template_str == '7':
                return old_img_path, './img/7.png'
            elif img_template_str == '0':  # exit, return "" empty string
                print('****** You have logged out of the National Day photo processing program ******')
                return ' '.' '
            else:
                print('No avatar template you entered: %s'% img_template_str)
        
         
    
    Processing merged images
    def handle_national_day_picture(self) :
        # Obtain the original wechat profile picture path and template path
        old_img_path, img_template_path = self.print_menu_national_day_picture()
        
        if img_template_path == ' ':  # indicates that the user has chosen to exit program 0
            return ' '    # direct return terminates the program
        
        Otherwise start processing
        Open image template
        img1 = Image.open(img_template_path)
        img1 = img1.convert('RGBA')
        ifimg1.size ! = (700.700) :Size = 700*700
            # Resize the image
            size = (700.700)
            img1.thumbnail(size)
            
        # Open the original wechat profile picture
        img2 = Image.open(old_img_path)
        img2 = img2.convert('RGBA')
        print('img2', img2.size)
        ifimg2.size ! = (700.700) :Size = 700*700
            # Resize the image
            size = (700.700)
            img2.thumbnail(size)
        
        # Image paste selection
        loc = (0.0.700.700)
        Paste img1 into img2
        img2.paste(img1, loc, img1)
        img2.show()   # display images
        old_name = os.path.basename(old_img_path).split('. ') [0] 
        template_name = os.path.basename(img_template_path).split('. ') [0]
        new_pic_path = "./img/Avatar/new/{0}_{1}.png".format(old_name, template_name)
        img2.save(new_pic_path)  # Save the generated profile picture
        print('****** New avatar file directory: %s******'%new_pic_path )
        print('****** Congratulations on your successful creation of your own National Day wechat profile photo ******')
        return 'success'
Copy the code

The second version, automatically read file directory, print picture and template directory, select the serial number

from PIL import Image
import os

"" demand: add Chinese national flag to the lower right corner of the picture to welcome National Day and express love for the motherland. """

# define an image manipulation class
class Picture:
    
    # template name
    template_dicts = {
        'flag':'1'.'Transparent Flag':'2'.'Happy birthday to the motherland':'3'.'Celebrate National Day':'4'.'Here's a red flag.':'5'.'Tian 'an Gate':'6'.'Flag of Tian 'anmen':'7'
        # More templates can be added yourself
        PNG format template name: serial number, file name: serial number
    }
    # File directory path
    template_root_path = './img/'
    wx_avatar_old_path = './img/Avatar/old/'
    wx_avatar_new_path = './img/Avatar/new/'
    # Image file suffix, if there are other formats can be added
    image_suffixes = {'png'.'jpg'.'jpeg'.'gif'.'JPG'.'PNG'.'GPEG'.'GIF'}
    "Print menu"
    def print_menu_national_day_picture(self) :
        1. Print menu
        print('****** Welcome to the National Day wechat avatar generation program ******')
        
        2. Print the original wechat avatar + select ""
        print('****** Please select the name of wechat profile picture you want to process ******')
        # 1) Obtain all picture files under the original profile picture directory of wechat and print out the file names
        index = 1
        temp_dict = {}
        for i in os.listdir(self.wx_avatar_old_path):
            file_suffix = i.split('. ') [1]
            if file_suffix in self.image_suffixes:  # Filter non-image files
                print('* * * * * * {0}, {1}'.format(index, i))
                temp_dict = {str(index): i}
                index+=1
        print('****** You can also enter: 0 to exit the program directly ******')
        
        # 2) The user selects the image
        old_img_index = input('****** Please enter the number of wechat avatar you want to process (enter the number) : ')
        # Exit the program
        if old_img_index == '0':
            print('****** You have logged out of the National Day photo processing program ******')
            return ' '.' '
        # Whether the file exists
        while old_img_index not in temp_dict:
            print('The serial number you entered does not exist, please re-enter')
            old_img_index = input('****** Please enter the number of wechat avatar you want to process (enter the number) : ')
        old_img_path = self.wx_avatar_old_path + temp_dict[old_img_index]
        
        3. Template print + Select ""
        while True:
            # 1) Print an existing template
            print('****** please select the image template, the current template design type is ******')
            The traversal dictionary automatically prints the template name
            for k,v in self.template_dicts.items():
                print('* * * * * * {1}, {0}'.format(k, v))
            
            # 2) The user selects the template
            img_template_str = input('please enter the template you want to use :(enter the number)')
            Check whether the user input is valid
            while img_template_str not in self.template_dicts.values():
                print('The serial number you entered does not exist, please re-enter')
                img_template_str = input('****** please enter the template you want to use :(enter the number)')
                
            # 3) Return to the original image path and template path based on user input
            if img_template_str in self.template_dicts.values():
                return old_img_path, self.template_root_path + img_template_str + '.png'
            else:
                print('No avatar template number you entered: %s'% img_template_str)
        
    
    Processing merged images
    def handle_national_day_picture(self) :
        # 1) Obtain the original wechat profile picture path and template path
        old_img_path, img_template_path = self.print_menu_national_day_picture()
        
        if img_template_path == ' ':  # indicates that the user has chosen to exit program 0
            return ' '    # direct return terminates the program
        
        
        # 2) Start processing
        Open image template
        img1 = Image.open(img_template_path)
        img1 = img1.convert('RGBA')
        size = (700.700)  Size = 700*700
        ifimg1.size ! = size:# Resize the image
            img1.thumbnail(size)
            
        # Open the original wechat profile picture
        img2 = Image.open(old_img_path)
        img2 = img2.convert('RGBA')
        ifimg2.size ! = size:# Resize the image
            img2.thumbnail(size)
        
        # 3) Image paste selection
        loc = (0.0.700.700)
        Paste img1 into img2
        img2.paste(img1, loc, img1)
        img2.show()   # display images
        old_name = os.path.basename(old_img_path).split('. ') [0] 
        Take the name of the avatar and the name of the template and put them together as the name of the new avatar
        template_name = os.path.basename(img_template_path).split('. ') [0]
        new_pic_path = self.wx_avatar_new_path + "{0}_{1}.png".format(old_name, template_name)
        img2.save(new_pic_path)  # Save the generated profile picture
        print('****** New avatar file directory: %s******'%new_pic_path )
        print('****** Congratulations on your successful creation of your own National Day wechat profile photo ******')
        print(' ')
        print('****** you can choose to continue with other avatars, or type 0 to exit the program ')
        print(' ')
        print(' ')
        return 'success'
Copy the code

Instantiate an object, and then call the function

t0 = Picture()

while True:
    # start program
    sucess = t0.handle_national_day_picture()
    # ./img/Avatar/old/3.jpeg
    if sucess == ' ':
        print('****** Thank you for using the National Day wechat profile picture production process has been completed ******')
        break
Copy the code

Generate renderings

Material file acquisition method: directly on the network to find, and then processing can be, or add my wechat pythonbrief, remarks: digging gold, can be obtained.

Fixation of trailer

Write a GUI interface to qingguo Micro channel avatar processing program.

The effect picture is as follows: