python - 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)
关于内存使用,我在这里犯了一个简单的错误吗?在处理更多和更大的文件时,是否有不同的模块可以使任务更容易?我将非常感谢所有帮助。
解决方案
这个问题已经很老了,但是自从我到了那里就遇到了同样的问题,这里有一个答案。
您只需在使用它们后关闭图像:
im1.close()
for i in imageList:
i.close()
这为我解决了。
PS:看一下glob
,它大大简化了路径的工作。
推荐阅读
- javascript - 如何在 js 中使用 SHIFT() 方法?
- postfix-mta - 像 mailchimp 一样在多个域上使用 Dkim
- swift - API 返回 JSON 分配给 javaScript 变量。如何读取那个 JSON?
- sql-server - 如何使用 VB.NET 中的语句从 SQL Server 数据库中获取一周列表?
- apache-spark-sql - 我在 s3 中有 .dat 文件。我需要通过 spark 读取文件并做一些过滤器并再次加载到 S3
- kubernetes - Kubernetes 上的私有 docker 注册表
- c++ - 防止 std::move 对象?
- python - 使用递归来确定一个词是否是回文
- python - 基于条件的计数器集或具有相同编号的行
- ray - Ray 中笔记本电脑/开发机器的最小集群配置文件是什么?