Python给图片批量添加水印

from PIL import Image, ImageDraw, ImageFont
import os

# 水印文本和字体设置
watermark_text = "水印字体"
font = ImageFont.truetype("C:/Windows/Fonts/simhei.ttf", 24)  # 选择一个字体文件和字体大小
rotation_angle = 45  # 倾斜角度
opacity = 60  # 0-255,0 表示完全透明,255 表示完全不透明
horizontal_spacing = 10  # 水印之间的水平间距
vertical_spacing = 30   # 水印之间的垂直间距

# 输入和输出文件夹
input_folder = "C:/Users/Lenovo/Desktop/1"
output_folder = "C:/Users/Lenovo/Desktop/2"
os.makedirs(output_folder, exist_ok=True)

# 列出输入文件夹中的所有图片文件
image_files = [f for f in os.listdir(input_folder) if f.endswith((".jpg", ".png", ".jpeg"))]
print(image_files)
for image_file in image_files:
    # 打开图片
    img = Image.open(os.path.join(input_folder, image_file))
    draw = ImageDraw.Draw(img)

    # 获取图片宽度和高度
    width, height = img.size

    # 创建字体
    font = ImageFont.truetype("C:/Windows/Fonts/simhei.ttf", 26)
    # 计算水印文本的宽度和高度
    text_width, text_height = draw.textsize(watermark_text, font)

    # 计算透明度
    transparency = opacity

    # 旋转水印
    watermark = Image.new('RGBA', (text_width, text_height), (0, 0, 0, 0))
    watermark_draw = ImageDraw.Draw(watermark)
    watermark_draw.text((0, 0), watermark_text, fill=(0, 0, 0, transparency), font=font)
    watermark = watermark.rotate(rotation_angle, expand=True)

    # 计算水印平铺的位置和间距
    x, y = 0, 0
    while y < height:
        while x < width:
            img.paste(watermark, (x, y), watermark)
            x += text_width + horizontal_spacing + vertical_spacing

        x = 0
        y += text_height + horizontal_spacing + vertical_spacing

        # 保存带有水印的图片
    img.save(os.path.join(output_folder, image_file))

print("水印添加完成。")

你可能感兴趣的:(python,python,图像处理)