1、首先安裝imagemagick
去 http://mirror.aarnet.edu.au/pub/imagemagick/ 尋找最新版本
我的是 http://mirror.aarnet.edu.au/pub/imagemagick/ImageMagick-6.9.10-49.tar.gz
wget ftp://mirror.aarnet.edu.au/pub/imagemagick/ImageMagick-6.9.10-49.tar.gz
tar -xzvf ImageMagick-6.9.10-49.tar.gz
cd ImageMagick-6.9.10-49
./configure --prefix=/usr/local/imagemagick
make
make install
2、安裝Imagick
去 http://pecl.php.net/package/imagick 尋找最新版本
例如:http://pecl.php.net/get/imagick-3.4.4.tgz
wget http://pecl.php.net/get/imagick-3.4.4.tgz
tar -xzvf imagick-3.4.4.tgz
cd imagick-3.4.4
phpize
./configure --with-php-config=/usr/local/php/bin/php-config --with-imagick=/usr/local/imagemagick
make
make install
make install 執行完的結果:
Installing shared extensions: /usr/local/data/php/lib/php/extensions/no-debug-non-zts-20131226/
Installing header files: /usr/local/data/php/include/php/
imagick.so 被生成到/usr/local/data/php/lib/php/extensions/no-debug-non-zts-20131226/
接下來我們把imagick.so添加到php.ini然後重啓PHP 就可以看見我們的環境中已經安裝上依賴啦~
但是我接下來的運行卻不順利,通過報錯得知是ghostscript版本過低 處理不了,那麼我們也安裝最新版
3.1、替換最新版(之前沒有安裝ghostscript的小夥伴看3.2)
照例去尋找最新版:https://www.ghostscript.com/download/gsdnld.html
獲取自己PHP可用的版本
wget https://github.com/ArtifexSoftware/ghostpdl-downloads/releases/download/gs927/ghostscript-9.27-linux-x86_64.tgz
tar -xzvf ghostscript-9.27-linux-x86_64.tgz
cd ghostscript-9.27-linux-x86_64
//這個時候文件夾下的Ghostscript 9.27 for Linux x86是可以直接使用的,我們去替換掉/usr/bin下面的gs就可以了
mv ./Ghostscript 9.27 for Linux x86 /usr/bin/gs
3.2、安裝最新版
尋找最新版:https://github.com/ArtifexSoftware/ghostpdl-downloads/releases
wget https://github.com/ArtifexSoftware/ghostpdl-downloads/releases/download/gs927/ghostscript-9.27.tar.gz
tar -xzvf ghostscript-9.27.tar.gz
cd ghostscript-9.27
./configure --prefix=/usr/bin
make
make install
4、PHP代碼運用:
/**
* pdfToJpg
* @param $pdfPath 待處理的PDF文件路徑
* @param $path 待保存的圖片路徑
* @return 保存好的圖片路徑和文件名
*/
public function pdfToJpg($pdfPath,$Path){
//判斷是否安裝imagick
if(!extension_loaded('imagick')){
return false;
}
//判斷pdf是否存在
if(!file_exists($pdfPath)){
return false;
}
//實例化imagick
$IM = new imagick();
$IM->setResolution(120,120);
$IM->setCompressionQuality(100);
$IM->readImage($pdfPath);
//添加白色底色
$IM->borderImage(new ImagickPixel('white'),1,1);
//只生成最後一頁
//$IM->setImageFormat('jpg');
//$Filename = $Path.'/'.md5(time()).'.jpg';
//if($IM->writeImage($Filename) == true){
// $Return = $Filename;
//}
//每頁都生成
foreach ($IM as $Key => $Var){
$Var->setImageFormat('png');
$Filename = $Path.'/'.md5($Key.time()).'.png';
if($Var->writeImage($Filename) == true){
$Return[] = $Filename;
}
}
return $Return;
}
以上就是centos linux下使用PHP利用imagick截取pdf生成圖片的小小案例啦~