You are here

class MediaPdfThumbnailImagickManager in Media PDF Thumbnail 8

Same name and namespace in other branches
  1. 8.4 src/Manager/MediaPdfThumbnailImagickManager.php \Drupal\media_pdf_thumbnail\Manager\MediaPdfThumbnailImagickManager
  2. 8.2 src/Manager/MediaPdfThumbnailImagickManager.php \Drupal\media_pdf_thumbnail\Manager\MediaPdfThumbnailImagickManager
  3. 8.3 src/Manager/MediaPdfThumbnailImagickManager.php \Drupal\media_pdf_thumbnail\Manager\MediaPdfThumbnailImagickManager

Class MediaPdfThumbnailImagickManager.

@package Drupal\media_pdf_thumbnail\Manager

Hierarchy

Expanded class hierarchy of MediaPdfThumbnailImagickManager

File

src/Manager/MediaPdfThumbnailImagickManager.php, line 12

Namespace

Drupal\media_pdf_thumbnail\Manager
View source
class MediaPdfThumbnailImagickManager {

  /**
   * Generate image from PDF file.
   *
   * @param string $source
   *   File source.
   * @param string $target
   *   File target.
   *
   * @return string
   *   File path.
   *
   * @throws \ImagickException
   */
  public function generateImage($source, $target) {
    $target = dirname($source) . DIRECTORY_SEPARATOR . $target;
    $im = new Imagick($source . "[0]");
    $im
      ->setimageformat("png");
    $im
      ->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
    $im
      ->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
    $im
      ->setImageBackgroundColor('white');
    $im
      ->thumbnailimage(2480, 3508);
    $im
      ->writeimage($target);
    $fileName = $im
      ->getImageFilename();
    $im
      ->clear();
    $im
      ->destroy();
    return $this
      ->moveImageToThumbnailFolder($fileName);
  }

  /**
   * Move thumbnail image file to thumbnail folder.
   *
   * @param string $filePath
   *   File path.
   *
   * @return string|null
   *   File image path.
   */
  protected function moveImageToThumbnailFolder($filePath) {
    if (file_exists($filePath)) {
      $filePathArray = explode('/', $filePath);
      if (!empty($filePathArray)) {
        $parentFolder = $filePathArray[count($filePathArray) - 2];
        $fileName = $filePathArray[count($filePathArray) - 1];
        if ($parentFolder) {
          $destination = 'public://styles/thumbnail/public/' . $parentFolder . '/';
          if (file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
            if (file_unmanaged_move($filePath, $destination, FILE_EXISTS_REPLACE)) {
              return $destination . $fileName;
            }
          }
        }
      }
    }
    return NULL;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
MediaPdfThumbnailImagickManager::generateImage public function Generate image from PDF file.
MediaPdfThumbnailImagickManager::moveImageToThumbnailFolder protected function Move thumbnail image file to thumbnail folder.