Python Pillow Image to PDF,然后合并内存问题



目标: 将有限数量的文件转换为.jpg格式并将它们合并为一个PDF文件。

预期成果: 文件夹中的文件已成功转换并合并为指定位置的一个pdf文件。

问题: 当文件大小超过一定数量时,在我的测试中,它大约是 400 mb,程序崩溃并显示以下消息:


Traceback (most recent call last):
File "C:UserskaczkAppDataLocalProgramsPythonPython38-32libsite-packagesPILImageFile.py", line 498, in _save
fh = fp.fileno()
io.UnsupportedOperation: fileno
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "MakePDF.py", line 10, in <module>
im1.save(pdf1_filename, "PDF" ,resolution=1000.0, save_all=True, append_images=imageList)
File "C:UserskaczkAppDataLocalProgramsPythonPython38-32libsite-packagesPILImage.py", line 2084, in save
save_handler(self, fp, filename)
File "C:UserskaczkAppDataLocalProgramsPythonPython38-32libsite-packagesPILPdfImagePlugin.py", line 46, in _save_all
_save(im, fp, filename, save_all=True)
File "C:UserskaczkAppDataLocalProgramsPythonPython38-32libsite-packagesPILPdfImagePlugin.py", line 175, in _save
Image.SAVE["JPEG"](im, op, filename)
File "C:UserskaczkAppDataLocalProgramsPythonPython38-32libsite-packagesPILJpegImagePlugin.py", line 770, in _save
ImageFile._save(im, fp, [("jpeg", (0, 0) + im.size, 0, rawmode)], bufsize)
File "C:UserskaczkAppDataLocalProgramsPythonPython38-32libsite-packagesPILImageFile.py", line 513, in _save
fp.write(d)
MemoryError

使用任务管理器运行程序后,我注意到执行该程序时计算机确实耗尽了 ram 内存。下面是使用的代码。

import os
from PIL import Image
fileList = os.listdir(r'C:locationofphotosfolder')
imageList = []
im1 = Image.open(os.path.join(r'C:locationofphotosfolder',fileList[0]))
for file in fileList[1:]:
imageList.append(Image.open(os.path.join(r'C:locationofphotosfolder',file)))
pdf1_filename =  r'C:locationofpdfdestination.pdf'
im1.save(pdf1_filename, "PDF" ,resolution=500.0, save_all=True, append_images=imageList)

关于内存使用,我在这里犯了一个容易的错误吗?是否有不同的模块可以在处理更多更大的文件时使任务更容易?我将非常感谢所有的帮助。

这个问题已经很老了,但是自从我到达那里与相同的问题作斗争以来,这里有一个答案。

您只需在使用图像后关闭它们:

im1.close()
for i in imageList:
i.close()

这为我解决了这个问题。

PS:看看glob,它大大简化了使用路径的工作。

最新更新