简体   繁体   English

使用ImageMagick将PDF转换为图像

[英]Converting PDF to image with ImageMagick

I want to convert a downloded pdf file to an image via PHP. 我想通过PHP将下载的pdf文件转换为图像。 For this purpose, I am using Imagemagick extension for PHP. 为此,我正在使用Imagemagick扩展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. 问题是,如果我通过file_get_contents函数下载pdf文件,我无法使用此下载内容创建Imagemagic对象。 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 无法读取文件:%PDF-1.6%גדֿ:7 0 obj <> endobj 86 0 obj <> / Filter / FlateDecode / ID [] / Index [7 146] / Info 6 0 R / Length 257 / Prev 592751 /根8 0 R /尺寸153 /类型/外部参照/ W [1 3 1] >>流hbbd `b ׁ'6“9DעƒH

Now, if I read in the locally stored pdf file, everything works fine. 现在,如果我读入本地存储的pdf文件,一切正常。 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 Imagick constructor needs a filename parameters which can either be a local file or a URL. ImageMagick PHP扩展文档页面中Imagick构造函数需要一个文件名参数,可以是本地文件 URL。 :

Paths can include wildcards for file names, or can be URLs. 路径可以包含文件名的通配符,也可以是URL。

You should pass the URL directly, without file_get_contents , PHP file streams are pretty powerful. 您应该直接传递URL,而不使用file_get_contents ,PHP文件流非常强大。

An other solution for you would be to store the file locally (see tempnam() and file_put_contents ), but if you don't use it for anything else than converting it to an image it's pretty useless : 另一个解决方案是在本地存储文件(请参阅tempnam()file_put_contents ),但如果不将其用于除将其转换为图像之外的其他任何内容,那么它就没用了:

$pdfUrl = "...";
$tmpFileName = tempnam(sys_get_temp_dir(), "pdf");
file_put_contents($tmpFileName, file_get_contents($pdfUrl));
// Do your ImageMagick job
unlink($tmpFileName);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM