In actual work, you may encounter adding watermarks to pictures in batches. These watermarks may be different for each picture, but the format must be unified, and the font, spacing, position, etc. must be coordinated. How to achieve it?
The following are the specific steps implemented in python:
Data situation:
A picture with a unified standard name, an excel, the structure is that the first column is the corresponding serial number, and the second column is the watermark that needs to be added.
1 | Longitude: 109.321305 Latitude: 31.343865 Address: Wuhan Time: 2023-04-05 08:34:07 |
2 | Longitude: 109.319677 Latitude: 31.345636 Address: Wuhan Time: 2023-04-05 08:48:31 |
3 | Longitude: 109.319677 Latitude: 31.345636 Address: Wuhan Time: 2023-04-09 09:10:43 |
code content
1. Import the necessary packages
from PIL import Image, ImageDraw, ImageFont
import openpyxl
2. Import data
# 打开Excel文件并读取数据
workbook = openpyxl.load_workbook('time.xlsx')
worksheet = workbook.active
data = [(row[0], row[1]) for row in worksheet.iter_rows(values_only=True)]
3. Cycle through each picture
# 循环处理每张图片
for i in range(1, 4):
# 打开图片文件
image = Image.open(f'{i}.jpg')
# 创建用于在图片上绘制文字的对象
draw = ImageDraw.Draw(image)
# 设置字体和水印文字
font = ImageFont.truetype('阿里巴巴普惠体R.ttf', size=20)
# 计算文字高度和行间距
text_height = font.getsize('A')[1]
line_spacing = int(text_height * 1.5)
# 循环处理每个需要添加水印的文本
for j, text in data:
if i == int(j):
# 计算绘制文字所需的位置
x =35
y = image.size[1] - (text_height + line_spacing)*2
# 在图片上绘制文字
draw.text((x, y), text, font=font, fill=(255, 255, 255, 128))
# 保存修改后的图片文件
image.save(f'watermarked_image{i}.jpg')
Effect example:
before adding
After adding:
illustrate:
You can adjust the placement position, font type, font size, spacing, etc. as needed.