Imagemagick convert pdf to jpeg

1k Views Asked by At

I am getting an error code when using this code to convert my pdf to jpg. I haven't use imagemagick before, so I'm not sure what I'm doing wrong.

The code i am using:

        $im = new Imagick();
        $im->setResolution(300,300);
        $im->readimage('artwork/$file_name'); 
        $im->setImageFormat('jpeg');    
        $im->writeImage('artwork/jpeg/$file_name'); 
        $im->clear(); 
        $im->destroy();

The error i am getting:

Fatal error: Uncaught exception 'ImagickException' with message 'unable to open image `@artwork/$file_name': No such file or directory @ blob.c/OpenBlob/2480' in /www/xx/xxxxx/xxxx/xxxx/xx/upload_artwork2.php:58 Stack trace: #0 /www/xx/xxxxx/xxxx/xxxx/xx/upload_artwork2.php(58): Imagick->readimage('@artwork/$file_...') #1 {main} thrown in /www/xx/xxxxx/xxxx/xxxx/xx/upload_artwork2.php on line 58

Is this the best way to do it, is there another way?

2

There are 2 best solutions below

0
On

I changed the code i was using to this and it worked fine. Only problem is that you need to add the .jpg or .pdf when uploading to the database, but works fine otherwise.

            $file_name = basename($file_name, '.pdf');

            // Convert this document
            // Each page to single image
            $img = new imagick('artwork/'.$file_name.'.pdf');

            // Set background color and flatten
            // Prevents black background on objects with transparency
            $img->setImageBackgroundColor('white');
            $img = $img->flattenImages();

            // Set image resolution
            // Determine num of pages
            $img->setResolution(300,300);
            $num_pages = $img->getNumberImages();

            // Compress Image Quality
            $img->setImageCompressionQuality(100);

            // Convert PDF pages to images
            for($i = 0;$i < $num_pages; $i++) {         

                // Set iterator postion
                $img->setIteratorIndex($i);

                // Set image format
                $img->setImageFormat('jpeg');

                // Write Images to temp 'upload' folder     
                $img->writeImage('artwork/'.$file_name.'-'.$i.'.jpg');
6
On

Please verify that your path is working - the error clearly states, that the input file artwork/$file_name does not exist (at the specified location at least).