python 在图片上覆盖图文
准备工作
下载安装:
- pillow
- imageio
安装pillow
pip install Pillow -i https://pypi.tuna.tsinghua.edu.cn/simple
安装imageio
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn imageio
代码测试
顺便多张图制作成动图
import imageio
import os
from PIL import Image, ImageDraw, ImageFont
#图片文件夹
dir = r'C:\Users\Administrator.DEEP-2020SHAOPP\Desktop\图片'
name = '图片名'
addP = r'C:\Users\Administrator.DEEP-2020SHAOPP\Desktop\addP.png'
#加载需要P上去的图片
tmp_img = Image.open(addP).convert('RGB') #要粘贴的图可选择大小或整张
def create_gif(image_list, gif_name, duration=0.05):
frames = []
for image_name in image_list:
frames.append(imageio.imread(dir+'/'+image_name))
imageio.mimsave(gif_name, frames, 'GIF', duration=duration)
def pic_text(filepath,text,setFont,fillColor,filename,direction=None):
print(filepath,text)
#打开图片
image = Image.open(filepath)
#图片宽高
s = image.size
size = (100,s[1] - 55)
#底图上需要P掉的区域
box = (0, s[1] - 80, 80, s[1])
region = tmp_img #使用整张
region = region.resize((box[2] - box[0], box[3] - box[1]))
image.paste(region, box)
#新建绘图对象
draw = ImageDraw.Draw(image)
draw.text(size,text,font=setFont,fill=fillColor,direction=None)
#保存
image.save(filename,disposal=3)
if __name__=="__main__":
#选择文字字体和大小(选择自己windows路径下的字体)
setFont = ImageFont.truetype('C:/windows/Fonts/simhei.ttf', 30)
#设置文字颜色
fillColor = "#000000"
image_list = os.listdir(dir+'/')
print('name',name)
for index,image_name in enumerate(image_list):
filepath = dir+'/'+image_name
filename = dir+'/'+image_name
text = name + ' 第' + str(index) + '张'
#添加文字
pic_text(filepath,text,setFont,fillColor,filename,direction=None)
duration = 1 # 1/20 每秒帧20
image_list = os.listdir(dir+'/')
gif_name = dir+'/'+name+'.gif'
print('gif_name',gif_name)
create_gif(image_list, gif_name, duration)