Dan
Dan

Reputation: 9468

Imagemagick error when trying to load file

I am trying to create a jpg preview of a pdf file as outlined in this question: How do I convert a PDF document to a preview image in PHP?

The relevant code to do so is:

$im = new imagick('file.pdf[0]');
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
echo $im;

I am running this on my localhost on a pdf file but get the error:

Fatal error: Uncaught exception 'ImagickException' with message 'Imagick::__construct(): HTTP request failed! HTTP/1.0 400 Bad Request '

The error is being triggered here:

$im = new imagick(build_url('uploads/files/'.$file_data['file_name'].'[0]'));

This is the same as the first line in the example code above, and I am providing the full url path to the pdf file, when I echo that it provides the correct path

http://oursite.localhost:8888/uploads/files/file_name.pdf[0]

Does anyone know what is causing this error? Thank you!

Upvotes: 0

Views: 3874

Answers (1)

Vladimir Bashkirtsev
Vladimir Bashkirtsev

Reputation: 1354

ImageMagick is quite bad as HTTP client. Pull down your image first, then feed it into ImageMagick as blob

Use following:

 $image = file_get_contents(build_url('uploads/files/'.$file_data['file_name'].'[0]'));
 if ($image !== false)
   {
     $im = new imagick();
     $im->readImageBlob($image);
   }
 else
   {
     echo "Uh-oh... Cannot load image from URL!";
   }

Upvotes: 5

Related Questions