查看: 268|回复: 0

Python Pillow批量图片水印脚本实现文字Logo与平铺

[复制链接]
发表于 1 小时前 | 显示全部楼层 |阅读模式
批量处理图片水印是开发中常见的自动化需求,尤其当图片数量达到数千张时,手动操作几乎不可行。Python 的 Pillow 库提供了完整的图像处理接口,可以基于透明图层叠加的方式,快速实现文字水印、Logo 水印以及全屏平铺水印。本文从实际代码出发,给出三个可复用的水印函数,并提供一个通用的批量处理入口,适合直接嵌入到自动化流程中。
  1. # 基础环境
  2. pip install Pillow
复制代码

核心思路是:打开原图并转换为 RGBA 模式,创建一张同尺寸的透明图层,在透明图层上绘制文字或粘贴 Logo,再通过 Image.alpha_composite 将图层与原图合成,最后按需转换为 RGB 保存。全程不修改原文件,输出到指定目录。

文字水印实现
文字水印通过 ImageDraw.text 绘制,支持自定义内容、位置、字号、颜色透明度以及旋转角度。字体默认读取 Windows 下的微软雅黑 msyh.ttc,如果不存在则回退到默认字体。注意,若要在 Linux 或 macOS 上运行,需要将字体路径替换为系统中实际存在的中文字体文件,否则中文会显示为方框。
  1. from PIL import Image, ImageDraw, ImageFont
  2. import os
  3. from pathlib import Path
  4. def add_text_watermark(input_image, output_image, text="内部资料",
  5.                        position="center", font_size=40, color=(255, 255, 255, 128),
  6.                        angle=0):
  7.     img = Image.open(input_image).convert('RGBA')
  8.     txt_layer = Image.new('RGBA', img.size, (255, 255, 255, 0))
  9.     draw = ImageDraw.Draw(txt_layer)
  10.     try:
  11.         font = ImageFont.truetype("C:/Windows/Fonts/msyh.ttc", font_size)
  12.     except:
  13.         font = ImageFont.load_default()
  14.     bbox = draw.textbbox((0, 0), text, font=font)
  15.     text_width = bbox[2] - bbox[0]
  16.     text_height = bbox[3] - bbox[1]
  17.     positions = {
  18.         'center': ((img.width - text_width) // 2, (img.height - text_height) // 2),
  19.         'bottom-right': (img.width - text_width - 20, img.height - text_height - 20),
  20.         'bottom-left': (20, img.height - text_height - 20),
  21.         'top-right': (img.width - text_width - 20, 20),
  22.         'top-left': (20, 20),
  23.     }
  24.     x, y = positions.get(position, positions['center'])
  25.     if angle != 0:
  26.         big_layer = Image.new('RGBA', (img.width * 2, img.height * 2), (255, 255, 255, 0))
  27.         big_draw = ImageDraw.Draw(big_layer)
  28.         big_draw.text((img.width // 2, img.height // 2), text, font=font, fill=color)
  29.         big_layer = big_layer.rotate(angle, expand=0)
  30.         txt_layer = big_layer.crop((img.width // 2, img.height // 2,
  31.                                     img.width // 2 + img.width,
  32.                                     img.height // 2 + img.height))
  33.     else:
  34.         draw.text((x, y), text, font=font, fill=color)
  35.     result = Image.alpha_composite(img, txt_layer)
  36.     result = result.convert('RGB')
  37.     result.save(output_image, quality=95)
  38.     print(f"文字水印: {os.path.basename(input_image)}")
复制代码

旋转处理的原理是先把文字画在一张比原图大四倍的透明画布中心,再旋转整张画布,最后裁剪出与原图等大的区域。这样可以避免旋转后文字超出边界。

Logo 图片水印实现
图片水印适合放公司 Logo,支持透明度调整和等比缩放。建议使用 PNG 透明背景,否则会带白色底块。缩放时根据原图宽度乘以 scale 计算宽度,高度按 Logo 原始宽高比计算,保证不变形。透明度控制通过修改 alpha 通道实现。
  1. def add_image_watermark(input_image, output_image, logo_path,
  2.                         position="bottom-right", opacity=0.5, scale=0.15):
  3.     img = Image.open(input_image).convert('RGBA')
  4.     logo = Image.open(logo_path).convert('RGBA')
  5.     new_logo_size = (int(img.width * scale),
  6.                      int(img.height * scale * logo.height / logo.width))
  7.     logo = logo.resize(new_logo_size, Image.LANCZOS)
  8.     if opacity < 1:
  9.         r, g, b, a = logo.split()
  10.         a = a.point(lambda x: int(x * opacity))
  11.         logo = Image.merge('RGBA', (r, g, b, a))
  12.     positions = {
  13.         'center': ((img.width - logo.width) // 2, (img.height - logo.height) // 2),
  14.         'bottom-right': (img.width - logo.width - 20, img.height - logo.height - 20),
  15.         'bottom-left': (20, img.height - logo.height - 20),
  16.         'top-right': (img.width - logo.width - 20, 20),
  17.         'top-left': (20, 20),
  18.     }
  19.     x, y = positions.get(position, positions['bottom-right'])
  20.     watermark_layer = Image.new('RGBA', img.size, (0, 0, 0, 0))
  21.     watermark_layer.paste(logo, (x, y))
  22.     result = Image.alpha_composite(img, watermark_layer)
  23.     result = result.convert('RGB')
  24.     result.save(output_image, quality=95)
  25.     print(f"Logo水印: {os.path.basename(input_image)}")
复制代码

平铺水印实现
对于防泄漏需求,可以将文字错落铺满全图。通过两个 while 循环按行列绘制,行号奇偶时偏移半个间距,形成类似砖墙的排列方式。适合对文档截图声明“机密文件”之类的场景。
  1. def add_tiled_watermark(input_image, output_image, text="内部资料",
  2.                          font_size=30, color=(255, 255, 255, 50), angle=-30, spacing=150):
  3.     img = Image.open(input_image).convert('RGBA')
  4.     txt_layer = Image.new('RGBA', img.size, (255, 255, 255, 0))
  5.     draw = ImageDraw.Draw(txt_layer)
  6.     try:
  7.         font = ImageFont.truetype("C:/Windows/Fonts/msyh.ttc", font_size)
  8.     except:
  9.         font = ImageFont.load_default()
  10.     bbox = draw.textbbox((0, 0), text, font=font)
  11.     text_width = bbox[2] - bbox[0]
  12.     text_height = bbox[3] - bbox[1]
  13.     y = 0
  14.     while y < img.height:
  15.         x = 0
  16.         row_offset = (y // spacing) % 2 * (spacing // 2)
  17.         while x < img.width:
  18.             draw.text((x + row_offset, y), text, font=font, fill=color)
  19.             x += text_width + spacing
  20.         y += text_height + spacing
  21.     result = Image.alpha_composite(img, txt_layer)
  22.     result = result.convert('RGB')
  23.     result.save(output_image, quality=95)
  24.     print(f"平铺水印: {os.path.basename(input_image)}")
复制代码

批量处理入口
三个函数都接收 input_image 和 output_image 路径,因此可以统一封装批量处理函数。只需要遍历输入目录下的图片文件,调用对应水印函数即可。支持 jpg、png、bmp、webp、tiff 等常见格式。
  1. def batch_add_watermark(input_dir, output_dir, watermark_func, **kwargs):
  2.     input_path = Path(input_dir)
  3.     output_path = Path(output_dir)
  4.     output_path.mkdir(parents=True, exist_ok=True)
  5.     image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.webp', '.tiff'}
  6.     count = 0
  7.     for file_path in input_path.iterdir():
  8.         if file_path.is_file() and file_path.suffix.lower() in image_extensions:
  9.             output_file = output_path / file_path.name
  10.             watermark_func(str(file_path), str(output_file), **kwargs)
  11.             count += 1
  12.     print(f"\n批量水印完成: {count} 张图片")
复制代码

使用示例
批量给员工工牌照片添加“仅限内部使用”文字水印:
  1. if __name__ == "__main__":
  2.     batch_add_watermark(
  3.         input_dir="原始工牌照片",
  4.         output_dir="已加水印",
  5.         watermark_func=add_text_watermark,
  6.         text="仅限内部使用",
  7.         position="center",
  8.         font_size=40,
  9.     )
复制代码

批量给产品图片添加 Logo:
  1. # batch_add_watermark(
  2.     #     input_dir="产品图片",
  3.     #     output_dir="已加Logo",
  4.     #     watermark_func=add_image_watermark,
  5.     #     logo_path="company_logo.png",
  6.     #     position="bottom-right",
  7.     #     opacity=0.7,
  8.     #     scale=0.1
  9.     # )
复制代码

对机密文档截图做全屏平铺水印:
  1. # batch_add_watermark(
  2.     #     input_dir="机密文档截图",
  3.     #     output_dir="平铺水印",
  4.     #     watermark_func=add_tiled_watermark,
  5.     #     text="机密文件",
  6.     #     font_size=25,
  7.     #     angle=-30,
  8.     # )
复制代码

常见问题与排查
中文水印显示为方框,原因是代码找不到中文字体。解决方法是显式指定系统中文字体路径,比如微软雅黑 msyh.ttc 或宋体 simsun.ttc。

水印太显眼时,调节 color 元组的第四个参数 alpha 值,例如 (255, 255, 255, 50) 表示透明度较高。

保存 PNG 后水印丢失,这是因为合成的结果是 RGBA 模式,如果直接保存为 PNG 通常正常;但如果想保留透明通道,应使用 result.save(output_image, 'PNG'),不要转换为 RGB。

整体来看,Pillow 的水印方案足够应对大多数批量场景。通过替换字体路径和调整透明度、位置、缩放比例,可以灵活适配不同业务需求。对于需要更高性能的场景,可以考虑 multiprocessing 并行处理多个文件,但要注意 Pillow 线程安全性,推荐使用进程池。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

指导单位

江苏省公安厅

江苏省通信管理局

浙江省台州刑侦支队

DEFCON GROUP 86025

Hacking Group 021A

旗下站点

态势感知中心

应急响应中心

红盟安全

联系我们

官方QQ群:112851260

官方邮箱:security#ihonker.org(#改成@)

官方核心成员

关注微信公众号

Archiver|手机版|小黑屋| ( 沪ICP备2021026908号 )

GMT+8, 2026-8-28 15:36 , Processed in 0.021380 second(s), 18 queries , Gzip On, Redis On.

Powered by ihonker.com

Copyright © 2015-现在.

  • 返回顶部