我的应用程序工作了几次,然后在每个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脚本,它会再次运行几次。
答案 0 :(得分:2)
错误是由系统耗尽资源引起的。 Wand调用ImageMagick库;反过来,它将解码工作传递给Ghostscript代表。 Ghostscript非常稳定,但确实使用了大量资源,并且在并行运行时感到不快(我的意见)。
任何帮助?
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)
答案 1 :(得分:0)
似乎我创建了一个新图像并没有销毁它。这填补了记忆。
我只需使用with new Image(...) as img
代替img = new Image(...)
。