[英]Images are replaced with blank white space while converting pdf to lower version (1.4 ) using ghostscript
[英]Converting PDF to Images using PHP(ghostscript) taking too long
我有一個PHP腳本正在將pdf文件轉換為一系列jpeg圖像。
腳本如何實現此目的:
- Download pdf to local server.
- Create folders to place jpeg images, one folder for large images and one for small images.
- Extract images from pdfs to correct folders.
- Go through each of the files in the large folder and scale images to 1000 width.
這是我正在使用的代碼的細分。
$outputfile = "filename";
$cmd = "wget -q \"$url\" -O books/$outputfile.pdf";
exec($cmd);
if(!is_dir("books/$outputfile")) mkdir("books/$outputfile");
if(!is_dir("books/large/")) mkdir("books/large/");
if(!is_dir("books/large/$outputfile")) mkdir("books/large/$outputfile");
set_time_limit(9000);
......................................................................
/* Skipped Code to figure out with & height of pdf: $width, $height */
......................................................................
/* Extract Images from PDF, once in a large size (first) and another at its original size */
exec("'gs' -o books/large/$outputfile/$outputfile-%06d.jpg -dDEVICEWIDTHPOINTS=$width -dDEVICEHEIGHTPOINTS=$height -dFIXEDMEDIA=true -dSAFER -dBATCH -dNOPAUSE -sDEVICE=jpeg -dPDFFitPage=true -dUseCropBox=true -r300 -dJPEGQ=100 -dTextAlphaBits=4 'books/$outputfile.pdf'",$output1);
exec("'gs' -o books/$outputfile/$outputfile-%06d.jpg -dDEVICEWIDTHPOINTS=$width -dDEVICEHEIGHTPOINTS=$height -dFIXEDMEDIA=true -dSAFER -dBATCH -dNOPAUSE -sDEVICE=jpeg -dPDFFitPage=true -dUseCropBox=true -dJPEGQ=100 -dTextAlphaBits=4 'books/$outputfile.pdf'",$output2);
$directory = "/var/www/html/pdf/books/large/$outputfile/";
$d = dir($directory);
chdir($directory);
/* Scale image to be 1000px wide and auto height */
$largewidth = 1000;
$scale = 1000 / intVal($width);
$largeheight = intVal($height) * $scale;
while($entry = $d->read()) {
if($entry != "." && $entry != "..") {
$size = getimagesize($entry);
$fp = fopen($entry, "rb");
if ($size && $fp) {
$swidth = 1000;
$scale = 1000 / intVal($size[0]);
$sheight = intVal(intVal($size[1]) * $scale);
$dimg = imagecreatetruecolor($swidth, $sheight);
$simg = imagecreatefromjpeg($entry);
imagecopyresampled($dimg,$simg,0,0,0,0,$swidth,$sheight,$size[0],$size[1]);
imagejpeg($dimg,$entry,85);
}
else {
echo "fail";
}
}
}
$d->close();
問題在於,將整個pdf轉換為一系列圖像大約需要一個小時。 pdf通常為300至500頁。
你們認為此代碼中有什么我可以做得更好的嗎?
最耗時的是在文件末尾瀏覽大文件夾中的每個圖像並將其縮放到1000寬度。
另外,我在該服務器上安裝任何新的php擴展名的訪問權限也很有限,因此我認為imagemagick也不可行。
謝謝
由於您說大部分時間都花在縮放圖像上,因此您可能希望讓Ghostscript生成所需大小的圖像,而不是事后縮放圖像。
同樣縮放JPEG圖像很可能會導致出現偽像。 如果必須縮放,在最后一步之前應避免使用JPEG。
請注意,我對PHP一無所知,因此無法真正對該腳本發表評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.