Page 1 of 1

Converting a multi-page pdf to multiple JPG images with Imagick and PHP

Posted: 2017-08-16T11:47:33-07:00
by Peter3818
I have a small script for creating jpg images from an uploaded multi-paged pdf file ($uploadfile) with Imagick:

Code: Select all

$imagick = new imagick();
$imagick->setResolution(600, 600);
$imagick->readImage($uploadfile);
$imagick->setImageFormat('jpg');
$pages = (int)$imagick->getNumberImages();
foreach($imagick as $i=>$imagick) {
    $imagick->writeImage($uploadfile. " page ". ($i+1) ." of ".  $pages.".jpg");
}
$imagick->clear();
unlink ($uploadfile);
This works fine for a 1 or 2 paged pdf-document, but gives an error with 3 or more pages:

Code: Select all

[lsapi:error] Backend fatal error: PHP Fatal error:  Uncaught exception 'ImagickException' with message 'Failed to read the file' in /index.php:152\nStack trace:\n#0 /index.php(152): Imagick->readimage('...')\n#1 {main}\n  thrown in /index.php on line 152\n
Line 152 mentioned in the error log is:

Code: Select all

$imagick->readImage($uploadfile);
Thank you in advance!

Re: Converting a multi-page pdf to multiple JPG images with Imagick and PHP

Posted: 2017-08-16T12:35:15-07:00
by snibgo
Difficult to guess. I suggest you chop out everything else, to check the error really is in reading the PDF. Perhaps you are running out of memory. How many page is it, and how large is each page? 8*11 inches at 600 dpi, at 8 bytes per pixel, is 253 MB per page.

Re: Converting a multi-page pdf to multiple JPG images with Imagick and PHP

Posted: 2017-08-17T04:06:50-07:00
by Peter3818
Thank you, snibgo. It was a memory problem.

I changed the code to:

Code: Select all

$im = new imagick($uploadfile);
$pages = $im->getNumberImages();
if ($pages < 3) { $resolution = 600; } else { $resolution = floor(sqrt(1000000/$pages)); }
$imagick = new imagick();
$imagick->setResolution($resolution, $resolution);
$imagick->readImage($uploadfile);
$imagick->setImageFormat('jpg');
foreach($imagick as $i=>$imagick) { $imagick->writeImage($uploadfile. " page ". ($i+1) ." of ".  $pages.".jpg"); }
$imagick->clear();
Now it works fine.