Python 使用 img2pdf 转换失败,请问我的代码是哪里出错了?
问题描述
如果图片的目录只有一层,就可以正常合成PDF,如果嵌套了多层就会抛异常,但是不知道怎么优化解决,下面代码直接运行是可以的,注释掉的部分是有文件夹嵌套的情况下,会失败
相关代码
import osimport 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,2Apparently 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
回答:
试试吧孩子
import osimport img2pdf
def img_to_pdf(path_name, file_format):
pdf_file = 'test.pdf'
image_path_list = [
os.path.join(parent, fn)
for parent, dirnames, filenames in os.walk(path_name)
for fn in filenames if fn.endswith(file_format)]
with open(pdf_file, 'wb') as pf:
pf.write(img2pdf.convert(image_path_list))
print('处理完成,请检查文件“test.pdf”')
if __name__ == '__main__':
img_to_pdf(r"C:\Users\Psheng\Desktop\新建文件夹", "jpg")
别问我为什么用列表推导式,因为我的老师告诉我,列表推导式比较能装X(手动滑稽)
以上是 Python 使用 img2pdf 转换失败,请问我的代码是哪里出错了? 的全部内容, 来源链接: utcz.com/a/158547.html