将.TIF转换为.PDF会产生PIL:读取图像错误

时间:2019-09-12 13:04:40

标签: python-3.x type-conversion python-imaging-library

我一直在尝试批处理一些.TIF文件并将其转换为PDF。我确实可以正常运行,但是在尝试更改img2pdf以使其可以接受更大的文件后,即使重新安装后,我也无法再次运行同一程序。

当前,它抛出以下错误:

>>>>
ImageOpenError: cannot read input image (not jpeg2000). PIL: error reading image: cannot identify image file <_io.BytesIO object at 0x000001A608255EB8>

这是我一直在使用的代码。任何人有任何建议吗?预先感谢。


import img2pdf, sys, os, time
image_directory = r"PATH"

image_files = []

for root, dirs, files in os.walk(image_directory):
    for file in files:
        if file.endswith(".tif") or file.endswith(".TIF"):
             print("Discovered this TIF: ", os.path.join(root, file))
             image_files.append(os.path.join(root, file))

for image in image_files:
    output_file = image[:-4] + ".pdf"
    print ("Putting all TIFs into ", output_file)
    pdf_bytes = img2pdf.convert(image)
    file = open(output_file,"wb")
    file.write(pdf_bytes)

这是完整的追溯

Traceback (most recent call last):

  File "<ipython-input-37-fe96d5eeb049>", line 1, in <module>
    runfile('PATH', wdir='PATH')

  File "PATH", line 704, in runfile
    execfile(filename, namespace)

  File "PATH", line 108, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "PATH", line 23, in <module>
    pdf_bytes = img2pdf.convert(image_files)

  File "PATH", line 1829, in convert
    ) in read_images(rawdata, kwargs["colorspace"], kwargs["first_frame_only"]):

  File "PATH", line 1171, in read_images
    "PIL: error reading image: %s" % e

ImageOpenError: cannot read input image (not jpeg2000). PIL: error reading image: cannot identify image file <_io.BytesIO object at 0x000001A6082BE3B8>

2 个答案:

答案 0 :(得分:3)

如果按照我的理解,如果您想递归地找到所有TIFF图像并将每张TIFF图像转换为相应命名的PDF文件,则可以与 GNU Parallel ImageMagick 在终端中像这样:

find . -iname "*tif" -print0 | parallel -0 --dry-run mogrify {} {.}.pdf

示例输出

mogrify ./OpenCVTIFF64/result.tif ./OpenCVTIFF64/result.pdf
mogrify ./OpenCVTIFF64/a.tif ./OpenCVTIFF64/a.pdf
mogrify ./OpenCVBasics/a.tif ./OpenCVBasics/a.pdf
mogrify ./CImgDump/image.tif ./CImgDump/image.pdf

该命令说... ”从当前目录开始,递归查找所有TIFF文件(无论是大写,小写还是某种混合形式),并将其以空值结尾的名称传递给 GNU Parallel >。然后,它应读取每个名称并运行 ImageMagick mogrify,以将该TIFF转换为具有相同名称,但扩展名替换为PDF的文件。” < / p>

如果它满足您的要求,请删除--dry-run,然后再次进行。

答案 1 :(得分:0)

因此,即使命令本身未正确执行,但在执行pip install'Pillow> = 6.0.0'--force-reinstall后,此操作仍然有效。跑步时,我会收到一些警告,但现在可以使用了。简短的版本是,这是枕头的问题。