我正在尝试使用tiff
和PDF
将Pillow
文件转换为PyPDF
。我能够使用早期版本的Pillow
来使用它,虽然我不能使用哪个版本。
我最近升级到Pillow 3.1.0
,现在我遇到了问题。这是以前正在运行的代码。
import os
import traceback
from PIL import Image
from PyPDF2 import PdfFileReader, PdfFileMerger
to_merge = []
with Image.open('my_tif.tif') as img:
seeker = 0
while True:
try:
# temp file name for PDF
img_pdf = 'temp_{}.pdf'.format(seeker)
#seeks to next image with TIFF
img.seek(seeker)
# saves the image as a PDF
img.save(img_pdf)
seeker += 1
to_merge.append(img_pdf)
except Exception as err:
traceback.print_exc()
break
merger = PdfFileMerger()
for f in to_merge:
merger.append(PdfFileReader(f))
os.remove(f)
merger.write('merged.pdf')
事先,它为tiff
中的每个图像生成了一个PDF,然后将PDF合并在一起没有问题。
升级到Pillow 3.1.0
后,它会遍历所有图片,但会在最终图片上抛出ValueError
。
Traceback (most recent call last):
File "C:/Code/Python/tiff_to_pdf.py", line 16, in <module>
img.save(img_pdf)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1675, in save
save_handler(self, fp, filename)
File "C:\Python27\lib\site-packages\PIL\PdfImagePlugin.py", line 155, in _save
im.seek(pageNumber)
File "C:\Python27\lib\site-packages\PIL\TiffImagePlugin.py", line 930, in seek
self._seek(max(frame, 0)) # Questionable backwards compatibility.
File "C:\Python27\lib\site-packages\PIL\TiffImagePlugin.py", line 956, in _seek
self.fp.seek(self._frame_pos[frame])
ValueError: I/O operation on closed file
ValueError
的原因是什么?
答案 0 :(得分:0)
前一段时间我遇到了同样的问题。我找到的唯一解决方案是将文件作为文件对象打开,并在每次迭代时将其传递给Image.Open:
with open('my_tif.tif', 'rb') as f:
seeker = 0
while True:
try:
img = Image.open(f)
# temp file name for PDF
img_pdf = 'temp_{}.pdf'.format(seeker)
#seeks to next image with TIFF
img.seek(seeker)
# saves the image as a PDF
img.save(img_pdf)
seeker += 1
to_merge.append(img_pdf)
except Exception as err:
traceback.print_exc()
break
答案 1 :(得分:0)
我在 Pillow 5.4.1 中也出现了这个问题,降级到 5.0.0 已解决。
File "/home1/irteam/miniconda3/lib/python3.6/site-packages/tornado/web.py", line 1592, in _execute
result = yield result
File "/home1/irteam/miniconda3/lib/python3.6/site-packages/tornado/gen.py", line 1133, in run
value = future.result()
File "/home1/irteam/miniconda3/lib/python3.6/site-packages/tornado/gen.py", line 1141, in run
yielded = self.gen.throw(*exc_info)
File "/home1/irteam/deploy/oneapp-clover/doc_base/clover/profilehandler.py", line 73, in get
image, tmp_error_code = yield loadUserImage(user_no, hash_id, headers)
File "/home1/irteam/miniconda3/lib/python3.6/site-packages/tornado/gen.py", line 1133, in run
value = future.result()
File "/home1/irteam/miniconda3/lib/python3.6/site-packages/tornado/gen.py", line 1147, in run
yielded = self.gen.send(value)
File "/home1/irteam/deploy/oneapp-clover/doc_base/clover/merge_profile.py", line 273, in loadUserImage
setCache(user_cache_key, image_file.getvalue())
ValueError: I/O operation on closed file.