2013-04-18 13 views
2

我遇到一個與imagick php庫有關的問題。PHP庫對象錯誤

我正在做我的文件系統的遞歸搜索,並尋找任何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'),的錯誤消失。

我不知道爲什麼會發生這種情況。有人能給我提示這個問題嗎?非常感謝

回答

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 
      } 
     } 
+0

感謝你洙多的幫幫我! – FlyingCat

0

也許嘗試從這個辦法:PDF to JPG conversion using PHP

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

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

它似乎也從閱讀其他職位,GhostScript的更快呢?

3

根據this.jpg文件格式爲JPEG

注1

$file變量是一個對象SplFileInfo,但你總是使用它像一個字符串。在RecursiveDirectoryIterator的構造函數中使用RecursiveDirectoryIterator::CURRENT_AS_PATHNAME標誌,成爲一個真正的字符串。

注2

您可以RegexIterator過濾迭代器條目,f.ex(1後注):new RegexIterator($recursiveIteratorIterator, '/\.pdf$/')。或者,您也可以使用GlobIterator來搜索PDF文件。

+0

感謝你的幫助+1 .. – FlyingCat