本文通过Python实现简单的证件照制作
import os,time
from PIL import Image
import requests
def removebg():
response = requests.post(
'https://api.remove.bg/v1.0/removebg',
files={'image_file': open('需要处理的照片路径', 'rb')},
data={'size': 'auto'},
headers={'X-Api-Key': 'xxxxxxxxxxxx'})
if response.status_code == requests.codes.ok:
with open('no-bg.png', 'wb') as out:
out.write(response.content)
else:
print("Error:", response.status_code, response.text)
将处理好的no-bg.png保存到本地
def changebg(nbgurl,outimg):
'''经过removebg处理的图片 输出的图片'''
newBgImg=removebg(nbgurl)
lastimage=Image.open(newBgImg)
#rgb即为需要处理成什么颜色的底
newimage=Image.new('RGBA',(lastimage.size),rgb)
newimage.paste(lastimage,(0,0),lastimage)
newimage.save(outimg)
def merged(mergedurl):
num=0
#算好每个图片的间隔
toImage = Image.new('RGB', (pic_width,pic_height),(255,255,255))
for k in range(0,1000,500):
for n in range(0,1440,360):
first=(x+n,y+k)
lists.append(first)
for i in range(8):
#需要处理的照片
pic_fole_head = Image.open(mergedurl)
width, height = pic_fole_head.size
tmppic = pic_fole_head.resize((width_i, height_i))
toImage.paste(tmppic, lists[num])
num = num + 1
toImage.save('merged.jpg')
import os,time
from PIL import Image
import requests
def removebg(url):
response = requests.post(
'https://api.remove.bg/v1.0/removebg',
files={'image_file': open(url, 'rb')},
data={'size': 'auto'},
headers={'X-Api-Key': 'xxxxxx'})
if response.status_code == requests.codes.ok:
with open('no-bg.png', 'wb') as out:
out.write(response.content)
print('[INFO] {} 图片背景去除完成'.format(time.ctime()))
return 'no-bg.png'
else:
print("Error:", response.status_code, response.text)
def changebg(nbgurl,outimg):
'''经过removebg处理的图片 输出的图片'''
newBgImg=removebg(nbgurl)
lastimage=Image.open(newBgImg)
newimage=Image.new('RGBA',(lastimage.size),rgb)
newimage.paste(lastimage,(0,0),lastimage)
newimage.save(outimg)
print('[INFO] {} 背景改色完成'.format(time.ctime()))
def merged(mergedurl):
num=0
toImage = Image.new('RGB', (pic_width,pic_height),(255,255,255))
for k in range(0,1000,500):
for n in range(0,1440,360):
#获取每个照片的坐标 为元组
first=(x+n,y+k)
lists.append(first)
for i in range(8):
pic_fole_head = Image.open(mergedurl)
width, height = pic_fole_head.size
tmppic = pic_fole_head.resize((width_i, height_i))
toImage.paste(tmppic, lists[num])
num = num + 1
toImage.save('merged.jpg')
print('[INFO] {} 排版完成'.format(time.ctime()))
if __name__ == "__main__":
import json
with open('./conf.json','r') as r:
conf=json.load(r)
width_i = conf['width_i']
height_i = conf['height_i']
#生成5寸底板
pic_width=conf['pic_width']
pic_height=conf['pic_height']
#照片间隙
x=conf['x']
y=conf['y']
#所有坐标
lists=[]
#图片背景颜色
rgb=tuple(conf['rgb'])
changebg('timg.jpg','./newbg.png')
merged('./newbg.png')
这里将参数写到了json文件中,方便修改使用
JSON:
{
"width_i":295,//一寸照片的默认大小
"height_i":413,
"pic_width":1500,
"pic_height":1051,
"x":65,
"y":40,
"rgb":[255,0,0]//这是背景颜色 其余颜色见RGB调色盘
}