繁体   English   中英

如何将多页 PDF 转换为 Python 中的图像对象列表?

[英]How to convert multipage PDF to list of image objects in Python?

我想将多页 PDF 文档转换为列表结构中的一系列图像对象,而无需在 Python 中将图像保存在磁盘中(我想用 PIL Image 处理它们)。 到目前为止,我只能先将图像写入文件:

from wand.image import Image

with Image(filename='source.pdf') as img:

    with img.convert('png') as converted:
        converted.save(filename='pyout/page.png')

但是如何将上面的 img 对象直接转换为 PIL.Image 对象列表?

新答案:

pip 安装 pdf2image

from pdf2image import convert_from_path, convert_from_bytes
images = convert_from_path('/path/to/my.pdf')

您可能还需要安装枕头。 这可能只适用于 linux。

https://github.com/Belval/pdf2image

两种方法的结果可能不同。

旧答案:

蟒蛇 3.4:

from PIL import Image
from wand.image import Image as wimage
import os
import io

if __name__ == "__main__":
    filepath = "fill this in"
    assert os.path.exists(filepath)
    page_images = []
    with wimage(filename=filepath, resolution=200) as img:
        for page_wand_image_seq in img.sequence:
            page_wand_image = wimage(page_wand_image_seq)
            page_jpeg_bytes = page_wand_image.make_blob(format="jpeg")
            page_jpeg_data = io.BytesIO(page_jpeg_bytes)
            page_image = Image.open(page_jpeg_data)
            page_images.append(page_image)

最后,您可以对 mogrify 进行系统调用,但这可能会更复杂,因为您需要管理临时文件。

简单的方法是使用PIL保存图像文件并在读取它们后删除它们。

我建议使用 pdf2image 包。 在使用 pdf2image 包之前,您可能需要通过 anaconda 安装 poppler 包

conda install -c conda-forge poppler

如果卡住了,请在安装前更新 conda:

conda update conda
conda update anaconda

安装 poppler 后,通过 pip 安装 pdf2image :

pip install pdf2image

然后运行此代码:

from pdf2image import convert_from_path
dpi = 500 # dots per inch
pdf_file = 'work.pdf'
pages = convert_from_path(pdf_file ,dpi )
for i in range(len(pages)):
   page = pages[i]
   page.save('output_{}.jpg'.format(i), 'JPEG')

之后,请使用 PIL 阅读它们并删除它们。

我用魔杖回答如下:

from wand.image import Image as wi
...
Data = filedialog.askopenfilename(initialdir="/", title="Choose File", filetypes = (("Portable Document Format","*.pdf"),("All Files", "*.*")))
apps.append(Data)
print(Data)
PDFfile = wi(filename = Data, resolution = 300)
Images = PDFfile.convert('tiff')
ImageSequence = 1
for img in PDFfile.sequence:
    image = wi(image = img)
    image.save(filename = "Document_300"+"_"+str(ImageSequence)+".tiff")
    ImageSequence += 1

希望这会帮助你。

我已经使用 GUI 实现了它,您可以在其中简单地选择您的文件。

您还可以更改 jpg 等格式的 PDFfile.convert()。

从这里https://blog.alivate.com.au/poppler-windows/下载 Poppler,然后使用以下代码:

from pdf2image import convert_from_path

file_name = 'A019'
images = convert_from_path(r'D:\{}.pdf'.format(file_name), poppler_path=r'C:\poppler-0.68.0\bin')

for i, im in enumerate(images):
    im.save(r'D:\{}-{}.jpg'.format(file_name,i))

如果因为poppler的路径报错,在windows环境变量的“Path”中添加poppler的bin路径。 路径可以是这样的“C:\\poppler-0.68.0\\bin”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM