You are here

public function MediaThumbnailVideo::createThumbnail in Media Thumbnails Video 8

Create a thumbnail file using the passed source uri.

Parameters

string $sourceUri: The uri of the source file, like 'public://invoices/inv001.pdf'.

Return value

\Drupal\file\Entity\File|null The new managed file object for the generated thumbnail.

Overrides MediaThumbnailInterface::createThumbnail

File

src/Plugin/MediaThumbnail/MediaThumbnailVideo.php, line 29

Class

MediaThumbnailVideo
Media thumbnail plugin for videos.

Namespace

Drupal\media_thumbnails_video\Plugin\MediaThumbnail

Code

public function createThumbnail($sourceUri) {
  $config = $this->config
    ->getEditable('media_thumbnails_video.settings');
  $path = $this->fileSystem
    ->realpath($sourceUri);
  try {

    // Create ffmpeg container.
    $ffmpeg = FFMpeg::create([
      'ffmpeg.binaries' => $config
        ->get('ffmpeg'),
      'ffprobe.binaries' => $config
        ->get('ffprobe'),
      'timeout' => $config
        ->get('timeout'),
      'ffmpeg.threads' => $config
        ->get('threads'),
    ]);
    try {

      // Try open file form real path.
      $video = $ffmpeg
        ->open($path);
      $thumbnail_path = $path . '.png';
      $width = $this->configuration['width'];
      $video
        ->frame(TimeCode::fromSeconds(1))
        ->save($thumbnail_path);
      if (!empty($width)) {
        $image = imagecreatefrompng($thumbnail_path);
        $image = imagescale($image, $width);
        imagepng($image, $thumbnail_path);
      }

      // Create a managed file object.
      $file = File::create([
        'uri' => $sourceUri . '.png',
        'status' => 1,
      ]);
      try {
        $file
          ->save();
        return $file;
      } catch (EntityStorageException $e) {
        $this->logger
          ->warning(t('Could not create thumbnail file entity.'));
        return NULL;
      }
    } catch (\Exception $e) {
      $this->logger
        ->warning($e
        ->getMessage());
      return NULL;
    }
  } catch (ExecutableNotFoundException $e) {
    $this->logger
      ->warning($e
      ->getMessage());
    return NULL;
  }
}