Skip to content

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(tools): 新增 fix_image_aspect.py 工具,修复 PPT 转形状时图片拉伸问题

hugohe3c3a535a6ea55
diff --git a/README.md b/README.md
index 69e77ee4..23bc8543 100644
--- a/README.md
+++ b/README.md
@@ -172,7 +172,7 @@ PPT Master 是一个创新的 AI 辅助视觉内容创作系统,通过四个
SVG 文件 (svg_output/)
↓
后处理工具(用户自行调用)
- ├── finalize_svg.py → svg_final/(嵌入图标/图片 + 文本扁平化 + 圆角转Path)
+ ├── finalize_svg.py → svg_final/(嵌入图标 + 修复图片宽高比 + 嵌入图片 + 文本扁平化 + 圆角转Path)
└── svg_to_pptx.py → output.pptx(导出 PowerPoint)
```
@@ -603,9 +603,10 @@ ppt-master/
│ ├── project_manager.py # 项目管理工具
│ ├── svg_quality_checker.py # SVG 质量检查
│ ├── batch_validate.py # 批量验证工具
-│ ├── finalize_svg.py # 最终化处理(嵌入图标/图片)
+│ ├── finalize_svg.py # 最终化处理(嵌入图标 + 修复图片宽高比 + 嵌入图片)
│ ├── embed_icons.py # 图标嵌入工具
│ ├── embed_images.py # 图片嵌入工具
+│ ├── fix_image_aspect.py # 图片宽高比修复工具(防止 PPT 转形状时拉伸)
│ ├── flatten_tspan.py # tspan扁平化工具
│ └── svg_to_pptx.py # SVG转PPTX工具(原生矢量嵌入)
│
@@ -853,13 +854,20 @@ python3 tools/generate_examples_index.py
### 后处理工具 (`finalize_svg.py`)
-统一后处理入口,执行嵌入图标/图片、文本扁平化、圆角转 Path:
+统一后处理入口,执行嵌入图标、修复图片宽高比、嵌入图片、文本扁平化、圆角转 Path:
```bash
# 直接运行,无需参数
python3 tools/finalize_svg.py <项目路径>
```
+**处理步骤**:
+1. 嵌入图标 - 替换 `<use data-icon="..."/>` 为实际图标
+2. 修复图片宽高比 - 防止 PPT 转形状时图片拉伸变形 ✨
+3. 嵌入图片 - 将外部图片转为 Base64
+4. 文本扁平化 - 将 `<tspan>` 转为独立 `<text>`
+5. 圆角转 Path - 将 `<rect rx="..."/>` 转为 `<path>`
+
**注意**:生成阶段仍应使用 `<tspan>` 手动换行,后处理会自动扁平化。
### SVG 转 PPTX 工具 (`svg_to_pptx.py`)
diff --git a/README_EN.md b/README_EN.md
index 72329cee..9b4a6bed 100644
--- a/README_EN.md
+++ b/README_EN.md
@@ -172,7 +172,7 @@ User Input Document
SVG Files (svg_output/)
↓
Post-processing Tools (User invoked)
- ├── finalize_svg.py → svg_final/ (Embed icons/images + Text flattening + Round corners to Path)
+ ├── finalize_svg.py → svg_final/ (Embed icons + Fix image aspect ratio + Embed images + Text flattening + Round corners to Path)
└── svg_to_pptx.py → output.pptx (Export to PowerPoint)
```
@@ -603,9 +603,10 @@ ppt-master/
│ ├── project_manager.py # Project management tool
│ ├── svg_quality_checker.py # SVG quality check
│ ├── batch_validate.py # Batch validation tool
-│ ├── finalize_svg.py # Finalization processing (embed icons/images)
+│ ├── finalize_svg.py # Finalization processing (embed icons + fix image aspect + embed images)
│ ├── embed_icons.py # Icon embedding tool
│ ├── embed_images.py # Image embedding tool
+│ ├── fix_image_aspect.py # Image aspect ratio fix tool (prevent stretching in PPT)
│ ├── flatten_tspan.py # tspan flattening tool
│ └── svg_to_pptx.py # SVG to PPTX tool (native vector embedding)
│
@@ -853,13 +854,20 @@ python3 tools/generate_examples_index.py
### Post-processing Tool (`finalize_svg.py`)
-Unified post-processing entry, performs icon/image embedding, text flattening, round corners to Path:
+Unified post-processing entry, performs icon embedding, image aspect ratio fixing, image embedding, text flattening, round corners to Path:
```bash
# Run directly, no parameters needed
python3 tools/finalize_svg.py <project_path>
```
+**Processing Steps**:
+1. Embed icons - Replace `<use data-icon="..."/>` with actual icons
+2. Fix image aspect ratio - Prevent image stretching when converting to shapes in PPT ✨
+3. Embed images - Convert external images to Base64
+4. Text flattening - Convert `<tspan>` to independent `<text>`
+5. Round corners to Path - Convert `<rect rx="..."/>` to `<path>`
+
**Note**: Generation phase should still use `<tspan>` for manual line breaks, post-processing will auto-flatten.
### SVG to PPTX Tool (`svg_to_pptx.py`)
diff --git a/roles/README.md b/roles/README.md
index d86a0249..855a9f87 100644
--- a/roles/README.md
+++ b/roles/README.md
@@ -36,7 +36,7 @@
SVG 文件 (svg_output/)
↓
后处理工具 (推荐,用户自行调用)
- ├── finalize_svg.py → svg_final/ (嵌入图标/图片 + 文本扁平化 + 圆角转Path)
+ ├── finalize_svg.py → svg_final/ (嵌入图标 + 修复图片宽高比 + 嵌入图片 + 文本扁平化 + 圆角转Path)
└── svg_to_pptx.py → output.pptx (导出 PowerPoint)
```
diff --git a/tools/README.md b/tools/README.md
index f352cb8f..92be4e18 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -691,6 +691,51 @@ python3 tools/svg_rect_to_path.py examples/ppt169_demo/svg_output/01_cover.svg
---
+### 11. fix_image_aspect.py — SVG 图片宽高比修复工具
+
+解决 SVG 中 `<image>` 元素在 PowerPoint「转换为形状」时图片拉伸变形的问题。
+
+**问题**: PowerPoint 在将 SVG 转换为可编辑形状时,会忽略 `preserveAspectRatio` 属性,导致图片被拉伸以填满指定的 width/height 区域。
+
+**解决方案**:
+1. 读取图片的原始宽高比
+2. 根据 `preserveAspectRatio` 模式(meet/slice)计算正确的 x, y, width, height
+3. 移除 `preserveAspectRatio` 属性,用精确计算的尺寸替代
+
+**用法**:
+
+```bash
+# 处理单个 SVG 文件
+python3 tools/fix_image_aspect.py path/to/slide.svg
+
+# 处理多个文件
+python3 tools/fix_image_aspect.py slide_01.svg slide_02.svg slide_03.svg
+
+# 预览模式(不修改文件)
+python3 tools/fix_image_aspect.py --dry-run path/to/slide.svg
+
+# 通过 finalize_svg.py 自动处理(推荐)
+python3 tools/finalize_svg.py <项目路径>
+```
+
+**依赖**:
+
+```bash
+pip install Pillow # 用于读取图片尺寸(推荐安装)
+```
+
+> **注意**: 如果没有安装 Pillow,工具会尝试用基本方法读取 PNG/JPEG 的头信息,但建议安装以获得更好的兼容性。
+
+**使用场景**:
+
+当你需要在 PowerPoint 中将 SVG「转换为形状」进行编辑,且 SVG 中包含图片时,使用此工具可以防止图片拉伸变形。
+
+**已集成到 finalize_svg.py**:
+
+此工具已作为 `finalize_svg.py` 的处理步骤之一(`fix-aspect`),默认自动执行。
+
+---
+
## 工作流集成
### 典型工作流程
diff --git a/tools/analyze_images.py b/tools/analyze_images.py
new file mode 100644
index 00000000..bc75984c
--- /dev/null
+++ b/tools/analyze_images.py
@@ -0,0 +1,186 @@
+#!/usr/bin/env python3
+"""
+图片尺寸分析工具
+================
+分析指定文件夹中所有图片的宽度、高度、长宽比,输出PPT适配建议。
+
+用法:
+ python tools/analyze_images.py <images_folder_path>
+ python tools/analyze_images.py projects/xxx/images
+
+输出:
+ - 控制台显示分析报告
+ - 在图片目录的父目录生成 image_analysis.csv
+"""
+
+import os
+import sys
+from pathlib import Path
+
+try:
+ from PIL import Image
+except ImportError:
+ print("Error: PIL/Pillow not installed. Run: pip install Pillow")
+ sys.exit(1)
+
+
+def analyze_images(images_dir):
+ """分析指定目录下所有图片的尺寸信息"""
+
+ # 支持的图片格式
+ image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.tiff', '.tif'}
+
+ results = []
+
+ # 遍历目录中的所有文件
+ for filename in sorted(os.listdir(images_dir)):
+ filepath = os.path.join(images_dir, filename)
+
+ # 检查是否为图片文件
+ if os.path.isfile(filepath) and Path(filename).suffix.lower() in image_extensions:
+ try:
+ with Image.open(filepath) as img:
+ width, height = img.size
+ aspect_ratio = width / height
+
+ # 判断适合的PPT布局建议
+ if aspect_ratio > 1.5:
+ layout_hint = "宽幅横图"
+ elif aspect_ratio > 1.2:
+ layout_hint = "标准横图"
+ elif aspect_ratio > 0.8:
+ layout_hint = "接近正方形"
+ elif aspect_ratio > 0.6:
+ layout_hint = "标准竖图"
+ else:
+ layout_hint = "窄幅竖图"
+
+ results.append({
+ 'filename': filename,
+ 'width': width,
+ 'height': height,
+ 'aspect_ratio': aspect_ratio,
+ 'layout_hint': layout_hint,
+ 'filesize_kb': os.path.getsize(filepath) / 1024
+ })
+ except Exception as e:
+ print(f"[WARN] Cannot read {filename}: {e}")
+
+ return results
+
+
+def print_results(results):
+ """打印分析结果"""
+
+ print("\n" + "="*100)
+ print("Image Size Analysis Report")
+ print("="*100)
+
+ # 表头
+ print(f"\n{'No.':<4} {'Width':<7} {'Height':<7} {'Ratio':<7} {'Size':<10} {'Layout':<15} {'Filename'}")
+ print("-"*100)
+
+ for i, img in enumerate(results, 1):
+ print(f"{i:<4} {img['width']:<7} {img['height']:<7} {img['aspect_ratio']:<7.2f} {img['filesize_kb']:<10.1f}KB {img['layout_hint']:<15} {img['filename'][:40]}")
+
+ print("-"*100)
+ print(f"Total: {len(results)} images\n")
+
+ # 按长宽比分组统计
+ print("\nGroup by Aspect Ratio:")
+ print("-"*50)
+
+ categories = {
+ "Wide (>1.5)": [],
+ "Standard (1.2-1.5)": [],
+ "Square (0.8-1.2)": [],
+ "Portrait (0.6-0.8)": [],
+ "Narrow (<0.6)": []
+ }
+
+ for img in results:
+ ar = img['aspect_ratio']
+ if ar > 1.5:
+ categories["Wide (>1.5)"].append(img)
+ elif ar > 1.2:
+ categories["Standard (1.2-1.5)"].append(img)
+ elif ar > 0.8:
+ categories["Square (0.8-1.2)"].append(img)
+ elif ar > 0.6:
+ categories["Portrait (0.6-0.8)"].append(img)
+ else:
+ categories["Narrow (<0.6)"].append(img)
+
+ for cat, imgs in categories.items():
+ if imgs:
+ print(f"\n{cat}: {len(imgs)} images")
+ for img in imgs[:5]: # 只显示前5个
+ print(f" - {img['width']}x{img['height']} (ratio {img['aspect_ratio']:.2f}) - {img['filename'][:35]}...")
+ if len(imgs) > 5:
+ print(f" ... and {len(imgs) - 5} more")
+
+ # 输出PPT适配建议
+ print("\n" + "="*100)
+ print("PPT Fit Suggestions (16:9 = 1280x720)")
+ print("="*100)
+
+ ppt_width, ppt_height = 1280, 720
+ ppt_ratio = ppt_width / ppt_height
+
+ print(f"\nStandard PPT canvas: {ppt_width}x{ppt_height} (ratio {ppt_ratio:.2f})")
+
+ fit_count = 0
+ for img in results:
+ if 1.5 <= img['aspect_ratio'] <= 2.0:
+ fit_count += 1
+
+ print(f"\nImages suitable for full-screen display: {fit_count}")
+
+
+def save_csv(results, csv_path):
+ """保存结果到CSV文件"""
+ with open(csv_path, 'w', encoding='utf-8') as f:
+ f.write("No,Filename,Width,Height,AspectRatio,SizeKB,Layout\n")
+ for i, img in enumerate(results, 1):
+ f.write(f"{i},{img['filename']},{img['width']},{img['height']},{img['aspect_ratio']:.2f},{img['filesize_kb']:.1f},{img['layout_hint']}\n")
+ print(f"\nCSV saved to: {csv_path}")
+
+
+def main():
+ if len(sys.argv) < 2:
+ print("Usage: python analyze_images.py <images_folder_path>")
+ print("Example: python analyze_images.py projects/myproject/images")
+ print(" python analyze_images.py C:/path/to/images")
+ sys.exit(1)
+
+ images_dir = sys.argv[1]
+
+ # 转换为绝对路径
+ images_dir = os.path.abspath(images_dir)
+
+ if not os.path.exists(images_dir):
+ print(f"Error: Directory not found: {images_dir}")
+ sys.exit(1)
+
+ if not os.path.isdir(images_dir):
+ print(f"Error: Not a directory: {images_dir}")
+ sys.exit(1)
+
+ print(f"Analyzing: {images_dir}")
+
+ results = analyze_images(images_dir)
+
+ if results:
+ print_results(results)
+
+ # 保存到CSV文件(保存在图片目录的父目录)
+ parent_dir = os.path.dirname(images_dir)
+ csv_path = os.path.join(parent_dir, "image_analysis.csv")
+ save_csv(results, csv_path)
+ else:
+ print("No image files found in the directory.")
+
+
+if __name__ == "__main__":
+ main()
+
diff --git a/tools/finalize_svg.py b/tools/finalize_svg.py
index 4b897f67..9a2ae213 100644
--- a/tools/finalize_svg.py
+++ b/tools/finalize_svg.py
@@ -18,6 +18,7 @@ PPT Master - SVG 后处理工具(统一入口)
处理选项:
embed-icons - 替换 <use data-icon="..."/> 为实际图标 SVG
+ fix-aspect - 修复图片宽高比(防止 PPT 转形状时拉伸)
embed-images - 将外部图片转换为 Base64 嵌入
flatten-text - 将 <tspan> 转为独立 <text>(用于特殊渲染器)
fix-rounded - 将 <rect rx="..."/> 转为 <path>(用于 PPT 转形状)
@@ -33,6 +34,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from embed_icons import process_svg_file as embed_icons_in_file
from embed_images import embed_images_in_svg
+from fix_image_aspect import fix_image_aspect_in_svg
def safe_print(text):
@@ -132,7 +134,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/4] 嵌入图标...")
+ safe_print("[1/5] 嵌入图标...")
icons_count = 0
for svg_file in svg_final.glob('*.svg'):
count = embed_icons_in_file(svg_file, icons_dir, dry_run=False, verbose=False)
@@ -143,10 +145,24 @@ def finalize_project(project_dir: Path, options: dict, dry_run: bool = False, qu
else:
safe_print(" 无图标")
- # 步骤 3: 嵌入图片
+ # 步骤 3: 修复图片宽高比(防止 PPT 转形状时拉伸)
+ if options.get('fix_aspect'):
+ if not quiet:
+ safe_print("[2/5] 修复图片宽高比...")
+ aspect_count = 0
+ for svg_file in svg_final.glob('*.svg'):
+ count = fix_image_aspect_in_svg(str(svg_file), dry_run=False, verbose=False)
+ aspect_count += count
+ if not quiet:
+ if aspect_count > 0:
+ safe_print(f" {aspect_count} 张图片已修复")
+ else:
+ safe_print(" 无图片")
+
+ # 步骤 4: 嵌入图片
if options.get('embed_images'):
if not quiet:
- safe_print("[2/4] 嵌入图片...")
+ safe_print("[3/5] 嵌入图片...")
images_count = 0
for svg_file in svg_final.glob('*.svg'):
count, _ = embed_images_in_svg(str(svg_file), dry_run=False)
@@ -157,10 +173,10 @@ def finalize_project(project_dir: Path, options: dict, dry_run: bool = False, qu
else:
safe_print(" 无图片")
- # 步骤 4: 文本扁平化
+ # 步骤 5: 文本扁平化
if options.get('flatten_text'):
if not quiet:
- safe_print("[3/4] 文本扁平化...")
+ safe_print("[4/5] 文本扁平化...")
flatten_count = 0
for svg_file in svg_final.glob('*.svg'):
if process_flatten_text(svg_file, verbose=False):
@@ -171,10 +187,10 @@ def finalize_project(project_dir: Path, options: dict, dry_run: bool = False, qu
else:
safe_print(" 无需处理")
- # 步骤 5: 圆角转 Path
+ # 步骤 6: 圆角转 Path
if options.get('fix_rounded'):
if not quiet:
- safe_print("[4/4] 圆角转 Path...")
+ safe_print("[5/5] 圆角转 Path...")
rounded_count = 0
for svg_file in svg_final.glob('*.svg'):
count = process_rounded_rect(svg_file, verbose=False)
@@ -208,6 +224,7 @@ def main():
处理选项(用于 --only):
embed-icons 嵌入图标
+ fix-aspect 修复图片宽高比(防止 PPT 转形状时拉伸)
embed-images 嵌入图片
flatten-text 文本扁平化
fix-rounded 圆角转 Path
@@ -216,7 +233,7 @@ def main():
parser.add_argument('project_dir', type=Path, help='项目目录路径')
parser.add_argument('--only', nargs='+', metavar='OPTION',
- choices=['embed-icons', 'embed-images', 'flatten-text', 'fix-rounded'],
+ choices=['embed-icons', 'fix-aspect', 'embed-images', 'flatten-text', 'fix-rounded'],
help='只执行指定的处理(默认执行全部)')
parser.add_argument('--dry-run', '-n', action='store_true',
help='仅预览操作,不实际执行')
@@ -234,6 +251,7 @@ def main():
# 只执行指定的处理
options = {
'embed_icons': 'embed-icons' in args.only,
+ 'fix_aspect': 'fix-aspect' in args.only,
'embed_images': 'embed-images' in args.only,
'flatten_text': 'flatten-text' in args.only,
'fix_rounded': 'fix-rounded' in args.only,
@@ -242,6 +260,7 @@ def main():
# 默认执行全部
options = {
'embed_icons': True,
+ 'fix_aspect': True,
'embed_images': True,
'flatten_text': True,
'fix_rounded': True,
diff --git a/tools/fix_image_aspect.py b/tools/fix_image_aspect.py
new file mode 100644
index 00000000..ab896ca4
--- /dev/null
+++ b/tools/fix_image_aspect.py
@@ -0,0 +1,373 @@
+#!/usr/bin/env python3
+"""
+SVG 图片宽高比修复工具
+
+修复 SVG 中 <image> 元素的尺寸,使其与图片原始宽高比一致。
+这样在 PowerPoint 将 SVG 转换为形状时,图片不会被拉伸变形。
+
+原理:
+ PowerPoint 在将 SVG 转换为可编辑形状时,会忽略 preserveAspectRatio 属性,
+ 直接将图片拉伸以填满 width/height 指定的区域。
+
+ 此工具会读取实际图片的宽高比,重新计算 <image> 元素的 x, y, width, height,
+ 使图片居中显示且保持原始宽高比。
+
+用法:
+ python3 tools/fix_image_aspect.py <svg_file> [svg_file2] ...
+ python3 tools/fix_image_aspect.py projects/xxx/svg_output/*.svg
+
+ # 预览模式
+ python3 tools/fix_image_aspect.py --dry-run projects/xxx/svg_output/*.svg
+
+示例:
+ python3 tools/fix_image_aspect.py projects/应急避难场所专项规划/svg_output/slide_06_current_overview.svg
+"""
+
+import os
+import re
+import sys
+import base64
+import argparse
+from pathlib import Path
+from xml.etree import ElementTree as ET
+
+# 尝试导入 PIL,用于获取图片尺寸
+try:
+ from PIL import Image
+ HAS_PIL = True
+except ImportError:
+ HAS_PIL = False
+ print("[WARN] PIL not installed. Install with: pip install Pillow")
+ print(" Will try to use basic method for JPEG/PNG files.")
+
+
+def get_image_dimensions_pil(image_path):
+ """使用 PIL 获取图片尺寸"""
+ try:
+ with Image.open(image_path) as img:
+ return img.width, img.height
+ except Exception as e:
+ print(f" [WARN] Cannot read image with PIL: {e}")
+ return None, None
+
+
+def get_image_dimensions_basic(image_path):
+ """基本方法获取图片尺寸(不依赖 PIL)"""
+ try:
+ with open(image_path, 'rb') as f:
+ data = f.read(64) # 读取头部信息
+
+ # PNG
+ if data[:8] == b'\x89PNG\r\n\x1a\n':
+ w = int.from_bytes(data[16:20], 'big')
+ h = int.from_bytes(data[20:24], 'big')
+ return w, h
+
+ # JPEG
+ if data[:2] == b'\xff\xd8':
+ # 需要完整读取文件来解析 JPEG
+ with open(image_path, 'rb') as f:
+ f.seek(2)
+ while True:
+ marker = f.read(2)
+ if not marker or len(marker) < 2:
+ break
+ if marker[0] != 0xff:
+ break
+ m = marker[1]
+ # SOF0, SOF2 markers contain dimensions
+ if m in (0xC0, 0xC2):
+ f.read(3) # Skip length and precision
+ h = int.from_bytes(f.read(2), 'big')
+ w = int.from_bytes(f.read(2), 'big')
+ return w, h
+ elif m == 0xD9: # EOI
+ break
+ elif m == 0xD8: # SOI
+ continue
+ elif 0xD0 <= m <= 0xD7: # RST
+ continue
+ else:
+ length = int.from_bytes(f.read(2), 'big')
+ f.seek(length - 2, 1)
+
+ return None, None
+ except Exception as e:
+ print(f" [WARN] Cannot read image dimensions: {e}")
+ return None, None
+
+
+def get_image_dimensions_from_base64(data_uri):
+ """从 Base64 数据 URI 获取图片尺寸"""
+ import io
+ try:
+ # 解析 data URI
+ match = re.match(r'data:image/(\w+);base64,(.+)', data_uri)
+ if not match:
+ return None, None
+
+ img_format = match.group(1)
+ b64_data = match.group(2)
+ img_bytes = base64.b64decode(b64_data)
+
+ if HAS_PIL:
+ with Image.open(io.BytesIO(img_bytes)) as img:
+ return img.width, img.height
+ else:
+ # 使用基本方法
+ if img_bytes[:8] == b'\x89PNG\r\n\x1a\n':
+ w = int.from_bytes(img_bytes[16:20], 'big')
+ h = int.from_bytes(img_bytes[20:24], 'big')
+ return w, h
+
+ return None, None
+ except Exception as e:
+ print(f" [WARN] Cannot parse base64 image: {e}")
+ return None, None
+
+
+def get_image_dimensions(href, svg_dir):
+ """获取图片尺寸"""
+ # 处理 data URI
+ if href.startswith('data:'):
+ return get_image_dimensions_from_base64(href)
+
+ # 处理外部文件
+ if not os.path.isabs(href):
+ full_path = os.path.join(svg_dir, href)
+ else:
+ full_path = href
+
+ if not os.path.exists(full_path):
+ print(f" [WARN] Image not found: {href}")
+ return None, None
+
+ if HAS_PIL:
+ return get_image_dimensions_pil(full_path)
+ else:
+ return get_image_dimensions_basic(full_path)
+
+
+def calculate_fitted_dimensions(img_width, img_height, box_width, box_height, mode='meet'):
+ """
+ 计算图片在框内的适合尺寸
+
+ Args:
+ img_width, img_height: 图片原始尺寸
+ box_width, box_height: 容器框尺寸
+ mode: 'meet' 保持宽高比,完全显示图片(可能有留白)
+ 'slice' 保持宽高比,完全填充容器(可能裁剪)
+
+ Returns:
+ (new_width, new_height, offset_x, offset_y)
+ """
+ img_ratio = img_width / img_height
+ box_ratio = box_width / box_height
+
+ if mode == 'meet':
+ # 完全显示图片,可能有留白
+ if img_ratio > box_ratio:
+ # 图片更宽,以宽度为准
+ new_width = box_width
+ new_height = box_width / img_ratio
+ else:
+ # 图片更高,以高度为准
+ new_height = box_height
+ new_width = box_height * img_ratio
+ else: # slice
+ # 完全填充容器,可能裁剪
+ if img_ratio > box_ratio:
+ # 图片更宽,以高度为准
+ new_height = box_height
+ new_width = box_height * img_ratio
+ else:
+ # 图片更高,以宽度为准
+ new_width = box_width
+ new_height = box_width / img_ratio
+
+ # 居中偏移
+ offset_x = (box_width - new_width) / 2
+ offset_y = (box_height - new_height) / 2
+
+ return new_width, new_height, offset_x, offset_y
+
+
+def fix_image_aspect_in_svg(svg_path, dry_run=False, verbose=True):
+ """
+ 修复 SVG 中图片的宽高比
+
+ Args:
+ svg_path: SVG 文件路径
+ dry_run: 是否只预览不修改
+ verbose: 是否输出详细信息
+
+ Returns:
+ 修复的图片数量
+ """
+ svg_dir = os.path.dirname(os.path.abspath(svg_path))
+
+ with open(svg_path, 'r', encoding='utf-8') as f:
+ content = f.read()
+
+ # 注册 SVG 命名空间
+ namespaces = {
+ '': 'http://www.w3.org/2000/svg',
+ 'xlink': 'http://www.w3.org/1999/xlink',
+ 'svg': 'http://www.w3.org/2000/svg',
+ 'sodipodi': 'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd',
+ 'inkscape': 'http://www.inkscape.org/namespaces/inkscape',
+ }
+
+ for prefix, uri in namespaces.items():
+ if prefix:
+ ET.register_namespace(prefix, uri)
+ else:
+ ET.register_namespace('', uri)
+
+ try:
+ tree = ET.parse(svg_path)
+ root = tree.getroot()
+ except ET.ParseError as e:
+ print(f" [ERROR] Cannot parse SVG: {e}")
+ return 0
+
+ # 查找所有 image 元素
+ fixed_count = 0
+
+ # 检查带命名空间和不带命名空间的 image 元素
+ for ns_prefix in ['', '{http://www.w3.org/2000/svg}']:
+ for image_elem in root.iter(f'{ns_prefix}image'):
+ # 获取 href 属性(支持 xlink:href 和 href)
+ href = image_elem.get('{http://www.w3.org/1999/xlink}href')
+ if href is None:
+ href = image_elem.get('href')
+ if href is None:
+ continue
+
+ # 获取当前尺寸和位置
+ try:
+ x = float(image_elem.get('x', 0))
+ y = float(image_elem.get('y', 0))
+ width = float(image_elem.get('width', 0))
+ height = float(image_elem.get('height', 0))
+ except (ValueError, TypeError):
+ continue
+
+ if width <= 0 or height <= 0:
+ continue
+
+ # 获取 preserveAspectRatio
+ par = image_elem.get('preserveAspectRatio', 'xMidYMid meet')
+
+ # 解析 preserveAspectRatio
+ # 格式: <align> [<meetOrSlice>]
+ # 例如: xMidYMid meet, xMidYMid slice, none
+ par_parts = par.split()
+ align = par_parts[0] if par_parts else 'xMidYMid'
+ meet_or_slice = par_parts[1] if len(par_parts) > 1 else 'meet'
+
+ if align == 'none':
+ # 如果是 none,不需要修复
+ continue
+
+ # 获取图片原始尺寸
+ img_width, img_height = get_image_dimensions(href, svg_dir)
+ if img_width is None or img_height is None:
+ continue
+
+ # 计算适合的尺寸
+ mode = 'slice' if meet_or_slice == 'slice' else 'meet'
+ new_width, new_height, offset_x, offset_y = calculate_fitted_dimensions(
+ img_width, img_height, width, height, mode
+ )
+
+ # 检查是否需要修改
+ tolerance = 0.5 # 允许的误差
+ if (abs(new_width - width) < tolerance and
+ abs(new_height - height) < tolerance):
+ # 尺寸已经正确,无需修改
+ continue
+
+ if verbose:
+ img_name = os.path.basename(href.split('?')[0][:50] if not href.startswith('data:') else '[base64]')
+ print(f" [FIX] {img_name}")
+ print(f" 原图尺寸: {img_width}x{img_height} (ratio: {img_width/img_height:.3f})")
+ print(f" 原框尺寸: {width}x{height} @ ({x}, {y})")
+ print(f" 新框尺寸: {new_width:.1f}x{new_height:.1f} @ ({x + offset_x:.1f}, {y + offset_y:.1f})")
+
+ if not dry_run:
+ # 更新属性
+ image_elem.set('x', f'{x + offset_x:.1f}')
+ image_elem.set('y', f'{y + offset_y:.1f}')
+ image_elem.set('width', f'{new_width:.1f}')
+ image_elem.set('height', f'{new_height:.1f}')
+ # 移除 preserveAspectRatio,因为现在尺寸已经正确
+ if 'preserveAspectRatio' in image_elem.attrib:
+ del image_elem.attrib['preserveAspectRatio']
+
+ fixed_count += 1
+
+ if not dry_run and fixed_count > 0:
+ # 保存修改
+ tree.write(svg_path, encoding='unicode', xml_declaration=True)
+
+ return fixed_count
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description='修复 SVG 中图片的宽高比,防止 PowerPoint 转换时拉伸变形',
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog='''
+示例:
+ %(prog)s slide_01.svg # 处理单个文件
+ %(prog)s *.svg # 处理当前目录所有 SVG
+ %(prog)s --dry-run *.svg # 预览将处理的文件
+ %(prog)s projects/xxx/svg_output/*.svg # 处理项目目录
+ '''
+ )
+ parser.add_argument('files', nargs='+', 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 args.dry_run:
+ print("[INFO] 预览模式:只显示将要修改的内容,不实际修改文件\n")
+
+ total_fixed = 0
+ total_files = 0
+
+ for svg_file in args.files:
+ if not os.path.exists(svg_file):
+ if not args.quiet:
+ print(f"[ERROR] 文件不存在: {svg_file}")
+ continue
+
+ if not svg_file.endswith('.svg'):
+ if not args.quiet:
+ print(f"[SKIP] 跳过非 SVG 文件: {svg_file}")
+ continue
+
+ if not args.quiet:
+ print(f"\n[FILE] {os.path.basename(svg_file)}")
+
+ fixed = fix_image_aspect_in_svg(svg_file, dry_run=args.dry_run, verbose=not args.quiet)
+
+ if fixed > 0:
+ total_fixed += fixed
+ total_files += 1
+ elif not args.quiet:
+ print(" 无需修复")
+
+ print(f"\n{'=' * 50}")
+ if args.dry_run:
+ print(f"[预览] 将修复 {total_fixed} 张图片 (共 {total_files} 个文件)")
+ else:
+ print(f"[完成] 已修复 {total_fixed} 张图片 (共 {total_files} 个文件)")
+
+
+if __name__ == '__main__':
+ main()