Python 批量给某个目录的图片加水印

#pip install pillow

#| 参数名              | 说明                   |
#| ---------------- | -------------------- |
#| `image_dir`      | 原图所在文件夹(支持 PNG、JPG)  |
#| `watermark_file` | PNG 格式水印图片(建议带透明背景)  |
#| `output_dir`     | 输出文件夹                |
#| `position`       | 支持预设字符串或 `(x, y)` 坐标 |
#| `rotation`       | 顺时针旋转角度              |
#| `opacity`        | 0 \~ 1 之间,水印图透明度     |


import os
from PIL import Image, ImageEnhance

def add_watermark_to_images(
    image_dir="images",
    watermark_file="watermark.png",
    output_dir="output_watermarked",
    position="bottom-right",  # 可选: 'top-left', 'top-right', 'center', 'bottom-left', 'bottom-right', 或 (x, y)
    rotation=0,               # 旋转角度(顺时针)
    opacity=0.3               # 水印透明度(0 ~ 1)
):
    os.makedirs(output_dir, exist_ok=True)

    # 加载水印图
    watermark = Image.open(watermark_file).convert("RGBA")

    # 设置透明度
    if opacity < 1.0:
        alpha = watermark.split()[3]
        alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
        watermark.putalpha(alpha)

    # 旋转
    if rotation != 0:
        watermark = watermark.rotate(rotation, expand=True)

    for filename in os.listdir(image_dir):
        if not filename.lower().endswith((".jpg", ".jpeg", ".png")):
            continue

        img_path = os.path.join(image_dir, filename)
        img = Image.open(img_path).convert("RGBA")

        # 创建同尺寸空图合成图层
        layer = Image.new("RGBA", img.size, (0, 0, 0, 0))
        wm_width, wm_height = watermark.size
        img_width, img_height = img.size

        # 计算位置
        if isinstance(position, tuple):
            pos = position
        else:
            if position == "top-left":
                pos = (0, 0)
            elif position == "top-right":
                pos = (img_width - wm_width, 0)
            elif position == "center":
                pos = ((img_width - wm_width) // 2, (img_height - wm_height) // 2)
            elif position == "bottom-left":
                pos = (0, img_height - wm_height)
            else:  # bottom-right
                pos = (img_width - wm_width, img_height - wm_height)

        # 合成图层
        layer.paste(watermark, pos, watermark)
        watermarked = Image.alpha_composite(img, layer)

        # 输出为 JPG 或 PNG,保持格式一致
        output_path = os.path.join(output_dir, filename)
        if filename.lower().endswith(".jpg") or filename.lower().endswith(".jpeg"):
            watermarked.convert("RGB").save(output_path, "JPEG")
        else:
            watermarked.save(output_path, "PNG")

        print(f"✅ 已处理:{filename}")

    print("🎉 所有图片水印处理完成!")

# 示例调用
if __name__ == "__main__":
    add_watermark_to_images(
        image_dir="images",
        watermark_file="watermark.png",
        output_dir="output_watermarked",
        position="top-left",  # 可自定义如 (50, 50)
        rotation=30,
        opacity=0.5
    )

  

posted @ 2025-07-16 10:56  Iamluckyman  阅读(20)  评论(0)    收藏  举报