Skip to main content
 首页 » 编程设计

python之获取通过 Wand 转换的结果文件列表

2025年05月04日7emanlee

Imagemagick是用于显示、转换和编辑光栅图像文件的开源软件套件。 Wand是 ctypes用于 Python 的基于 ImageMagick 的绑定(bind)。

我如何获得图像文件列表,这是我使用 Wand 得到的结果?

例如,有一个 2 页的 PDF 文件 file.pdf,我将其转换为 2 个 JPEG 文件 file-0.jpg 和 file-1 .jpg。我如何获取列表 ['file-0.jpg', 'file-1.jpg']?

目前我只是使用glob:

with Image(filename='file.pdf') as original: 
    with original.clone() as converted: 
        converted.format = 'jpeg' 
        converted.save(filename='file.jpg') 
images = glob('*.jpg') 

但也许有一种更惯用的方式通过 Wand 库本身。

请您参考如下方法:

您可以使用 Image.sequence .每个序列项都有 index .

from wand.image import Image 
 
with Image(filename='file.pdf') as img: 
    img.save(filename='file.jpg') 
    if len(img.sequence) > 1: 
        images = ['file-{0.index}.jpg'.format(x) for x in img.sequence] 
    else: 
        images = ['file.jpg']