安装模块
pip install pillow
pip install removebg
引入模块
from PIL import Image
from removebg import RemoveBg
去removebg官网申请key 免费用户一个月可以提交50次 https://www.remove.bg/
api_key = '从官网申请的key'
定义函数
def change_bgcolor(file_in, file_out, api_key, color):
'''
#必须为png格式
'''
p, s = file_in.split(".")
rmbg = RemoveBg(api_key, 'error.log')
rmbg.remove_background_from_img_file(file_in)
file_no_bg = "{}.{}_no_bg.{}".format(p, s, s)
no_bg_image = Image.open(file_no_bg)
x, y = no_bg_image.size
new_image = Image.new('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)
# 修改照片尺寸
def change_size(file_in, file_out, width, height):
image = Image.open(file_in)
resized_image = image.resize((width, height), Image.ANTIALIAS)
resized_image.save(file_out)
执行
if __name__ == "__main__":
file_in = r"D:\Users\Administrator\Desktop\test\static\images\zj.png"
file_out = r"D:\Users\Administrator\Desktop\test\static\images\zj_new.png"
# 尺寸可按需求自修改
# change_size(file_in, file_out, width, height)
# 换背景色
color = (0, 125, 255)
change_bgcolor(file_in, file_out, api_key, color)
需要注意的事 传入的文件后缀名得是png格式 因为remove_bg保存的抠图是png结尾 否则会导致找不到报错
之后可以通过创建新图 然后图片合并的方式创建证件照
可以参考这个网站 做一个样本过来 https://www.shiliuai.com/id_photo/?bd_vid=8016889657805523182