问题描述
如果图片的目录只有一层,就可以正常合成PDF,如果嵌套了多层就会抛异常,但是不知道怎么优化解决,下面代码直接运行是可以的,注释掉的部分是有文件夹嵌套的情况下,会失败
相关代码
import os
import img2pdf
def img_to_pdf(path_name, file_format):
pdf_file = 'test.pdf'
pn = path_name.split('')
print(pn)
pn1 = pn[1]
# pn2 = pn[2]
# pn3 = pn[3]
# pn4 = pn[4]
with open(pdf_file, 'wb') as pf:
file_list = os.listdir(path_name)
img_list = []
for pic in file_list:
if f'.{file_format}' in pic:
# pic = os.path.join(pn1, pn2, pn3, pn4, pic)
pic = os.path.join(pn1, pic)
img_list.append(pic)
print(img_list)
pf.write(img2pdf.convert(img_list))
print('处理完成,请检查文件“test.pdf”')
if __name__ == '__main__':
file_format = 'tif'
# path_name = 'F:tifMGTS_101_004172scan_image001'
path_name = 'F:test_pics'
img_to_pdf(path_name, file_format)
实际看到的错误信息又是什么?
JPEGPreDecode: Improper JPEG sampling factors 2,2
Apparently should be 1,1..
Traceback (most recent call last):
File "F:/nlc_010.py", line 49, in <module>
img_to_pdf(path_name, file_format)
File "F:/nlc_010.py", line 41, in img_to_pdf
pf.write(img2pdf.convert(img_list))
File "C:UsersXXXvenvlibsite-packagesimg2pdf.py", line 2032, in convert
) in read_images(rawdata, kwargs["colorspace"], kwargs["first_frame_only"]):
File "C:UsersXXXvenvlibsite-packagesimg2pdf.py", line 1601, in read_images
newimg.save(pngbuffer, format="png")
File "C:zzzzzz_pythonpython_softlibsite-packagesPILImage.py", line 2068, in save
self._ensure_mutable()
File "C:zzzzzz_pythonpython_softlibsite-packagesPILImage.py", line 589, in _ensure_mutable
self._copy()
File "C:zzzzzz_pythonpython_softlibsite-packagesPILImage.py", line 582, in _copy
self.load()
File "C:zzzzzz_pythonpython_softlibsite-packagesPILTiffImagePlugin.py", line 1070, in load
return self._load_libtiff()
File "C:zzzzzz_pythonpython_softlibsite-packagesPILTiffImagePlugin.py", line 1182, in _load_libtiff
raise OSError(err)
OSError: -2
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…