求可批量搜索文件夹内RTF文档并修改图片分辨率压缩体积的脚本
RTF批量压缩内嵌图片脚本方案
以下是可直接落地的实现方案,覆盖Python跨平台和Windows Word原生两种实现路径:
方案1:Python跨平台实现
无需依赖Office软件,可在Windows/macOS/Linux环境运行
前置依赖安装
执行以下命令安装所需库:
pip install pillow pyth
完整脚本代码
import os from io import BytesIO from PIL import Image from pyth.plugins.rtf15.reader import Rtf15Reader from pyth.plugins.rtf15.writer import Rtf15Writer from pyth.document import Image as RtfImage # 可修改配置项 TARGET_FOLDER = r"替换为你的rtf文件夹路径" # 支持嵌套子目录扫描 MAX_IMAGE_SIDE = 1920 # 图片最长边像素,超过则等比缩放 IMAGE_QUALITY = 75 # 图片压缩质量 0-100,75可兼顾清晰度和压缩率 BACKUP_ORIGINAL = True # 是否自动备份原始文件,避免数据丢失 def compress_image(image_data): img = Image.open(BytesIO(image_data)) width, height = img.size # 小于尺寸上限的图片不处理 if max(width, height) <= MAX_IMAGE_SIDE: return image_data # 计算等比缩放参数 scale = MAX_IMAGE_SIDE / max(width, height) new_size = (int(width*scale), int(height*scale)) img = img.resize(new_size, Image.Resampling.LANCZOS) # 压缩输出 output = BytesIO() img.save(output, format="JPEG", quality=IMAGE_QUALITY, optimize=True) return output.getvalue() def process_single_rtf(file_path): print(f"处理中:{file_path}") # 备份原始文件 if BACKUP_ORIGINAL: bak_path = file_path + ".bak" if not os.path.exists(bak_path): with open(file_path, "rb") as src, open(bak_path, "wb") as dst: dst.write(src.read()) # 读取并处理rtf with open(file_path, "rb") as f: doc = Rtf15Reader.read(f) # 遍历替换所有内嵌图片 for para in doc.content: if hasattr(para, "content"): for elem in para.content: if isinstance(elem, RtfImage): elem.data = compress_image(elem.data) # 保存修改后的文件 with open(file_path, "wb") as f: Rtf15Writer.write(doc, f) print(f"处理完成:{file_path}") if __name__ == "__main__": for root, _, files in os.walk(TARGET_FOLDER): for file in files: if file.lower().endswith(".rtf"): process_single_rtf(os.path.join(root, file)) print("全部文件处理完成")
方案2:Windows Word VBA实现
兼容性最好,适合处理Word生成的RTF文件,无需额外安装软件
使用方法
- 打开Word,按
Alt+F11打开VBA编辑器 - 粘贴下方代码,按F5运行,选择目标文件夹即可
Sub BatchCompressRTFImages() Dim folderPath As String Dim file As String Dim doc As Document ' 选择目标文件夹 With Application.FileDialog(msoFileDialogFolderPicker) If .Show = -1 Then folderPath = .SelectedItems(1) & "\" Else Exit Sub End If End With file = Dir(folderPath & "*.rtf") Do While file <> "" Set doc = Documents.Open(FileName:=folderPath & file) ' 批量压缩所有图片 For Each shp In doc.InlineShapes If shp.Type = wdInlineShapePicture Then shp.PictureFormat.Compress _ PictureResolution:=wdWebResolution, _ ApplyToSelectedPictures:=False, _ DeleteCroppedAreas:=True End If Next doc.Save doc.Close file = Dir Loop MsgBox "所有文件处理完成" End Sub
注意事项
- 运行前建议先拿1-2个测试文件验证压缩效果,确认符合预期后再批量操作
- 如果Python脚本处理后出现RTF格式错乱问题,优先使用VBA方案,兼容性更好
- 两种方案默认都不会修改矢量图、OLE嵌入对象,仅处理位图类图片
内容的提问来源于stack exchange,提问作者PJramos
相关产品推荐
相关产品推荐

