gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:26:40 26 4
gpt4 key购买 nike

我想将多页 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

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

旧答案:

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

关于python - 如何将多页 PDF 转换为 Python 中的图像对象列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43064124/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com