2

I am having an issue with imagick php library.

I am doing a recursive search in my file system and look for any pdf files.

    $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);
            }
        }
    }

However, I am getting an error saying

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");

However, if I replace my $im = new Imagick($file) with $im = new Imagick('/test/project/test1.pdf'), the error is gone.

I don't know why this is happening. Can someone give me a hint for this issue? Thanks so much

FlyingCat
  • 14,036
  • 36
  • 119
  • 198

3 Answers3

3

According to this, the .jpg files' format is JPEG.

Note 1:

Your $file variable is an object SplFileInfo, but you are using it always like a string. Use RecursiveDirectoryIterator::CURRENT_AS_PATHNAME flag in RecursiveDirectoryIterator's constructor, to be a real string.

Note 2:

You can filter the iterator entries with RegexIterator, f.ex.: new RegexIterator($recursiveIteratorIterator, '/\.pdf$/') (after Note 1). Or, you can use GlobIterator too for searching only pdf files.

pozs
  • 34,608
  • 5
  • 57
  • 63
1

As @pozs pointed out

Note 1: Your $file variable is an object SplFileInfo, but you are using it always like a string.

Here's a code snippet which gets you the filename as string and has an optimized method to get the file extension:

<?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
            }
        }
Rolando Isidoro
  • 4,983
  • 2
  • 31
  • 43
0

Maybe try this approach from : PDF to JPG conversion using PHP

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

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

It also seems from reading other posts that GhostScript is faster?

Community
  • 1
  • 1
Revent
  • 2,091
  • 2
  • 18
  • 33