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

如何在Python中转换EMF/WMF格式图片为PNG/JPG?

解决Python中EMF/WMF格式图片转换的可行方案

方案1:通过LibreOffice命令行工具(跨平台、免费稳定)

LibreOffice原生支持EMF/WMF格式解析,可通过Python调用其命令行完成格式转换,无需依赖付费API或废弃库。

  • 操作步骤:
    1. 安装LibreOffice(对应系统版本,确保添加到系统PATH)
    2. 使用Python的subprocess模块调用转换命令

示例代码:

import subprocess
import os

def convert_emf_to_png(input_emf_path, output_dir):
    os.makedirs(output_dir, exist_ok=True)
    # 调用LibreOffice无头模式执行转换
    result = subprocess.run(
        [
            "soffice",
            "--headless",
            "--convert-to", "png",
            input_emf_path,
            "--outdir", output_dir
        ],
        capture_output=True,
        text=True
    )
    if result.returncode != 0:
        print(f"转换失败:{result.stderr}")
    else:
        print(f"转换成功,文件已保存到 {output_dir}")

# 调用示例
convert_emf_to_png("test.emf", "output_images")

方案2:Windows平台专属——使用Win32 COM接口(系统原生支持)

Windows系统通过GDI+内置EMF/WMF解析能力,可借助pywin32库调用Word完成转换,无需额外安装软件。

  • 操作步骤:
    1. 安装依赖:pip install pywin32
    2. 调用Word的COM接口插入EMF并导出为图片

示例代码:

import win32com.client as win32
import os

def emf_to_png_win32(input_emf, output_png):
    word = win32.gencache.EnsureDispatch('Word.Application')
    word.Visible = False
    doc = word.Documents.Add()
    
    # 插入EMF图片并保持原尺寸
    shape = doc.Shapes.AddPicture(
        input_emf,
        LinkToFile=False,
        SaveWithDocument=True,
        Left=0, Top=0, Width=-1, Height=-1
    )
    
    # 导出为PNG(Filter=17对应PNG格式)
    shape.Export(output_png, Filter=17)
    
    # 清理资源
    doc.Close(SaveChanges=False)
    word.Quit()

# 调用示例
emf_to_png_win32("test.emf", "output.png")

方案3:修复ImageMagick的Delegate依赖(可选)

如果坚持使用Wand库,需先解决EMF解码Delegate缺失问题:

  • Windows:安装完整版本的ImageMagick,勾选所有Delegate组件,同时确保系统已安装Ghostscript
  • Linux:通过包管理器安装libmagickcore-6.q16-6-extra(或对应版本的额外Delegate包)
  • 验证:运行identify -list format | grep EMF,若能看到EMF格式支持,再重新测试Wand代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 15:43:31