我有一个使用Imagick的PHP脚本,但是如果用户提供的PDF文件不包含页面或页面没有高度或宽度,则存在NAN错误的风险。我不确定在PDF结构中是否可行。同样,使用大于总页数的jpeg创建jpeg也会导致错误。通常是否可以发送有效的PDF文件包装但没有实际的页面内容?
在下面的函数中,我假设可能有0个高度或0个宽度。并使用代码if($ imH == 0){$ imH = 1;},但是基于假设的代码感觉不对。
该功能的某些部分来自umidjons的文章:https ://gist.github.com/umidjons/11037635
PHP代码:
function genPdfThumbnail ( $src, $targ, $size=256, $page=1 ){
if(file_exists($src) && !is_dir($src)): // source path must be available and cannot be a directory
if(mime_content_type($src) != 'application/pdf'){return FALSE;} // source is not a pdf file returns a failure
$sepa = '/'; // using '/' as path separation for nfs on linux.
$targ = dirname($src).$sepa.$targ;
$size = intval($size); // only use as integer, default is 256
$page = intval($page); // only use as integer, default is 1
$page--; // default page 1, must be treated as 0 hereafter
if ($page<0){$page=0;} // we cannot have negative values
$img = new Imagick($src."[$page]");
$imH = $img->getImageHeight();
$imW = $img->getImageWidth();
if ($imH==0) {$imH=1;} // if the pdf page has no height use 1 instead
if ($imW==0) {$imW=1;} // if the pdf page has no width use 1 instead
$sizR = round($size*(min($imW,$imH)/max($imW,$imH))); // relative pixels of the shorter side
$img -> setImageColorspace(255); // prevent image colors from inverting
$img -> setImageBackgroundColor('white'); // set background color before flatten
$img = $img->flattenImages(); // prevent black zones on transparency in pdf
$img -> setimageformat('jpeg');
调用该函数,例如:
$newthumb = genPdfThumbnail('/nfs/vsp/server/u/user/public_html/any.pdf','thumbs/any.p01.jpg',150,'01');
慕神8447489
慕田峪7331174