首页 > 解决方案 > Python Pillow Image 转 PDF 然后合并内存问题

问题描述

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

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

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



Traceback (most recent call last):
  File "C:\Users\kaczk\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\ImageFile.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:\Users\kaczk\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\Image.py", line 2084, in save
    save_handler(self, fp, filename)
  File "C:\Users\kaczk\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\PdfImagePlugin.py", line 46, in _save_all
    _save(im, fp, filename, save_all=True)
  File "C:\Users\kaczk\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\PdfImagePlugin.py", line 175, in _save
    Image.SAVE["JPEG"](im, op, filename)
  File "C:\Users\kaczk\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\JpegImagePlugin.py", line 770, in _save
    ImageFile._save(im, fp, [("jpeg", (0, 0) + im.size, 0, rawmode)], bufsize)
  File "C:\Users\kaczk\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\ImageFile.py", line 513, in _save
    fp.write(d)
MemoryError

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

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

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

标签: pythonpdf-generationpython-imaging-library

解决方案


这个问题已经很老了,但是自从我到了那里就遇到了同样的问题,这里有一个答案。

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

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

这为我解决了。

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


推荐阅读