import datetime
import os
import random
from PIL import Image, ImageDraw, ImageFont
import sys
sys.stdout.reconfigure(encoding='utf-8')
def get_font_path():
if os.name == 'nt': # Windows
font_path = os.path.join("C:\\Windows\\Fonts\\simfang.ttf")
else: # Linux or macOS
font_path = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
return font_path
def generate_diploma(my_name, my_card, my_job, my_photo):
# >>>>>>>参数>>>>>>>>>>>
# 证书模版地址
BASE_DIRS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
image_path = os.path.join(BASE_DIRS, 'static', 'base', 'diploma.png')
# 证书日期
current_datetime = datetime.datetime.now()
current_datetime = current_datetime.strftime('%Y年%m月%d日')
# 证书编号
current_number = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(10000, 99999))
# 证书文本
text_list = [
(current_number, (378, 42)),
(my_name, (320, 226)),
(my_card, (320, 282)),
(my_job, (320, 340)),
(current_datetime, (343, 670))
]
# 证书字体大小
font_size = 16
# 证书字体颜色
text_color = (0, 0, 0) # 设置文本颜色为黑色
# 证书个人照片
overlay_image_path = fr'{my_photo}' # 要添加的另一张图片的路径
# 证书个人照片大小
overlay_image_size = (100, 130) # 设置插入图片的大小为 (宽度, 高度)
# 证书照片位置
overlay_position = (88, 230) # 设置另一张图片的位置
# >>>>>>>执行>>>>>>>>>>>>
image = Image.open(image_path)
draw = ImageDraw.Draw(image)
font_path = get_font_path()
font = ImageFont.truetype(font_path, font_size)
for text, position in text_list:
# 将文本添加到图片上
draw.text(position, text, fill=text_color, font=font)
# 打开要添加的另一张图片
overlay_image = Image.open(overlay_image_path)
# 调整另一张图片的大小
overlay_image = overlay_image.resize(overlay_image_size)
# 在原图上粘贴另一张图片
image.paste(overlay_image, overlay_position)
# 生成图片
BASE_DIRS2 = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
path_url = os.path.join(BASE_DIRS2, 'static', 'diploma')
if not os.path.exists(path_url):
# 判断目录是否存在,若不存在则递归创建目录
os.makedirs(path_url)
image_name = current_number + '_' + my_name + '.png'
file_path = os.path.join(path_url, image_name)
image.save(file_path)
# image.show()
return file_path
# if __name__ == "__main__":
# my_name = '马可波罗'
# my_card = '156852348562312568'
# my_job = 'ADC'
# photo = 'E:\\odoo\\odoo_Pro\\online-training-system\\static\\file\\20230801153150717937_马可波罗.jpeg'
# my_photo = fr'{photo}'
# print('>>>>>>>', my_photo)
# generate_diploma(my_name, my_card, my_job, my_photo)
Python在图片中添加文字
于 2023-08-16 10:23:07 首次发布