如何将多页 PDF 转换为 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 对象列表呢?

原文由 Hendrik 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 450
1 个回答

新答案:

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

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

旧答案:

Python 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 进行系统调用,但这可能会更复杂,因为您需要管理临时文件。

原文由 Bryant Kou 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题