SoFunction
Updated on 2024-11-17

Less than 20 lines of implementation of Python code to create a beautiful ID card photo

Whether we go to school or after the work, basically need to use the electronic photo ID, such photos are basically on the photo size, background color requirements, in this article we look at how to use less than 20 lines of Python code to complete the production of the photo ID.

synopsis

Making ID photos we have two main jobs: modify the photo background and modify the size of the photo, modify the background we need to use third-party librariesremovebgTo change the size of the photo, you need to use thePIL libraries, which are installed using thepip install removebg cap (a poem)pip install Pillow Ready to go.

utilizationremovebg We also need an API key, which can be obtained as follows: first, we open the link address/users/sign_up Register an account and open it as shown below:


We fill in the mailbox and password and then check the agreement to submit, after the site will give us just fill in the mailbox to send a verification message, we into their mailboxes click on the verification link to complete the verification of the completion of the account after the registration work.

Once the account is registered, we then open the/zh/profile#api-key The address is logged into your account to get to the location pictured below:


We click on the Show button in the image above to get the secret key.

code implementation

The code implementation is also relatively simple, or the idea we talked about before: use theremovebg The library modifies the background color of the photo using thePIL The library modifies the size of the photo, which is implemented as shown below:

from PIL import Image
from removebg import RemoveBg

# Modify photo background color
def change_bgcolor(file_in, file_out, api_key, color):
  rmbg = RemoveBg(api_key, '')
  rmbg.remove_background_from_img_file(file_in)
  no_bg_image = (file_in)
  x, y = no_bg_image.size
  new_image = ('RGBA', no_bg_image.size, color=color)
  new_image.paste(no_bg_image, (0, 0, x, y), no_bg_image)
  new_image.save(file_out)

# Modify photo size
def change_size(file_in, file_out, width, height):
  image = (file_in)
  resized_image = ((width, height), )
  resized_image.save(file_out)

We can see that the entire implementation took less than 20 lines of code.

Effective demonstration

Finally, let's take a look at the implementation:


to this article on the realization of this less than 20 lines of Python code to create a beautiful photo ID article is introduced to this, more related Python photo ID content, please search for my previous posts or continue to browse the following related articles I hope that you will support me in the future more!