2012-02-10 139 views
24

我用豆蔻腳本將PDF轉換爲JPG。這有效,但質量很差。PDF格式轉換爲JPEG PHP和ImageMagick的

腳本:

$im = new imagick('document.pdf[ 0]'); 
$im->setImageColorspace(255); 
$im->setResolution(300, 300); 
$im->setCompressionQuality(95); 
$im->setImageFormat('jpeg'); 
$im->writeImage('thumb.jpg'); 
$im->clear(); 
$im->destroy(); 

還有一兩件事,我想保持PDF的原始大小,但轉換裁剪JPG大小。

回答

37

它可以通過setResolution可以做到,但你需要在加載圖像之前做到這一點。 嘗試是這樣的:

// instantiate Imagick 
$im = new Imagick(); 

$im->setResolution(300,300); 
$im->readimage('document.pdf[0]'); 
$im->setImageFormat('jpeg');  
$im->writeImage('thumb.jpg'); 
$im->clear(); 
$im->destroy(); 
+3

看來,在某些情況下,ImageMagick的要求安裝Ghostscript的,因爲否則會拋出一個後記代表世界上爲什麼失敗的錯誤 – Zsolti 2013-11-06 12:13:31

+0

做setResolution和setImageResolution做不同的事情,並在該文檔相同的描述?謝謝,你完全救了我。 – Hissvard 2017-08-31 14:01:04

5

從PDF產生的圖像的質量可以在PDF閱讀之前設置density(這是DPI)來改變 - 這得到過去ghostscript (gs)其下方的光柵化PDF。在雙您需要的密度得到一個好的結果,超採樣,並使用resample找回所需的DPI。如果您需要RGB JPEG,請記得將colorspace更改爲RGB。

一個典型的命令行版本爲convert可能是:

convert -density 600 document.pdf[0] -colorspace RGB -resample 300 output.jpg 

如果你需要裁剪,重採樣之後的-shave命令通常是明智的,如果圖像在頁面中居中。

至於PHP IMagick extension,好吧,我從來沒有親自使用它 - 所以我不確定你如何指定文件讀取提示,但我希望它是可能的。

3
$im = new imagick(); 

//this must be called before reading the image, otherwise has no effect 

$img->setResolution(200,200); 

//read the pdf 

$img->readImage("{$pdf_file}[0]"); 
0

點擊here瞭解更多詳情。試試這個:

HTML

<html> 

    <body> 

    <form action="ConvertPdfToImg.php" enctype="multipart/form-data" method="post" name="f1"> 

     <input id="templateDoc" name="templateDoc" type="file" /> 

     <input type="submit" /> 

    </form> 

    </body> 

</html> 

PHP

$pdfAbsolutePath = __DIR__."/test.pdf"; 

if (move_uploaded_file($_FILES['templateDoc']["tmp_name"], $pdfAbsolutePath)) { 

     $im    = new imagick($pdfAbsolutePath); 

     $noOfPagesInPDF = $im->getNumberImages(); 

     if ($noOfPagesInPDF) { 

      for ($i = 0; $i < $noOfPagesInPDF; $i++) { 

       $url = $pdfAbsolutePath.'['.$i.']'; 

       $image = new Imagick($url); 

       $image->setImageFormat("jpg"); 

       $image->writeImage(__DIR__."/".($i+1).'-'.rand().'.jpg'); 

      } 

      echo "All pages of PDF is converted to images"; 

     } 
     echo "PDF doesn't have any pages"; 

} 
+0

你完全忽略了一點,所有申請的處理是完全無關的問題。你應該總是清楚地指出你正在指向你自己的博客。 – 2017-04-26 10:02:02