我的应用程序工作几次,然后在每个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脚本,它将再次工作几次。
该错误是由系统用尽的资源引起的。魔杖称为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)
看来我创建了一个新图像,没有破坏它。这填补了记忆。
我只需要使用with new Image(...) as img
而不是img = new Image(...)
。