1

我想通过 PHP 将下载的 pdf 文件转换为图像。为此,我使用了 PHP 的 Imagemagick 扩展。问题是,如果我通过 file_get_contents 函数下载 pdf 文件,我无法使用下载的内容创建 Imagemagic 对象。这是代码:

<?php

$url = "pdf webaddress";
$pdfData = file_get_contents($url);

try
    {

        $img = new Imagick($pdfData);
        $img->setResolution(480,640);
        $img->setImageFormat("jpeg");
        $img->writeImage("test.jpeg");  

    }
catch(Exception $e)
{
    echo $e->getMessage();
}
?>

我收到以下错误:

无法读取文件:%PDF-1.6 %גדֿ׃ 7 0 obj <> endobj 86 0 obj <>/Filter/FlateDecode/ID[]/Index[7 146]/Info 6 0 R/Length 257/Prev 592751/ Root 8 0 R/Size 153/Type/XRef/W[1 3 1]>>stream h�bbd `bׁ'6 '9D עƒH

现在,如果我读入本地存储的 pdf 文件,一切正常。代码是:

 $image = "output.png";
 $img = new Imagick("path to pdf file");
 $img->setResolution(480,640);
 $img->setImageFormat("jpeg");
 $img->writeImage("test.jpeg"); 

任何建议,帮助表示赞赏。

4

1 回答 1

3

ImageMagick PHP 扩展文档页面Imagick构造函数需要一个文件名参数,它可以是本地文件URL。:

路径可以包含文件名的通配符,也可以是 URL。

你应该直接传递 URL,没有file_get_contents,PHP 文件流非常强大。

您的另一个解决方案是将文件存储在本地(请参阅tempnam()file_put_contents),但如果您不将其用于任何其他目的,而不是将其转换为图像,那将毫无用处:

$pdfUrl = "...";
$tmpFileName = tempnam(sys_get_temp_dir(), "pdf");
file_put_contents($tmpFileName, file_get_contents($pdfUrl));
// Do your ImageMagick job
unlink($tmpFileName);
于 2012-06-22T15:43:37.763 回答