使用PHP(ghostscript)将PDF转换为图像花费的时间太长
我有一个php脚本,用于将pdf文件转换为一系列jpeg图像 脚本如何实现这一点:使用PHP(ghostscript)将PDF转换为图像花费的时间太长,php,pdf,jpeg,ghostscript,Php,Pdf,Jpeg,Ghostscript,我有一个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 th
- 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一无所知,因此无法对脚本进行评论