UnrecognizedImageError - 图片插入错误 - python-docx

San*_*mon 3 python image-uploading python-docx

我正在尝试将一个 wmf 文件插入到 docx 中,使用python-docx它产生以下回溯。

Traceback (most recent call last):
  File "C:/Users/ADMIN/PycharmProjects/ppt-to-word/ppt_reader.py", line 79, in <module>
    read_ppt(path, file)
  File "C:/Users/ADMIN/PycharmProjects/ppt-to-word/ppt_reader.py", line 73, in read_ppt
    write_docx(ppt_data, False)
  File "C:/Users/ADMIN/PycharmProjects/ppt-to-word/ppt_reader.py", line 31, in write_docx
    document.add_picture(slide_data.get('picture_location'), width=Inches(5.0))
  File "C:\Python34\lib\site-packages\docx\document.py", line 72, in add_picture
    return run.add_picture(image_path_or_stream, width, height)
  File "C:\Python34\lib\site-packages\docx\text\run.py", line 62, in add_picture
    inline = self.part.new_pic_inline(image_path_or_stream, width, height)
  File "C:\Python34\lib\site-packages\docx\parts\story.py", line 56, in new_pic_inline
    rId, image = self.get_or_add_image(image_descriptor)
  File "C:\Python34\lib\site-packages\docx\parts\story.py", line 29, in get_or_add_image
    image_part = self._package.get_or_add_image_part(image_descriptor)
  File "C:\Python34\lib\site-packages\docx\package.py", line 31, in get_or_add_image_part
    return self.image_parts.get_or_add_image_part(image_descriptor)
  File "C:\Python34\lib\site-packages\docx\package.py", line 74, in get_or_add_image_part
    image = Image.from_file(image_descriptor)
  File "C:\Python34\lib\site-packages\docx\image\image.py", line 55, in from_file
    return cls._from_stream(stream, blob, filename)
  File "C:\Python34\lib\site-packages\docx\image\image.py", line 176, in _from_stream
    image_header = _ImageHeaderFactory(stream)
  File "C:\Python34\lib\site-packages\docx\image\image.py", line 199, in _ImageHeaderFactory
    raise UnrecognizedImageError
docx.image.exceptions.UnrecognizedImageError
Run Code Online (Sandbox Code Playgroud)

图像文件是.wmf格式。

任何帮助或建议表示赞赏。

sca*_*nny 6

python-docx通过“识别”其独特的标题来识别图像文件的类型。通过这种方式,它可以区分 JPEG 与 PNG、TIFF 等。这比映射文件扩展名可靠得多,也比要求用户告诉您类型更方便。这是一种很常见的方法。

此错误表示python-docx未找到它识别的标头。Windows 元文件格式 (WMF) 以这种方式可能会很棘手,专有规范和现场文件样本的变化有很大的余地。

要解决此问题,我建议您使用可以识别它的内容读取文件(我将从 Pillow 开始)并将其“转换”为相同或其他格式,希望在此过程中更正标题。

首先,我会尝试阅读它并将其另存为 WMF(或者 EMF,如果这是一个选项)。这可能足以解决问题。如果您必须更改为中间格式然后返回,那可能会造成损失,但可能总比没有好。

ImageMagick 可能是另一个不错的选择,因为它可能比 Pillow 具有更好的覆盖范围。