TL;DR运营做图、设计师导出、产品经理处理截图——每次都要一张张调尺寸、压大小、加水印。写了一个 Python 脚本调用视觉大模型做智能裁剪批量处理 100 张图只要几分钟。1. 先看效果实测数据100 张 4K 原图手动处理2-3 小时脚本处理5 分钟节省时间97%水印对齐准确率自动识别主体位置不挡脸不挡文字2. 核心需求分析批量图片处理有三个真实痛点尺寸不统一公众号头图、朋友圈封面、小程序 icon 各有尺寸文件太大一次活动几百张图上传慢、加载慢水印难加加在角落挡内容加在中间挡主体传统工具PS、在线网站的问题是每次都要手动操作无法批量。3. 环境准备bashpip install Pillow python-dotenv tqdm openai4. 基础版纯规则处理4.1 缩放 压缩Python - image_processor.py基础版from PIL import Image import os from pathlib import Path from tqdm import tqdm # 1. 批量缩放 def resize_batch(input_dir: str, output_dir: str, max_width: int 1920): input_dir Path(input_dir) output_dir Path(output_dir) output_dir.mkdir(parentsTrue, exist_okTrue) image_files list(input_dir.glob(*.jpg)) \ list(input_dir.glob(*.png)) for img_path in tqdm(image_files, desc缩放中): img Image.open(img_path) # 等比缩放 width, height img.size if width max_width: ratio max_width / width new_size (max_width, int(height * ratio)) img img.resize(new_size, Image.LANCZOS) output_path output_dir / img_path.name img.save(output_path, quality85, optimizeTrue) print(f✅ {img_path.name} → {new_size}) # 2. 批量添加水印 def add_watermark(input_dir: str, output_dir: str, watermark_text: str): input_dir Path(input_dir) output_dir Path(output_dir) output_dir.mkdir(parentsTrue, exist_okTrue) image_files list(input_dir.glob(*.jpg)) \ list(input_dir.glob(*.png)) for img_path in tqdm(image_files, desc加水印中): img Image.open(img_path) img_w, img_h img.size # 创建水印层 watermark Image.new(RGBA, img.size, (0, 0, 0, 0)) from PIL import ImageDraw, ImageFont draw ImageDraw.Draw(watermark) font_size int(img_w / 40) try: font ImageFont.truetype(msyh.ttc, font_size) # 微软雅黑 except: font ImageFont.load_default() bbox draw.textbbox((0, 0), watermark_text, fontfont) text_w bbox[2] - bbox[0] text_h bbox[3] - bbox[1] # 水印位置右下角留 20px 边距 x img_w - text_w - 20 y img_h - text_h - 20 draw.text((x, y), watermark_text, fontfont, fill(255, 255, 255, 120)) # 合并 if img.mode ! RGBA: img img.convert(RGBA) img Image.alpha_composite(img, watermark) output_path output_dir / img_path.name img.convert(RGB).save(output_path, quality90) print(f✅ {img_path.name} → 已加水印) # 使用 resize_batch(./input, ./output, max_width1920) add_watermark(./output, ./final, watermark_text公众号名称)5. 进阶版AI 智能裁剪5.1 痛点基础版水印加在固定角落。如果图片主体在角落就会遮挡内容。用视觉大模型识别图片主体把水印加在不挡内容的位置。5.2 用 GPT-4o 识别主体位置Python - AI 智能裁剪核心代码from openai import OpenAI import base64 import json client OpenAI() def find_main_subject(image_path: str) - dict: 用 GPT-4o 识别图片主体位置返回安全区域坐标 with open(image_path, rb) as f: img_b64 base64.b64encode(f.read()).decode() response client.chat.completions.create( modelgpt-4o, messages[{ role: user, content: [ {type: image_url, image_url: {url: fdata:image/jpeg;base64,{img_b64}}}, {type: text, text: 这张图片的主体是什么主体大概在哪个区域四个角的哪个角或中间 请返回 JSON 格式 { subject: 主体描述, position: top_left | top_right | bottom_left | bottom_right | center, safe_area: bottom_right // 水印可以安全放的位置 }} ] }], max_tokens200 ) result_text response.choices[0].message.content # 解析 JSON return json.loads(result_text)5.3 智能水印位置Python - 智能水印位置策略from PIL import Image, ImageDraw, ImageFont def smart_watermark(img: Image.Image, text: str, position_hint: str bottom_right) - Image.Image: 根据主体位置智能放置水印 img_w, img_h img.size draw ImageDraw.Draw(img) font_size int(img_w / 50) try: font ImageFont.truetype(msyh.ttc, font_size) except: font ImageFont.load_default() bbox draw.textbbox((0, 0), text, fontfont) text_w bbox[2] - bbox[0] text_h bbox[3] - bbox[1] margin 20 # 根据安全区域决定水印位置 positions { bottom_right: (img_w - text_w - margin, img_h - text_h - margin), bottom_left: (margin, img_h - text_h - margin), top_right: (img_w - text_w - margin, margin), top_left: (margin, margin), center: ((img_w - text_w) // 2, (img_h - text_h) // 2), } pos positions.get(position_hint, positions[bottom_right]) # 半透明白字 draw.text(pos, text, fontfont, fill(255, 255, 255, 140)) return img6. 完整脚本一键处理Python - main.py完整版# main.py import os from pathlib import Path from tqdm import tqdm from PIL import Image, ImageDraw, ImageFont from openai import OpenAI import base64, json, time client OpenAI() # 配置 INPUT_DIR ./input_images OUTPUT_DIR ./output_images WATERMARK 你的公众号 MAX_WIDTH 1920 USE_AI_SMART True # 设为 False 用规则模式更快 Path(OUTPUT_DIR).mkdir(parentsTrue, exist_okTrue) # 工具函数 def resize(img: Image.Image, max_w: int) - Image.Image: w, h img.size if w max_w: img img.resize((max_w, int(h * max_w / w)), Image.LANCZOS) return img def find_safe_zone(img_path: str) - str: try: with open(img_path, rb) as f: b64 base64.b64encode(f.read()).decode() resp client.chat.completions.create( modelgpt-4o, messages[{ role: user, content: [ {type: image_url, image_url: {url: fdata:image/jpeg;base64,{b64}}}, {type: text, text: 水印放哪个角不挡内容返回top_left / top_right / bottom_left / bottom_right} ] }], max_tokens50 ) return resp.choices[0].message.content.strip() except Exception as e: print(f⚠️ AI 分析失败回退规则模式: {e}) return bottom_right def add_watermark(img: Image.Image, safe_zone: str, text: str) - Image.Image: img_w, img_h img.size draw ImageDraw.Draw(img) try: font ImageFont.truetype(msyh.ttc, int(img_w / 50)) except: font ImageFont.load_default() bbox draw.textbbox((0, 0), text, fontfont) tw, th bbox[2] - bbox[0], bbox[3] - bbox[1] m 20 pos_map { bottom_right: (img_w - tw - m, img_h - th - m), bottom_left: (m, img_h - th - m), top_right: (img_w - tw - m, m), top_left: (m, m), } pos pos_map.get(safe_zone, pos_map[bottom_right]) draw.text(pos, text, fontfont, fill(255, 255, 255, 140)) return img # 主流程 def process_batch(): files list(Path(INPUT_DIR).glob(*.jpg)) \ list(Path(INPUT_DIR).glob(*.png)) print(f 发现 {len(files)} 张图片开始处理...) for f in tqdm(files, desc处理中): img Image.open(f) # 1. 缩放 img resize(img, MAX_WIDTH) # 2. AI 找安全区 safe_zone bottom_right if USE_AI_SMART: safe_zone find_safe_zone(str(f)) time.sleep(0.5) # 防止 API 限流 # 3. 加水印 img add_watermark(img, safe_zone, WATERMARK) # 4. 保存 out Path(OUTPUT_DIR) / f.name img.convert(RGB).save(out, quality85, optimizeTrue) tqdm.write(f✅ {f.name} → {safe_zone}) print(f\n 完成共处理 {len(files)} 张图片结果在 {OUTPUT_DIR}) if __name__ __main__: process_batch()7. 使用说明bash# 1. 创建目录 mkdir input_images output_images # 2. 把图片放进 input_images/ # 3. 设置 API Key也可以用环境变量 # export OPENAI_API_KEYsk-... # 4. 运行 python main.py # 5. 查看结果 ls output_images/8. 成本分析模式100张图成本速度效果规则模式$0快1分钟一般水印位置固定AI 智能模式~$0.5慢10分钟好水印自动避让主体 建议日常批量处理用规则模式免费快重要活动图用 AI 智能模式效果好。9. 总结这个脚本解决了三个问题缩放统一最大宽度等比缩放不变形压缩降低文件大小加快加载水印规则模式免费快AI 模式智能避让主体核心代码不超过 150 行改改配置就能适配自己的场景。如果对你有帮助欢迎在评论区分享你的图片处理需求。