2

我遇到了imagickphp 库的问题。

我正在我的文件系统中进行递归搜索并查找任何pdf文件。

    $it = new RecursiveDirectoryIterator("/test/project");
    $display = Array ('pdf');
    foreach(new RecursiveIteratorIterator($it) as $file){
        if (in_array(strtolower(array_pop(explode('.', $file))), $display))
        {
            if(file_exists($file)){
                echo $file;     //this would echo /test/project/test1.pdf
                $im = new Imagick($file);
                $im->setImageFormat("jpg");

                file_put_contents('test.txt', $im);
            }
        }
    }

但是,我收到一条错误消息

Fatal error:  Uncaught exception 'ImagickException' with message 'Can not process empty Imagick object' in /test.php:57
Stack trace:
#0 /test.php(57): Imagick->setimageformat('jpg')
#1 {main}
  thrown in /test.php on line 57

line 57 is  $im->setImageFormat("jpg");

但是,如果我用错误代替我$im = new Imagick($file)$im = new Imagick('/test/project/test1.pdf'),错误就消失了。

我不知道为什么会这样。有人可以给我这个问题的提示吗?非常感谢

4

3 回答 3

3

据此文件的.jpg格式为JPEG.

注1

你的$file变量是一个对象SplFileInfo,但你总是像字符串一样使用它。在 的构造函数中使用RecursiveDirectoryIterator::CURRENT_AS_PATHNAME标志RecursiveDirectoryIterator,成为一个真正的字符串。

注2

RegexIterator您可以使用, f.ex.:过滤迭代器条目new RegexIterator($recursiveIteratorIterator, '/\.pdf$/'):(在注 1之后)。或者,您也可以GlobIterator用于仅搜索 pdf 文件。

于 2013-04-18T19:18:38.257 回答
1

正如@pozs 指出的

注意 1:您的 $file 变量是一个对象 SplFileInfo,但您始终像使用字符串一样使用它。

这是一个代码片段,它可以将文件名作为字符串获取,并具有获取文件扩展名的优化方法:

<?php
    $display           = array ('pdf');
    $directoryIterator = new RecursiveDirectoryIterator('./test/project');

    // The key of the iterator is a string with the filename 
    foreach (new RecursiveIteratorIterator($directoryIterator) as $fileName => $file) {

        // Optimized method to get the file extension
        $fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);

        if (in_array(strtolower($fileExtension), $display)) {
            if(file_exists($fileName)){
                echo "{$fileName}\n";

                // Just do what you want with Imagick here
            }
        }
于 2013-04-18T19:34:03.883 回答
0

也许尝试这种方法:PDF to JPG conversion using PHP

$fp_pdf = fopen($pdf, 'rb');

$img = new imagick();
$img->readImageFile($fp_pdf);

从阅读其他帖子看来,GhostScript 更快?

于 2013-04-18T19:15:55.443 回答