我們正在轉換PDF頁面的多個單個圖像。我們在stackoverflow中找到了一段代碼,並將其轉換爲一個服務類。我們安裝了Imagick,它也顯示在phpinfo()中。但是,在我們的laravel應用程序5.2版中,我們遇到了以下錯誤。Laravel 5.2:類Imagick沒有找到
ReflectionException in Container.php line 798:
Class Imagick does not exist
我們測試了我們的代碼在laravel環境之外,它的工作就像一個魅力。沒有這樣的錯誤被拋出。我們還運行了以下命令來檢查Imagick
php -i | grep -i imagick
,這是輸出
/etc/php5/cli/conf.d/20-imagick.ini,
imagick
imagick module => enabled
imagick module version => 3.4.3RC1
imagick classes => Imagick, ImagickDraw, ImagickPixel, ImagickPixelIterator
Imagick compiled with ImageMagick version => ImageMagick 6.7.7-10 2016-06-01 Q16 http://www.imagemagick.org
Imagick using ImageMagick library version => ImageMagick 6.7.7-10 2016-06-01 Q16 http://www.imagemagick.org
imagick.locale_fix => 0 => 0
imagick.progress_monitor => 0 => 0
imagick.skip_version_check => 0 => 0
一切似乎是正確的。它在Laravel外工作,但不在laravel。我不知道什麼是錯的。我們是否必須配置Laravel來使用Imagick?
這裏是我們的服務類,我們使用
<?php
namespace App\Services\Utilities;
use Imagick;
class PdfToImageService
{
/**
* Destination folder where images will be saved
* @var string
*/
protected $destination = 'images/users/';
/**
* Injecting dependencies
*
* @param Imagick $imagick
*/
function __construct(Imagic $imagick)
{
$this->imagick = $imagick;
}
/**
* Convert pdf having multiple pages to multiple single images
*
* 1. Strip document extension
* 2. Convert this document
* 3. Set background color and flatten. It Prevents black background on objects with transparency
* 4. Set image resolution
* 5. Determine number of pages
* 6. Compress Image Quality
* 7. Generate images from each pdf page
* 8. Destroy current imagick session
*
* @param string $fileName
* @return array $convertedImageNames
*/
public function createImages($fileName)
{
$fileName = basename($fileName);
$this->imagick->readImage($fileName);
$this->imagick->setImageBackgroundColor('white');
$this->imagick->setResolution(300,300);
$this->imagick->setImageCompressionQuality(100);
$convertedImageNames = $this->generateImageFromPDFPage(
$fileName, $this->imagick->getNumberImages()
);
$this->imagick->destroy();
return $convertedImageNames;
}
/**
* Loop throught each pdf pages and convert it to image.
* A. Set iterator postion
* B. Set image format
* C. Write Images to destination folder
*
* @param string $fileName
* @param integer $noOfPages
* @return array
*/
private function generateImageFromPDFPage($fileName, $noOfPages)
{
for($i = 0;$i < $noOfPages; $i++) {
$this->imagick->setIteratorIndex($i);
$this->imagick->setImageFormat('jpeg');
$this->imagick->writeImage($this->destination.$fileName.'-'.$i.'.jpg');
$convertedImageNames[$i] = $fileName.'-'.$i.'.jpg';
}
return $convertedImageNames;
}
}
問題可能是命名空間。嘗試在Imagick使用語句前添加\。這可能是Laravel解決錯誤的類在IOC容器,它可能不被理解的全局命名空間中的類 – developernaren