只有通过python的子进程调用ImageMagick的convert才会失败。

2024-10-08 21:20:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将pdf文件的第一页转换为缩略图JPEG文件。我的代码类似于下面的python代码。在

from tempfile import TemporaryFile, NamedTemporaryFile
import os
from subprocess import call
…
def createThumbnail(reporttempfile, thumbnailtempfile):
    # build the command for executing for extracting thumbnail
    command = "convert -resize 241x344 -background white -gravity center -extent 241x344 -quality 75" 
    csplit = command.split(' ')
    csplit.append("pdf:"+reporttempfile.name + "[0]")
    csplit.append(thumbnailtempfile.name)
    print "csplit = ", csplit
    print "cmd = %s" % " ".join(csplit)
    # run the command convert to create thumbnail
    retval = call(csplit)
    print "retval = %d" % retval
    return retval

当我调用上述函数时,我得到以下输出:

^{pr2}$

但是,当我通过在shell上输入直接调用命令时,convert成功而没有任何问题,并且我可以看到.jpg文件被正确地转换了。使用的命令是(上面的输出中也打印了):

convert -resize 241x344 -background white -gravity center -extent 241x344 -quality 75 pdf:/tmp/reportfile0001_zeEJ8B.pdf[0] /tmp/thumbnail0001_DTPHGb.jpg

我在Mac(10.9.5)和ImageMagick 6.9.0-0 Q16 x86_64 2015-04-09和Ubuntu 14(ImageMagick 6.7.7-10 2014-03-06 Q16)上都看到过这种行为。在

我不知道为什么会发生这种事。有人能帮忙吗?在

谨致问候

序号


Tags: 文件the代码fromimportconvertforpdf
1条回答
网友
1楼 · 发布于 2024-10-08 21:20:01

必须先关闭临时文件,convert读取它。您可以使用delete=False选项打开临时文件,以避免在使用close()方法关闭临时文件时将其删除。要在处理完成后手动删除它,请使用它的unlink()方法,该方法恰好与os.unlink函数相同(必须将临时文件name属性作为其第一个参数传递)。在

相关问题 更多 >

    热门问题