吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 982|回复: 13
上一主题 下一主题
收起左侧

[Python 原创] Python使用Pillow模块实现图片批量添加水印

  [复制链接]
跳转到指定楼层
楼主
MowChan 发表于 2025-11-4 21:47 回帖奖励

功能说明

使用 Pillow 库为指定文件夹内的 PNG 图片批量添加水印。水印图片的路径为 watermark_path,将水印图片叠加到原图左上角位置,处理后的图片会保存在原图同文件夹下,文件名在原文件名基础上添加 -watermark 后缀。

运行环境

  • Windows 系统
  • Python 3.x
  • Pillow 图像处理库

源代码

from os import path
from os import walk as walk
from PIL import Image

image_paths, input_paths = [], []
watermark_path = r'D:\experiment\watermark.png'

def add_watermark(image_path, watermark_path, output_path):
    image = Image.open(image_path)
    watermark = Image.open(watermark_path)
    mask = watermark.copy()
    output = image.copy()
    output.paste(watermark, (0, 0), mask)
    output.save(output_path)

for _, _, files in walk('image'):
    for file in files:
        if path.splitext(file)[-1] in ('.png', '.PNG'):
            image_paths.append( ( path.join('image', file), *path.splitext(file) ) )

for image in image_paths:
    input_paths.append( ( image[0], 'image\\{}-watermark{}'.format(image[1], image[2]) ) )

for image, output in input_paths:
    add_watermark(image, watermark_path, output)
    print('{} Completed!'.format(image))

免费评分

参与人数 4吾爱币 +8 热心值 +3 收起 理由
qsj521521 + 1 + 1 谢谢@Thanks!
hwh425 + 1 热心回复!
xiaosanmeng + 1 + 1 我很赞同!
hrh123 + 5 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

推荐
lsb2pojie 发表于 2025-11-5 08:19
可以可以,不过我比较想去除水印
沙发
gprboy 发表于 2025-11-4 21:50
值得学习,代码不错,我先保存了,谢谢楼主。
3#
飘缈孤鸿影 发表于 2025-11-4 22:07
4#
sunson1097 发表于 2025-11-4 22:39
这代码后面要升级哦,原图只能是PNG
5#
aaa74124 发表于 2025-11-4 23:03
很好用,很方便,再也不用一个个的添加水印了
6#
 楼主| MowChan 发表于 2025-11-5 08:10 |楼主
sunson1097 发表于 2025-11-4 22:39
这代码后面要升级哦,原图只能是PNG

pillow支持主流的图片格式,L18的扩展名筛选一行代码改一下就都能用了
8#
anning666 发表于 2025-11-5 08:33
好简洁的代码,简单粗暴解决问题~~~666
9#
sunflash 发表于 2025-11-5 09:33
感谢分享,比PS简单
10#
Living312 发表于 2025-11-5 11:50
感谢楼主分享,便于ptyhon的学习
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-11-15 15:43

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表