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

IMagick is a native PHP extension to create and modify images using the ImageMagick API. ImageMagick Studio LLC did not write nor does it maintain the IMagick extension, however, IMagick users are welcome to discuss the extension here.
Post Reply
Peter3818
Posts: 2
Joined: 2017-08-16T11:39:56-07:00
Authentication code: 1151

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

Post by Peter3818 » 2017-08-16T11:47:33-07:00

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!

snibgo
Posts: 9402
Joined: 2010-01-23T23:01:33-07:00
Authentication code: 1151
Location: England, UK

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

Post by snibgo » 2017-08-16T12:35:15-07:00

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.
snibgo's IM pages: im.snibgo.com

Peter3818
Posts: 2
Joined: 2017-08-16T11:39:56-07:00
Authentication code: 1151

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

Post by Peter3818 » 2017-08-17T04:06:50-07:00

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.

Post Reply