我有一个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也是不可能的。
谢谢
答案 0 :(得分:1)
由于您说大部分时间都花在缩放图像上,因此您可能希望Ghostscript以所需的大小生成图像,而不是之后进行缩放。
同样缩放JPEG图像很可能会导致人工制品出现。如果你必须扩展,你应该避免使用JPEG直到最后一步。
请注意,我对PHP一无所知,因此我无法对脚本发表评论。