Getting invalid file name error while converting first pdf to jpg page

I use imagick to convert pdf to jpg to script I have ... it works fine if I give the direct path to the downloaded pdf without the specified page, but when I add [0] to the end of the file path to indicate that I I just want to read the first page, it gives the following error:

"Fatal error: ImagickException exception with message 'Invalid file name provided' Imagick-> readImage ()"

I also tried using '/path/to/file.pdf[0]' directly in the constructor with no luck, but without a page qualifier, which also works fine.

According to the documentation ... this should work. What am I doing wrong here?

 $doc_preview = new Imagick(); $doc_preview->setResolution(180,180); $doc_preview->readImage('/path/to/file.pdf[0]'); $doc_preview->setImageFormat('jpeg'); $doc_preview->writeImage('/path/to/file.jpg'); $doc_preview->clear(); $doc_preview->destroy(); 

UPDATE: I should have mentioned that I am using HHVM. Not sure if this will affect this case ... but me.

UPDATE2: I opened the problem in the github HHVM repository. I hope they fix this error ... until then, the answer I have outlined correctly below is a decent (albeit hacky) workaround.

+5
source share
3 answers

OK ... so the (hacky kind of) way to fix this in my situation is to use fopen() and then use setIteratorIndex(0) , which is IMPOSSIBLE. But for those who have the same problem ... there you go!

 $pdf_handle = fopen('/path/to/file.pdf', 'rb'); $doc_preview = new Imagick(); $doc_preview->setResolution(180,180); $doc_preview->readImageFile($pdf_handle); $doc_preview->setIteratorIndex(0); $doc_preview->setImageFormat('jpeg'); $doc_preview->writeImage('/path/to/file.jpg'); $doc_preview->clear(); $doc_preview->destroy(); 
+3
source

I do not have an image on my computer, but I can guess what the problem is. The problem is that when you open a PDF file with part of the page, you cannot include a directory path line that includes a slash. I think because I read the readImage function page from php.net here http://php.net/manual/en/imagick.readimage.php , and they do not include the directory path there, so I suppose it's a glitch, but continues. You should try changing the directory to a PDF using chdir() ( http://php.net/manual/en/function.chdir.php ), and then try the same function as this $doc_preview->readImage('file.pdf[0]'); , without a directory path. Most likely it will work. Some APIs have glitches, and you need to get around them.

+1
source

readImage () requires $ filename to be an absolute path.

If you want to use a relative path, use realpath () on it, which turns the relative path into an absolute path to the file.

Instead

 $imagick->readImage('/path/to/file.pdf[0]'); 

try

 $imagick->readImage(realpath("/path/to/file.pdf")."[0]"); 
+1
source

Source: https://habr.com/ru/post/1212472/


All Articles