#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
)