AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He
feat: 添加智能图片裁剪功能
hugohe387f6c5543d91
diff --git a/tools/crop_images.py b/tools/crop_images.pynew file mode 100644index 00000000..0f7889d4--- /dev/null+++ b/tools/crop_images.py@@ -0,0 +1,324 @@+#!/usr/bin/env python3+"""+PPT Master - 智能图片裁剪工具++根据 SVG 中 <image> 元素的 preserveAspectRatio 属性智能裁剪图片:+- slice: 裁剪填充(类似 CSS object-fit: cover)+- meet: 完整显示,不裁剪(类似 CSS object-fit: contain)++支持9种对齐方式:+- xMinYMin / xMidYMin / xMaxYMin (顶部对齐)+- xMinYMid / xMidYMid / xMaxYMid (垂直居中)+- xMinYMax / xMidYMax / xMaxYMax (底部对齐)++用法:+ python tools/crop_images.py <SVG文件或目录> [--dry-run]+"""++import os+import re+import hashlib+from pathlib import Path+from xml.etree import ElementTree as ET+from urllib.parse import unquote++try:+ from PIL import Image+except ImportError:+ print("Error: PIL (Pillow) is required. Run: pip install Pillow")+ exit(1)+++def parse_preserve_aspect_ratio(attr: str) -> tuple:+ """+ 解析 preserveAspectRatio 属性++ 返回: (align, meet_or_slice)+ align: 如 'xMidYMid'+ meet_or_slice: 'meet' 或 'slice'+ """+ if not attr:+ return ('xMidYMid', 'meet') # 默认值++ parts = attr.strip().split()+ align = parts[0] if parts else 'xMidYMid'+ meet_or_slice = parts[1] if len(parts) > 1 else 'meet'++ return (align, meet_or_slice)+++def get_crop_anchor(align: str) -> tuple:+ """+ 根据 align 值返回裁剪锚点++ 返回: (x_anchor, y_anchor)+ x_anchor: 0.0 (左), 0.5 (中), 1.0 (右)+ y_anchor: 0.0 (上), 0.5 (中), 1.0 (下)+ """+ x_map = {'xMin': 0.0, 'xMid': 0.5, 'xMax': 1.0}+ y_map = {'YMin': 0.0, 'YMid': 0.5, 'YMax': 1.0}++ x_anchor = 0.5+ y_anchor = 0.5++ for key, val in x_map.items():+ if key in align:+ x_anchor = val+ break++ for key, val in y_map.items():+ if key in align:+ y_anchor = val+ break++ return (x_anchor, y_anchor)+++def crop_image_to_size(img: Image.Image, target_width: int, target_height: int,+ x_anchor: float = 0.5, y_anchor: float = 0.5) -> Image.Image:+ """+ 按指定锚点裁剪图片到目标尺寸++ Args:+ img: PIL Image 对象+ target_width: 目标宽度+ target_height: 目标高度+ x_anchor: 水平锚点 (0=左, 0.5=中, 1=右)+ y_anchor: 垂直锚点 (0=上, 0.5=中, 1=下)++ Returns:+ 裁剪后的 PIL Image 对象+ """+ img_width, img_height = img.size++ # 计算缩放比例(取较大值以覆盖目标区域)+ scale = max(target_width / img_width, target_height / img_height)++ # 缩放图片+ new_width = int(img_width * scale)+ new_height = int(img_height * scale)+ img_resized = img.resize((new_width, new_height), Image.Resampling.LANCZOS)++ # 根据锚点计算裁剪位置+ extra_width = new_width - target_width+ extra_height = new_height - target_height++ left = int(extra_width * x_anchor)+ top = int(extra_height * y_anchor)+ right = left + target_width+ bottom = top + target_height++ return img_resized.crop((left, top, right, bottom))+++def process_svg_images(svg_file: str, output_dir: str = None, dry_run: bool = False,+ verbose: bool = True) -> tuple:+ """+ 处理 SVG 文件中的图片,根据 preserveAspectRatio 属性进行裁剪++ Args:+ svg_file: SVG 文件路径+ output_dir: 裁剪后图片的输出目录(默认为 images/cropped/)+ dry_run: 仅预览,不实际处理+ verbose: 详细输出++ Returns:+ (processed_count, error_count)+ """+ svg_path = Path(svg_file)+ svg_dir = svg_path.parent++ # 默认输出目录+ if output_dir is None:+ # 查找项目的 images 目录+ # svg_output 或 svg_final 的父目录下的 images+ project_dir = svg_dir.parent+ output_dir = project_dir / 'images' / 'cropped'+ else:+ output_dir = Path(output_dir)++ # 解析 SVG+ try:+ ET.register_namespace('', 'http://www.w3.org/2000/svg')+ ET.register_namespace('xlink', 'http://www.w3.org/1999/xlink')+ tree = ET.parse(str(svg_path))+ root = tree.getroot()+ except Exception as e:+ if verbose:+ print(f" [ERROR] 解析 SVG 失败: {e}")+ return (0, 1)++ ns = {'svg': 'http://www.w3.org/2000/svg', 'xlink': 'http://www.w3.org/1999/xlink'}++ processed_count = 0+ error_count = 0+ modified = False++ # 查找所有 image 元素+ for image in root.iter('{http://www.w3.org/2000/svg}image'):+ # 获取 href 属性+ href = image.get('{http://www.w3.org/1999/xlink}href') or image.get('href')+ if not href:+ continue++ # 跳过 base64 内嵌图片+ if href.startswith('data:'):+ continue++ # 获取 preserveAspectRatio 属性+ par = image.get('preserveAspectRatio', '')+ align, mode = parse_preserve_aspect_ratio(par)++ # 只处理 slice 模式+ if mode != 'slice':+ continue++ # 获取目标尺寸+ try:+ target_width = int(float(image.get('width', 0)))+ target_height = int(float(image.get('height', 0)))+ except (ValueError, TypeError):+ continue++ if target_width <= 0 or target_height <= 0:+ continue++ # 解析图片路径+ href_decoded = unquote(href)+ if href_decoded.startswith('../'):+ img_path = (svg_dir / href_decoded).resolve()+ else:+ img_path = (svg_dir / href_decoded).resolve()++ if not img_path.exists():+ if verbose:+ print(f" [SKIP] 图片不存在: {href}")+ continue++ # 获取裁剪锚点+ x_anchor, y_anchor = get_crop_anchor(align)++ if dry_run:+ if verbose:+ print(f" [DRY] {img_path.name} -> {target_width}x{target_height} "+ f"(align: {align}, anchor: {x_anchor},{y_anchor})")+ processed_count += 1+ continue++ # 创建输出目录+ output_dir.mkdir(parents=True, exist_ok=True)++ try:+ # 打开并处理图片+ img = Image.open(img_path)++ # 转换模式+ if img.mode in ('RGBA', 'P'):+ img = img.convert('RGB')++ # 裁剪+ cropped = crop_image_to_size(img, target_width, target_height, x_anchor, y_anchor)++ # 生成输出文件名(保持原文件名,放到 cropped 目录)+ output_filename = img_path.name+ output_path = output_dir / output_filename++ # 保存+ if img_path.suffix.lower() == '.png':+ cropped.save(output_path, 'PNG', optimize=True)+ else:+ cropped.save(output_path, 'JPEG', quality=90, optimize=True)++ if verbose:+ print(f" [OK] {img_path.name}: {img.size} -> {target_width}x{target_height} "+ f"({align})")++ # 更新 SVG 中的图片路径+ new_href = f"../images/cropped/{output_filename}"+ if image.get('{http://www.w3.org/1999/xlink}href'):+ image.set('{http://www.w3.org/1999/xlink}href', new_href)+ else:+ image.set('href', new_href)++ # 移除 preserveAspectRatio(图片已是正确尺寸)+ if 'preserveAspectRatio' in image.attrib:+ del image.attrib['preserveAspectRatio']++ modified = True+ processed_count += 1++ except Exception as e:+ if verbose:+ print(f" [ERROR] {img_path.name}: {e}")+ error_count += 1++ # 保存修改后的 SVG+ if modified and not dry_run:+ tree.write(str(svg_path), encoding='unicode', xml_declaration=False)++ return (processed_count, error_count)+++def process_directory(directory: str, dry_run: bool = False, verbose: bool = True) -> tuple:+ """处理目录中的所有 SVG 文件"""+ directory = Path(directory)+ total_processed = 0+ total_errors = 0++ for svg_file in directory.glob('*.svg'):+ if verbose:+ print(f" 处理: {svg_file.name}")+ processed, errors = process_svg_images(str(svg_file), dry_run=dry_run, verbose=verbose)+ total_processed += processed+ total_errors += errors++ return (total_processed, total_errors)+++def main():+ import argparse++ parser = argparse.ArgumentParser(+ description='PPT Master - 智能图片裁剪工具',+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog='''+示例:+ %(prog)s projects/my_project/svg_output+ %(prog)s page_01.svg --dry-run++preserveAspectRatio 用法:+ xMidYMid slice 居中裁剪(默认)+ xMidYMin slice 保留顶部+ xMidYMax slice 保留底部+ xMinYMid slice 保留左侧+ xMaxYMid slice 保留右侧+ xMidYMid meet 完整显示,不裁剪+ '''+ )++ parser.add_argument('path', type=Path, help='SVG 文件或目录')+ parser.add_argument('--dry-run', '-n', action='store_true', help='仅预览,不实际处理')+ parser.add_argument('--quiet', '-q', action='store_true', help='安静模式')++ args = parser.parse_args()++ if not args.path.exists():+ print(f"[ERROR] 路径不存在: {args.path}")+ exit(1)++ print("PPT Master - 智能图片裁剪")+ print("=" * 50)++ if args.path.is_file():+ processed, errors = process_svg_images(str(args.path), dry_run=args.dry_run,+ verbose=not args.quiet)+ else:+ processed, errors = process_directory(str(args.path), dry_run=args.dry_run,+ verbose=not args.quiet)++ print()+ print(f"完成: {processed} 张图片已裁剪, {errors} 个错误")+++if __name__ == '__main__':+ main()diff --git a/tools/finalize_svg.py b/tools/finalize_svg.pyindex 9a2ae213..01ff8dbc 100644--- a/tools/finalize_svg.py+++ b/tools/finalize_svg.py@@ -18,6 +18,7 @@ PPT Master - SVG 后处理工具(统一入口)处理选项:embed-icons - 替换 <use data-icon="..."/> 为实际图标 SVG+ crop-images - 根据 preserveAspectRatio="slice" 智能裁剪图片fix-aspect - 修复图片宽高比(防止 PPT 转形状时拉伸)embed-images - 将外部图片转换为 Base64 嵌入flatten-text - 将 <tspan> 转为独立 <text>(用于特殊渲染器)@@ -35,6 +36,7 @@ sys.path.insert(0, str(Path(__file__).parent))from embed_icons import process_svg_file as embed_icons_in_filefrom embed_images import embed_images_in_svgfrom fix_image_aspect import fix_image_aspect_in_svg+from crop_images import process_svg_images as crop_images_in_svgdef safe_print(text):@@ -134,7 +136,7 @@ def finalize_project(project_dir: Path, options: dict, dry_run: bool = False, qu# 步骤 2: 嵌入图标if options.get('embed_icons'):if not quiet:- safe_print("[1/5] 嵌入图标...")+ safe_print("[1/6] 嵌入图标...")icons_count = 0for svg_file in svg_final.glob('*.svg'):count = embed_icons_in_file(svg_file, icons_dir, dry_run=False, verbose=False)@@ -145,10 +147,26 @@ def finalize_project(project_dir: Path, options: dict, dry_run: bool = False, quelse:safe_print(" 无图标")- # 步骤 3: 修复图片宽高比(防止 PPT 转形状时拉伸)+ # 步骤 3: 智能裁剪图片(根据 preserveAspectRatio="slice")+ if options.get('crop_images'):+ if not quiet:+ safe_print("[2/6] 智能裁剪图片...")+ crop_count = 0+ crop_errors = 0+ for svg_file in svg_final.glob('*.svg'):+ count, errors = crop_images_in_svg(str(svg_file), dry_run=False, verbose=False)+ crop_count += count+ crop_errors += errors+ if not quiet:+ if crop_count > 0:+ safe_print(f" {crop_count} 张图片已裁剪")+ else:+ safe_print(" 无需裁剪(无 slice 属性的图片)")++ # 步骤 4: 修复图片宽高比(防止 PPT 转形状时拉伸)if options.get('fix_aspect'):if not quiet:- safe_print("[2/5] 修复图片宽高比...")+ safe_print("[3/6] 修复图片宽高比...")aspect_count = 0for svg_file in svg_final.glob('*.svg'):count = fix_image_aspect_in_svg(str(svg_file), dry_run=False, verbose=False)@@ -159,10 +177,10 @@ def finalize_project(project_dir: Path, options: dict, dry_run: bool = False, quelse:safe_print(" 无图片")- # 步骤 4: 嵌入图片+ # 步骤 5: 嵌入图片if options.get('embed_images'):if not quiet:- safe_print("[3/5] 嵌入图片...")+ safe_print("[4/6] 嵌入图片...")images_count = 0for svg_file in svg_final.glob('*.svg'):count, _ = embed_images_in_svg(str(svg_file), dry_run=False)@@ -173,10 +191,10 @@ def finalize_project(project_dir: Path, options: dict, dry_run: bool = False, quelse:safe_print(" 无图片")- # 步骤 5: 文本扁平化+ # 步骤 6: 文本扁平化if options.get('flatten_text'):if not quiet:- safe_print("[4/5] 文本扁平化...")+ safe_print("[5/6] 文本扁平化...")flatten_count = 0for svg_file in svg_final.glob('*.svg'):if process_flatten_text(svg_file, verbose=False):@@ -187,10 +205,10 @@ def finalize_project(project_dir: Path, options: dict, dry_run: bool = False, quelse:safe_print(" 无需处理")- # 步骤 6: 圆角转 Path+ # 步骤 7: 圆角转 Pathif options.get('fix_rounded'):if not quiet:- safe_print("[5/5] 圆角转 Path...")+ safe_print("[6/6] 圆角转 Path...")rounded_count = 0for svg_file in svg_final.glob('*.svg'):count = process_rounded_rect(svg_file, verbose=False)@@ -224,6 +242,7 @@ def main():处理选项(用于 --only):embed-icons 嵌入图标+ crop-images 智能裁剪图片(根据 preserveAspectRatio)fix-aspect 修复图片宽高比(防止 PPT 转形状时拉伸)embed-images 嵌入图片flatten-text 文本扁平化@@ -233,7 +252,7 @@ def main():parser.add_argument('project_dir', type=Path, help='项目目录路径')parser.add_argument('--only', nargs='+', metavar='OPTION',- choices=['embed-icons', 'fix-aspect', 'embed-images', 'flatten-text', 'fix-rounded'],+ choices=['embed-icons', 'crop-images', 'fix-aspect', 'embed-images', 'flatten-text', 'fix-rounded'],help='只执行指定的处理(默认执行全部)')parser.add_argument('--dry-run', '-n', action='store_true',help='仅预览操作,不实际执行')@@ -251,6 +270,7 @@ def main():# 只执行指定的处理options = {'embed_icons': 'embed-icons' in args.only,+ 'crop_images': 'crop-images' in args.only,'fix_aspect': 'fix-aspect' in args.only,'embed_images': 'embed-images' in args.only,'flatten_text': 'flatten-text' in args.only,@@ -260,6 +280,7 @@ def main():# 默认执行全部options = {'embed_icons': True,+ 'crop_images': True,'fix_aspect': True,'embed_images': True,'flatten_text': True,