|
| 1 | +import os |
| 2 | +import re |
| 3 | +from pathlib import Path |
| 4 | +from PIL import Image |
| 5 | +import argparse |
| 6 | + |
| 7 | +def convert_image_to_webp(input_path, output_path): |
| 8 | + """ |
| 9 | + 将图片转换为WebP格式(无损压缩) |
| 10 | + """ |
| 11 | + try: |
| 12 | + with Image.open(input_path) as img: |
| 13 | + # 如果是PNG且有透明通道,保持RGBA模式 |
| 14 | + if img.format == 'PNG' and img.mode in ('RGBA', 'LA'): |
| 15 | + img.save(output_path, 'WEBP', lossless=True, quality=100) |
| 16 | + else: |
| 17 | + # 转换为RGB模式(适用于JPG等格式) |
| 18 | + if img.mode != 'RGB': |
| 19 | + img = img.convert('RGB') |
| 20 | + img.save(output_path, 'WEBP', lossless=True, quality=100) |
| 21 | + return True |
| 22 | + except Exception as e: |
| 23 | + print(f"转换失败 {input_path}: {e}") |
| 24 | + return False |
| 25 | + |
| 26 | +def scan_and_convert_images(folder_path, keep_original=False): |
| 27 | + """ |
| 28 | + 扫描img文件夹并转换图片 |
| 29 | + """ |
| 30 | + img_folder = Path(folder_path) / 'img' |
| 31 | + if not img_folder.exists(): |
| 32 | + print(f"未找到img文件夹: {img_folder}") |
| 33 | + return [] |
| 34 | + |
| 35 | + converted_files = [] |
| 36 | + supported_formats = {'.png', '.jpg', '.jpeg'} |
| 37 | + |
| 38 | + for img_file in img_folder.iterdir(): |
| 39 | + if img_file.suffix.lower() in supported_formats: |
| 40 | + webp_file = img_file.with_suffix('.webp') |
| 41 | + |
| 42 | + print(f"正在转换: {img_file.name} -> {webp_file.name}") |
| 43 | + |
| 44 | + if convert_image_to_webp(img_file, webp_file): |
| 45 | + converted_files.append({ |
| 46 | + 'original': img_file.name, |
| 47 | + 'converted': webp_file.name, |
| 48 | + 'original_suffix': img_file.suffix.lower() |
| 49 | + }) |
| 50 | + # 根据选项决定是否删除原文件 |
| 51 | + if not keep_original: |
| 52 | + try: |
| 53 | + img_file.unlink() |
| 54 | + print(f"已删除原文件: {img_file.name}") |
| 55 | + except Exception as e: |
| 56 | + print(f"删除原文件失败 {img_file.name}: {e}") |
| 57 | + else: |
| 58 | + print(f"已保留原文件: {img_file.name}") |
| 59 | + |
| 60 | + return converted_files |
| 61 | + |
| 62 | +def update_markdown_references(folder_path, converted_files): |
| 63 | + """ |
| 64 | + 更新Markdown文件中的图片引用 |
| 65 | + """ |
| 66 | + folder = Path(folder_path) |
| 67 | + md_files = list(folder.glob('*.md')) |
| 68 | + |
| 69 | + if not md_files: |
| 70 | + print("未找到Markdown文件") |
| 71 | + return |
| 72 | + |
| 73 | + # 创建替换映射 |
| 74 | + replacement_map = {} |
| 75 | + for file_info in converted_files: |
| 76 | + original_name = file_info['original'] |
| 77 | + converted_name = file_info['converted'] |
| 78 | + # 移除扩展名的原始名称 |
| 79 | + base_name = Path(original_name).stem |
| 80 | + original_suffix = file_info['original_suffix'] |
| 81 | + |
| 82 | + # 创建多种可能的引用模式 |
| 83 | + patterns = [ |
| 84 | + f"img/{original_name}", |
| 85 | + f"./img/{original_name}", |
| 86 | + f"img/{base_name}{original_suffix}", |
| 87 | + f"./img/{base_name}{original_suffix}" |
| 88 | + ] |
| 89 | + |
| 90 | + for pattern in patterns: |
| 91 | + replacement_map[pattern] = f"img/{converted_name}" |
| 92 | + |
| 93 | + # 更新每个Markdown文件 |
| 94 | + for md_file in md_files: |
| 95 | + try: |
| 96 | + with open(md_file, 'r', encoding='utf-8') as f: |
| 97 | + content = f.read() |
| 98 | + |
| 99 | + original_content = content |
| 100 | + updated = False |
| 101 | + |
| 102 | + # 替换图片引用 |
| 103 | + for old_ref, new_ref in replacement_map.items(): |
| 104 | + # 匹配Markdown图片语法:  和 <img src="path"> |
| 105 | + patterns = [ |
| 106 | + (rf'(\!\[[^\]]*\]\()\s*{re.escape(old_ref)}\s*(\))', rf'\1{new_ref}\2'), |
| 107 | + (rf'(<img[^>]+src=["\'\'"])\s*{re.escape(old_ref)}\s*(["\'\'"][^>]*>)', rf'\1{new_ref}\2') |
| 108 | + ] |
| 109 | + |
| 110 | + for pattern, replacement in patterns: |
| 111 | + if re.search(pattern, content): |
| 112 | + content = re.sub(pattern, replacement, content) |
| 113 | + updated = True |
| 114 | + |
| 115 | + # 如果有更新,写回文件 |
| 116 | + if updated: |
| 117 | + with open(md_file, 'w', encoding='utf-8') as f: |
| 118 | + f.write(content) |
| 119 | + print(f"已更新Markdown文件: {md_file.name}") |
| 120 | + |
| 121 | + except Exception as e: |
| 122 | + print(f"更新Markdown文件失败 {md_file}: {e}") |
| 123 | + |
| 124 | +def main(): |
| 125 | + parser = argparse.ArgumentParser(description='将PNG/JPG图片转换为WebP格式并更新Markdown引用') |
| 126 | + parser.add_argument('--folder', required=True, help='包含img文件夹和Markdown文件的目标文件夹路径') |
| 127 | + parser.add_argument('--keep-original', action='store_true', help='保留原始图片文件,不删除') |
| 128 | + |
| 129 | + args = parser.parse_args() |
| 130 | + folder_path = Path(args.folder) |
| 131 | + |
| 132 | + if not folder_path.exists(): |
| 133 | + print(f"错误: 文件夹不存在 - {folder_path}") |
| 134 | + return |
| 135 | + |
| 136 | + if not folder_path.is_dir(): |
| 137 | + print(f"错误: 路径不是文件夹 - {folder_path}") |
| 138 | + return |
| 139 | + |
| 140 | + print(f"开始处理文件夹: {folder_path}") |
| 141 | + print("=" * 50) |
| 142 | + |
| 143 | + # 步骤1: 转换图片 |
| 144 | + print("1. 扫描并转换图片...") |
| 145 | + converted_files = scan_and_convert_images(folder_path, args.keep_original) |
| 146 | + |
| 147 | + if not converted_files: |
| 148 | + print("未找到需要转换的图片文件") |
| 149 | + return |
| 150 | + |
| 151 | + print(f"\n成功转换 {len(converted_files)} 个文件:") |
| 152 | + for file_info in converted_files: |
| 153 | + print(f" {file_info['original']} -> {file_info['converted']}") |
| 154 | + |
| 155 | + # 步骤2: 更新Markdown文件 |
| 156 | + print("\n2. 更新Markdown文件中的图片引用...") |
| 157 | + update_markdown_references(folder_path, converted_files) |
| 158 | + |
| 159 | + print("\n" + "=" * 50) |
| 160 | + print("转换完成!") |
| 161 | + |
| 162 | +if __name__ == "__main__": |
| 163 | + main() |
0 commit comments