下面是一个示例代码,它假设你已经安装了Pillow库来处理图像。在运行代码之前,确保将模板图片和目标图片保存在同一个文件夹中,并替换文件名和目标文本,以在图像上居中显示:
```python
from PIL import Image, ImageDraw, ImageFont
# 打开模板图片和目标图片
template = Image.open("template.png")
target = Image.open("target.png")
# 获取目标图片和模板图片的宽度和高度
target_width, target_height = target.size
template_width, template_height = template.size
# 在模板图片上居中添加文本
text = "Your text here"
font_size = 50
font = ImageFont.truetype("arial.ttf", font_size)
draw = ImageDraw.Draw(template)
text_width, text_height = draw.textsize(text, font=font)
text_x = (template_width - text_width) / 2
text_y = (template_height - text_height) / 2
draw.text((text_x, text_y), text, font=font, fill=(255, 255, 255))
# 将模板图片转换为半透明
alpha_level = 128
alpha = Image.new("L", template.size, alpha_level)
template.putalpha(alpha)
# 将模板图片居中合并到目标图片
target.paste(template, ((target_width - template_width) // 2, (target_height - template_height) // 2), template)
# 保存合并后的图片
target.save("merged.png")
```
请注意,此代码仅在使用指定的Arial字体和默认字体大小和颜色的情况下测试过,因此可能需要根据自己的情况进行调整。
发表评论 取消回复