使用PHP(ghostscript)将PDF转换为图像需要太长时间


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一无所知,所以我不能对脚本进行注释。