Python 使用 img2pdf 转换失败,请问我的代码是哪里出错了?
问题描述
如果图片的目录只有一层,就可以正常合成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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试吧孩子
别问我为什么用列表推导式,因为我的老师告诉我,列表推导式比较能装X(手动滑稽)