I want to convert a downloded pdf file to an image via PHP. For this purpose, I am using Imagemagick extension for PHP. The problem is that if I download the pdf file via file_get_contents function, I cannot create a Imagemagic object with this downloaded content. Here is the code:
<?php
$url = "pdf webaddress";
$pdfData = file_get_contents($url);
try
{
$img = new Imagick($pdfData);
$img->setResolution(480,640);
$img->setImageFormat("jpeg");
$img->writeImage("test.jpeg");
}
catch(Exception $e)
{
echo $e->getMessage();
}
?>
I am getting the following error:
Unable to read the file: %PDF-1.6 %גדֿ׃ 7 0 obj <> endobj 86 0 obj <>/Filter/FlateDecode/ID[]/Index[7 146]/Info 6 0 R/Length 257/Prev 592751/Root 8 0 R/Size 153/Type/XRef/W[1 3 1]>>stream h�bbd
`bׁ‘6 ’9DעƒH
Now, if I read in the locally stored pdf file, everything works fine. The code is:
$image = "output.png";
$img = new Imagick("path to pdf file");
$img->setResolution(480,640);
$img->setImageFormat("jpeg");
$img->writeImage("test.jpeg");
Any suggestions, help is appreciated.
From the ImageMagick PHP extension documentation page, the
Imagickconstructor needs a filename parameters which can either be a local file or a URL. :You should pass the URL directly, without
file_get_contents, PHP file streams are pretty powerful.An other solution for you would be to store the file locally (see
tempnam()andfile_put_contents), but if you don’t use it for anything else than converting it to an image it’s pretty useless :