【问题标题】:Using wand to convert image to pdf fails after a few successful results在一些成功的结果后,使用 wand 将图像转换为 pdf 失败
【发布时间】:2018-07-13 09:30:19
【问题描述】:

我的应用程序运行了几次,然后在每个 pdf 上都出现错误。这是我收到的错误:

Exception TypeError: TypeError("object of type 'NoneType' has no len()",) in <bound method Image.__del__ of <wand.image.Image: (empty)>> ignored

这是我使用的功能:

def read_pdf(file):
    pre, ext = os.path.splitext(file)
    filename = pre + '.png'

    with Image(filename=file, resolution=200) as pdf:
        amount_of_pages = len(pdf.sequence)

        image = Image(
            width=pdf.width,
            height=pdf.height * amount_of_pages
        )

        for i in range(0, amount_of_pages):
            image.composite(
                pdf.sequence[i],
                top=pdf.height * i,
                left=0
            )

        image.compression_quality = 100
        image.save(filename=filename)
        logging.info('Opened and saved pdf to image: \'' + file + '\'.')
        return filename

此函数将正确地将 pdf 转换为图像,但在两三次之后,它每次都会崩溃并抛出该异常。如果我重新启动 python 脚本,它会再次运行几次。

【问题讨论】:

    标签: python pdf wand


    【解决方案1】:

    该错误是由于系统资源不足引起的。 Wand 调用 ImageMagick 库;反过来,它将解码工作传递给 Ghostscript 委托。 Ghostscript 非常稳定,但确实会占用大量资源,并且在并行运行时并不满意(我的意见)。

    有什么帮助吗?

    • 尝试构建一个允许在 PDF 转换之间彻底关闭的解决方案。像队列工作者,或 脚本。最小的资源泄漏很快就会失控。
    • 避免调用wand.image.Image.sequance。报告了一些已知的内存泄漏问题。尽管许多问题已得到修复,但 PDF 任务似乎仍然存在问题。

    从发布的代码来看,您似乎只是用给定 PDF 的所有页面创建了一个高大的图像。我建议直接移植MagickAppendImages。

    import ctypes
    from wand.image import Image
    from wand.api import library
    
    # Map C-API to python
    library.MagickAppendImages.argtypes = (ctypes.c_void_p, ctypes.c_bool)
    library.MagickAppendImages.restype = ctypes.c_void_p
    
    with Image(filename='source.pdf') as pdf:
        # Reset image stack
        library.MagickResetIterator(pdf.wand)
        # Append all pages into one new image
        new_ptr = library.MagickAppendImages(pdf.wand, True)
        library.MagickWriteImage(new_ptr, b'output.png')
        library.DestroyMagickWand(new_ptr)
    

    【讨论】:

    • 更新了示例代码。 convert source.pdf -append output.png 是否成功完成而没有任何警告?
    • 这对我有用,虽然只是调用 sequence[0].destroy() 工作而不调用底层 ImageMagick 库。上周一直在尝试调试它。
    【解决方案2】:

    似乎我创建了一个新图像并没有破坏它。这填满了内存。

    我只需要使用with new Image(...) as img 而不是img = new Image(...)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 2020-06-29
      • 2015-05-07
      相关资源
      最近更新 更多