ImageMagick PHP: Converting a PDF to Image and displaying without saving.
Using ImageMagick with PHP is extremely simple. However there aren’t always answers online for more specific conversions.
Most examples use server commands in an exec() function. However, this is unwieldy and if your server supports it, PLEASE install the php module for ImageMagick. This gives you access to the library right in your code.
$image = new Imagick();
With this class, it makes image modifications so much easier. I needed to take PDF and convert it to an image. Instead of saving it, I wanted it to only display on page load. First you have to load the PDF into the class. After that, the image conversion is a cinch.
$pdf = '/pdf/mypdf.pdf[0]';
$image = new Imagick($pdf);
$image->resizeImage( 200, 200, imagick::FILTER_LANCZOS, 0);
$image->setImageFormat( "png" );
The “[0]” in the pdf path is telling ImageMagick to convert the first page of the pdf. You will have to run this conversion for each page if you want the whole pdf.
Now if we wanted to save it would be easy.
$image->writeImage('pdfAsImage.png');
BUT in this case I wanted to just display the converted image. Luckily, the class has a function named getImageBlob() which will serve you back the raw data of an image. We can take that raw data and put it right in an image tag with some descriptors. My final code:
$pdf = '/pdf/mypdf.pdf[0]';
$image = new Imagick($pdf);
$image->resizeImage( 200, 200, imagick::FILTER_LANCZOS, 0);
$image->setImageFormat( "png" );
$thumbnail = $image->getImageBlob();
echo "
";