You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python从.RTF文件提取图片?现有相关方案已失效

从RTF文件提取图片的可行方法

一、桌面工具快速提取(无需编程)

  • LibreOffice Writer:直接打开RTF文件,右键目标图片选择「保存」,可导出为PNG/JPG等格式。如果需要批量处理,可使用命令行模式:
    libreoffice --headless --convert-to png your_file.rtf
    
    注:命令行模式会将整个文档转为图片,若只需特定图片,手动打开保存更精准。
  • 轻量RTF编辑器:比如RTF Viewer类工具,打开文件后通常支持单独选中图片并导出,操作逻辑和普通文档编辑器一致。

二、手动提取(应急场景适用)

RTF本质是文本格式,图片多以Base64编码或二进制块存储:

  1. 用Notepad++等文本编辑器打开RTF文件
  2. 搜索关键词\pict定位图片块起始位置
  3. 根据\pngblip(PNG)、\jpegblip(JPG)等标记,提取对应编码内容(剔除RTF控制字符)
  4. 将提取的编码解码后保存为对应格式文件,比如Base64内容转二进制后存为.png

三、编程实现(基于当前可用库)

  • Python(Windows环境):借助Word COM接口+python-docx
    先将RTF转为DOCX,再提取图片:
    import win32com.client
    from docx import Document
    
    # RTF转DOCX
    word = win32com.client.Dispatch("Word.Application")
    doc = word.Documents.Open("your_file.rtf")
    doc.SaveAs("temp.docx", FileFormat=16)  # 16对应DOCX格式
    doc.Close()
    word.Quit()
    
    # 从DOCX提取图片
    doc = Document("temp.docx")
    for idx, rel in enumerate(doc.part.rels.values()):
        if "image" in rel.target_ref:
            img_data = rel.target_part.blob
            with open(f"extracted_img_{idx}.png", "wb") as f:
                f.write(img_data)
    
  • Python:rtfparse(维护中库)
    直接解析RTF结构提取图片:
    from rtfparse import RTFParser
    
    parser = RTFParser()
    doc = parser.parse("your_file.rtf")
    for img in doc.images:
        with open(f"img_{img.id}.{img.format}", "wb") as f:
            f.write(img.data)
    
    注:安装前执行pip install rtfparse --upgrade确保使用最新版本

内容的提问来源于stack exchange,提问作者Pancake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 18:01:17